SemaOpenMP.cpp 435 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024
  1. //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. /// \file
  10. /// \brief This file implements semantic analysis for OpenMP directives and
  11. /// clauses.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "TreeTransform.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclOpenMP.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtOpenMP.h"
  23. #include "clang/AST/StmtVisitor.h"
  24. #include "clang/AST/TypeOrdering.h"
  25. #include "clang/Basic/OpenMPKinds.h"
  26. #include "clang/Basic/TargetInfo.h"
  27. #include "clang/Lex/Preprocessor.h"
  28. #include "clang/Sema/Initialization.h"
  29. #include "clang/Sema/Lookup.h"
  30. #include "clang/Sema/Scope.h"
  31. #include "clang/Sema/ScopeInfo.h"
  32. #include "clang/Sema/SemaInternal.h"
  33. using namespace clang;
  34. //===----------------------------------------------------------------------===//
  35. // Stack of data-sharing attributes for variables
  36. //===----------------------------------------------------------------------===//
  37. namespace {
  38. /// \brief Default data sharing attributes, which can be applied to directive.
  39. enum DefaultDataSharingAttributes {
  40. DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
  41. DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
  42. DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
  43. };
  44. /// \brief Stack for tracking declarations used in OpenMP directives and
  45. /// clauses and their data-sharing attributes.
  46. class DSAStackTy final {
  47. public:
  48. struct DSAVarData final {
  49. OpenMPDirectiveKind DKind = OMPD_unknown;
  50. OpenMPClauseKind CKind = OMPC_unknown;
  51. Expr *RefExpr = nullptr;
  52. DeclRefExpr *PrivateCopy = nullptr;
  53. SourceLocation ImplicitDSALoc;
  54. DSAVarData() {}
  55. };
  56. typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
  57. OperatorOffsetTy;
  58. private:
  59. struct DSAInfo final {
  60. OpenMPClauseKind Attributes = OMPC_unknown;
  61. /// Pointer to a reference expression and a flag which shows that the
  62. /// variable is marked as lastprivate(true) or not (false).
  63. llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
  64. DeclRefExpr *PrivateCopy = nullptr;
  65. };
  66. typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
  67. typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
  68. typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
  69. typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
  70. /// Struct that associates a component with the clause kind where they are
  71. /// found.
  72. struct MappedExprComponentTy {
  73. OMPClauseMappableExprCommon::MappableExprComponentLists Components;
  74. OpenMPClauseKind Kind = OMPC_unknown;
  75. };
  76. typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
  77. MappedExprComponentsTy;
  78. typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
  79. CriticalsWithHintsTy;
  80. typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
  81. DoacrossDependMapTy;
  82. struct SharingMapTy final {
  83. DeclSAMapTy SharingMap;
  84. AlignedMapTy AlignedMap;
  85. MappedExprComponentsTy MappedExprComponents;
  86. LoopControlVariablesMapTy LCVMap;
  87. DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
  88. SourceLocation DefaultAttrLoc;
  89. OpenMPDirectiveKind Directive = OMPD_unknown;
  90. DeclarationNameInfo DirectiveName;
  91. Scope *CurScope = nullptr;
  92. SourceLocation ConstructLoc;
  93. /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
  94. /// get the data (loop counters etc.) about enclosing loop-based construct.
  95. /// This data is required during codegen.
  96. DoacrossDependMapTy DoacrossDepends;
  97. /// \brief first argument (Expr *) contains optional argument of the
  98. /// 'ordered' clause, the second one is true if the regions has 'ordered'
  99. /// clause, false otherwise.
  100. llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
  101. bool NowaitRegion = false;
  102. bool CancelRegion = false;
  103. unsigned AssociatedLoops = 1;
  104. SourceLocation InnerTeamsRegionLoc;
  105. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  106. Scope *CurScope, SourceLocation Loc)
  107. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  108. ConstructLoc(Loc) {}
  109. SharingMapTy() {}
  110. };
  111. typedef SmallVector<SharingMapTy, 4> StackTy;
  112. /// \brief Stack of used declaration and their data-sharing attributes.
  113. StackTy Stack;
  114. /// \brief true, if check for DSA must be from parent directive, false, if
  115. /// from current directive.
  116. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  117. Sema &SemaRef;
  118. bool ForceCapturing = false;
  119. CriticalsWithHintsTy Criticals;
  120. typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
  121. DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
  122. /// \brief Checks if the variable is a local for OpenMP region.
  123. bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
  124. public:
  125. explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
  126. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  127. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  128. bool isForceVarCapturing() const { return ForceCapturing; }
  129. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  130. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  131. Scope *CurScope, SourceLocation Loc) {
  132. Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
  133. Stack.back().DefaultAttrLoc = Loc;
  134. }
  135. void pop() {
  136. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
  137. Stack.pop_back();
  138. }
  139. void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
  140. Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
  141. }
  142. const std::pair<OMPCriticalDirective *, llvm::APSInt>
  143. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  144. auto I = Criticals.find(Name.getAsString());
  145. if (I != Criticals.end())
  146. return I->second;
  147. return std::make_pair(nullptr, llvm::APSInt());
  148. }
  149. /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
  150. /// add it and return NULL; otherwise return previous occurrence's expression
  151. /// for diagnostics.
  152. Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
  153. /// \brief Register specified variable as loop control variable.
  154. void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
  155. /// \brief Check if the specified variable is a loop control variable for
  156. /// current region.
  157. /// \return The index of the loop control variable in the list of associated
  158. /// for-loops (from outer to inner).
  159. LCDeclInfo isLoopControlVariable(ValueDecl *D);
  160. /// \brief Check if the specified variable is a loop control variable for
  161. /// parent region.
  162. /// \return The index of the loop control variable in the list of associated
  163. /// for-loops (from outer to inner).
  164. LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
  165. /// \brief Get the loop control variable for the I-th loop (or nullptr) in
  166. /// parent directive.
  167. ValueDecl *getParentLoopControlVariable(unsigned I);
  168. /// \brief Adds explicit data sharing attribute to the specified declaration.
  169. void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
  170. DeclRefExpr *PrivateCopy = nullptr);
  171. /// \brief Returns data sharing attributes from top of the stack for the
  172. /// specified declaration.
  173. DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  174. /// \brief Returns data-sharing attributes for the specified declaration.
  175. DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
  176. /// \brief Checks if the specified variables has data-sharing attributes which
  177. /// match specified \a CPred predicate in any directive which matches \a DPred
  178. /// predicate.
  179. DSAVarData hasDSA(ValueDecl *D,
  180. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  181. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  182. bool FromParent);
  183. /// \brief Checks if the specified variables has data-sharing attributes which
  184. /// match specified \a CPred predicate in any innermost directive which
  185. /// matches \a DPred predicate.
  186. DSAVarData
  187. hasInnermostDSA(ValueDecl *D,
  188. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  189. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  190. bool FromParent);
  191. /// \brief Checks if the specified variables has explicit data-sharing
  192. /// attributes which match specified \a CPred predicate at the specified
  193. /// OpenMP region.
  194. bool hasExplicitDSA(ValueDecl *D,
  195. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  196. unsigned Level, bool NotLastprivate = false);
  197. /// \brief Returns true if the directive at level \Level matches in the
  198. /// specified \a DPred predicate.
  199. bool hasExplicitDirective(
  200. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  201. unsigned Level);
  202. /// \brief Finds a directive which matches specified \a DPred predicate.
  203. bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
  204. const DeclarationNameInfo &,
  205. SourceLocation)> &DPred,
  206. bool FromParent);
  207. /// \brief Returns currently analyzed directive.
  208. OpenMPDirectiveKind getCurrentDirective() const {
  209. return Stack.back().Directive;
  210. }
  211. /// \brief Returns parent directive.
  212. OpenMPDirectiveKind getParentDirective() const {
  213. if (Stack.size() > 2)
  214. return Stack[Stack.size() - 2].Directive;
  215. return OMPD_unknown;
  216. }
  217. /// \brief Set default data sharing attribute to none.
  218. void setDefaultDSANone(SourceLocation Loc) {
  219. Stack.back().DefaultAttr = DSA_none;
  220. Stack.back().DefaultAttrLoc = Loc;
  221. }
  222. /// \brief Set default data sharing attribute to shared.
  223. void setDefaultDSAShared(SourceLocation Loc) {
  224. Stack.back().DefaultAttr = DSA_shared;
  225. Stack.back().DefaultAttrLoc = Loc;
  226. }
  227. DefaultDataSharingAttributes getDefaultDSA() const {
  228. return Stack.back().DefaultAttr;
  229. }
  230. SourceLocation getDefaultDSALocation() const {
  231. return Stack.back().DefaultAttrLoc;
  232. }
  233. /// \brief Checks if the specified variable is a threadprivate.
  234. bool isThreadPrivate(VarDecl *D) {
  235. DSAVarData DVar = getTopDSA(D, false);
  236. return isOpenMPThreadPrivate(DVar.CKind);
  237. }
  238. /// \brief Marks current region as ordered (it has an 'ordered' clause).
  239. void setOrderedRegion(bool IsOrdered, Expr *Param) {
  240. Stack.back().OrderedRegion.setInt(IsOrdered);
  241. Stack.back().OrderedRegion.setPointer(Param);
  242. }
  243. /// \brief Returns true, if parent region is ordered (has associated
  244. /// 'ordered' clause), false - otherwise.
  245. bool isParentOrderedRegion() const {
  246. if (Stack.size() > 2)
  247. return Stack[Stack.size() - 2].OrderedRegion.getInt();
  248. return false;
  249. }
  250. /// \brief Returns optional parameter for the ordered region.
  251. Expr *getParentOrderedRegionParam() const {
  252. if (Stack.size() > 2)
  253. return Stack[Stack.size() - 2].OrderedRegion.getPointer();
  254. return nullptr;
  255. }
  256. /// \brief Marks current region as nowait (it has a 'nowait' clause).
  257. void setNowaitRegion(bool IsNowait = true) {
  258. Stack.back().NowaitRegion = IsNowait;
  259. }
  260. /// \brief Returns true, if parent region is nowait (has associated
  261. /// 'nowait' clause), false - otherwise.
  262. bool isParentNowaitRegion() const {
  263. if (Stack.size() > 2)
  264. return Stack[Stack.size() - 2].NowaitRegion;
  265. return false;
  266. }
  267. /// \brief Marks parent region as cancel region.
  268. void setParentCancelRegion(bool Cancel = true) {
  269. if (Stack.size() > 2)
  270. Stack[Stack.size() - 2].CancelRegion =
  271. Stack[Stack.size() - 2].CancelRegion || Cancel;
  272. }
  273. /// \brief Return true if current region has inner cancel construct.
  274. bool isCancelRegion() const { return Stack.back().CancelRegion; }
  275. /// \brief Set collapse value for the region.
  276. void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
  277. /// \brief Return collapse value for region.
  278. unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
  279. /// \brief Marks current target region as one with closely nested teams
  280. /// region.
  281. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  282. if (Stack.size() > 2)
  283. Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
  284. }
  285. /// \brief Returns true, if current region has closely nested teams region.
  286. bool hasInnerTeamsRegion() const {
  287. return getInnerTeamsRegionLoc().isValid();
  288. }
  289. /// \brief Returns location of the nested teams region (if any).
  290. SourceLocation getInnerTeamsRegionLoc() const {
  291. if (Stack.size() > 1)
  292. return Stack.back().InnerTeamsRegionLoc;
  293. return SourceLocation();
  294. }
  295. Scope *getCurScope() const { return Stack.back().CurScope; }
  296. Scope *getCurScope() { return Stack.back().CurScope; }
  297. SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
  298. /// Do the check specified in \a Check to all component lists and return true
  299. /// if any issue is found.
  300. bool checkMappableExprComponentListsForDecl(
  301. ValueDecl *VD, bool CurrentRegionOnly,
  302. const llvm::function_ref<
  303. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  304. OpenMPClauseKind)> &Check) {
  305. auto SI = Stack.rbegin();
  306. auto SE = Stack.rend();
  307. if (SI == SE)
  308. return false;
  309. if (CurrentRegionOnly) {
  310. SE = std::next(SI);
  311. } else {
  312. ++SI;
  313. }
  314. for (; SI != SE; ++SI) {
  315. auto MI = SI->MappedExprComponents.find(VD);
  316. if (MI != SI->MappedExprComponents.end())
  317. for (auto &L : MI->second.Components)
  318. if (Check(L, MI->second.Kind))
  319. return true;
  320. }
  321. return false;
  322. }
  323. /// Create a new mappable expression component list associated with a given
  324. /// declaration and initialize it with the provided list of components.
  325. void addMappableExpressionComponents(
  326. ValueDecl *VD,
  327. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  328. OpenMPClauseKind WhereFoundClauseKind) {
  329. assert(Stack.size() > 1 &&
  330. "Not expecting to retrieve components from a empty stack!");
  331. auto &MEC = Stack.back().MappedExprComponents[VD];
  332. // Create new entry and append the new components there.
  333. MEC.Components.resize(MEC.Components.size() + 1);
  334. MEC.Components.back().append(Components.begin(), Components.end());
  335. MEC.Kind = WhereFoundClauseKind;
  336. }
  337. unsigned getNestingLevel() const {
  338. assert(Stack.size() > 1);
  339. return Stack.size() - 2;
  340. }
  341. void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
  342. assert(Stack.size() > 2);
  343. assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
  344. Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
  345. }
  346. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  347. getDoacrossDependClauses() const {
  348. assert(Stack.size() > 1);
  349. if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
  350. auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
  351. return llvm::make_range(Ref.begin(), Ref.end());
  352. }
  353. return llvm::make_range(Stack[0].DoacrossDepends.end(),
  354. Stack[0].DoacrossDepends.end());
  355. }
  356. };
  357. bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
  358. return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
  359. isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
  360. }
  361. } // namespace
  362. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  363. auto *VD = dyn_cast<VarDecl>(D);
  364. auto *FD = dyn_cast<FieldDecl>(D);
  365. if (VD != nullptr) {
  366. VD = VD->getCanonicalDecl();
  367. D = VD;
  368. } else {
  369. assert(FD);
  370. FD = FD->getCanonicalDecl();
  371. D = FD;
  372. }
  373. return D;
  374. }
  375. DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
  376. ValueDecl *D) {
  377. D = getCanonicalDecl(D);
  378. auto *VD = dyn_cast<VarDecl>(D);
  379. auto *FD = dyn_cast<FieldDecl>(D);
  380. DSAVarData DVar;
  381. if (Iter == std::prev(Stack.rend())) {
  382. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  383. // in a region but not in construct]
  384. // File-scope or namespace-scope variables referenced in called routines
  385. // in the region are shared unless they appear in a threadprivate
  386. // directive.
  387. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
  388. DVar.CKind = OMPC_shared;
  389. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  390. // in a region but not in construct]
  391. // Variables with static storage duration that are declared in called
  392. // routines in the region are shared.
  393. if (VD && VD->hasGlobalStorage())
  394. DVar.CKind = OMPC_shared;
  395. // Non-static data members are shared by default.
  396. if (FD)
  397. DVar.CKind = OMPC_shared;
  398. return DVar;
  399. }
  400. DVar.DKind = Iter->Directive;
  401. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  402. // in a Construct, C/C++, predetermined, p.1]
  403. // Variables with automatic storage duration that are declared in a scope
  404. // inside the construct are private.
  405. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  406. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  407. DVar.CKind = OMPC_private;
  408. return DVar;
  409. }
  410. // Explicitly specified attributes and local variables with predetermined
  411. // attributes.
  412. if (Iter->SharingMap.count(D)) {
  413. DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
  414. DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
  415. DVar.CKind = Iter->SharingMap[D].Attributes;
  416. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  417. return DVar;
  418. }
  419. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  420. // in a Construct, C/C++, implicitly determined, p.1]
  421. // In a parallel or task construct, the data-sharing attributes of these
  422. // variables are determined by the default clause, if present.
  423. switch (Iter->DefaultAttr) {
  424. case DSA_shared:
  425. DVar.CKind = OMPC_shared;
  426. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  427. return DVar;
  428. case DSA_none:
  429. return DVar;
  430. case DSA_unspecified:
  431. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  432. // in a Construct, implicitly determined, p.2]
  433. // In a parallel construct, if no default clause is present, these
  434. // variables are shared.
  435. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  436. if (isOpenMPParallelDirective(DVar.DKind) ||
  437. isOpenMPTeamsDirective(DVar.DKind)) {
  438. DVar.CKind = OMPC_shared;
  439. return DVar;
  440. }
  441. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  442. // in a Construct, implicitly determined, p.4]
  443. // In a task construct, if no default clause is present, a variable that in
  444. // the enclosing context is determined to be shared by all implicit tasks
  445. // bound to the current team is shared.
  446. if (isOpenMPTaskingDirective(DVar.DKind)) {
  447. DSAVarData DVarTemp;
  448. for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
  449. I != EE; ++I) {
  450. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  451. // Referenced in a Construct, implicitly determined, p.6]
  452. // In a task construct, if no default clause is present, a variable
  453. // whose data-sharing attribute is not determined by the rules above is
  454. // firstprivate.
  455. DVarTemp = getDSA(I, D);
  456. if (DVarTemp.CKind != OMPC_shared) {
  457. DVar.RefExpr = nullptr;
  458. DVar.CKind = OMPC_firstprivate;
  459. return DVar;
  460. }
  461. if (isParallelOrTaskRegion(I->Directive))
  462. break;
  463. }
  464. DVar.CKind =
  465. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  466. return DVar;
  467. }
  468. }
  469. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  470. // in a Construct, implicitly determined, p.3]
  471. // For constructs other than task, if no default clause is present, these
  472. // variables inherit their data-sharing attributes from the enclosing
  473. // context.
  474. return getDSA(++Iter, D);
  475. }
  476. Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
  477. assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
  478. D = getCanonicalDecl(D);
  479. auto It = Stack.back().AlignedMap.find(D);
  480. if (It == Stack.back().AlignedMap.end()) {
  481. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  482. Stack.back().AlignedMap[D] = NewDE;
  483. return nullptr;
  484. } else {
  485. assert(It->second && "Unexpected nullptr expr in the aligned map");
  486. return It->second;
  487. }
  488. return nullptr;
  489. }
  490. void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
  491. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
  492. D = getCanonicalDecl(D);
  493. Stack.back().LCVMap.insert(
  494. std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
  495. }
  496. DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
  497. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
  498. D = getCanonicalDecl(D);
  499. return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
  500. : LCDeclInfo(0, nullptr);
  501. }
  502. DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
  503. assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
  504. D = getCanonicalDecl(D);
  505. return Stack[Stack.size() - 2].LCVMap.count(D) > 0
  506. ? Stack[Stack.size() - 2].LCVMap[D]
  507. : LCDeclInfo(0, nullptr);
  508. }
  509. ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
  510. assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
  511. if (Stack[Stack.size() - 2].LCVMap.size() < I)
  512. return nullptr;
  513. for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
  514. if (Pair.second.first == I)
  515. return Pair.first;
  516. }
  517. return nullptr;
  518. }
  519. void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
  520. DeclRefExpr *PrivateCopy) {
  521. D = getCanonicalDecl(D);
  522. if (A == OMPC_threadprivate) {
  523. auto &Data = Stack[0].SharingMap[D];
  524. Data.Attributes = A;
  525. Data.RefExpr.setPointer(E);
  526. Data.PrivateCopy = nullptr;
  527. } else {
  528. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
  529. auto &Data = Stack.back().SharingMap[D];
  530. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  531. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  532. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  533. (isLoopControlVariable(D).first && A == OMPC_private));
  534. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  535. Data.RefExpr.setInt(/*IntVal=*/true);
  536. return;
  537. }
  538. const bool IsLastprivate =
  539. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  540. Data.Attributes = A;
  541. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  542. Data.PrivateCopy = PrivateCopy;
  543. if (PrivateCopy) {
  544. auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
  545. Data.Attributes = A;
  546. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  547. Data.PrivateCopy = nullptr;
  548. }
  549. }
  550. }
  551. bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
  552. D = D->getCanonicalDecl();
  553. if (Stack.size() > 2) {
  554. reverse_iterator I = Iter, E = std::prev(Stack.rend());
  555. Scope *TopScope = nullptr;
  556. while (I != E && !isParallelOrTaskRegion(I->Directive)) {
  557. ++I;
  558. }
  559. if (I == E)
  560. return false;
  561. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  562. Scope *CurScope = getCurScope();
  563. while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
  564. CurScope = CurScope->getParent();
  565. }
  566. return CurScope != TopScope;
  567. }
  568. return false;
  569. }
  570. /// \brief Build a variable declaration for OpenMP loop iteration variable.
  571. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  572. StringRef Name, const AttrVec *Attrs = nullptr) {
  573. DeclContext *DC = SemaRef.CurContext;
  574. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  575. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  576. VarDecl *Decl =
  577. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  578. if (Attrs) {
  579. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  580. I != E; ++I)
  581. Decl->addAttr(*I);
  582. }
  583. Decl->setImplicit();
  584. return Decl;
  585. }
  586. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  587. SourceLocation Loc,
  588. bool RefersToCapture = false) {
  589. D->setReferenced();
  590. D->markUsed(S.Context);
  591. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  592. SourceLocation(), D, RefersToCapture, Loc, Ty,
  593. VK_LValue);
  594. }
  595. DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
  596. D = getCanonicalDecl(D);
  597. DSAVarData DVar;
  598. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  599. // in a Construct, C/C++, predetermined, p.1]
  600. // Variables appearing in threadprivate directives are threadprivate.
  601. auto *VD = dyn_cast<VarDecl>(D);
  602. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  603. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  604. SemaRef.getLangOpts().OpenMPUseTLS &&
  605. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  606. (VD && VD->getStorageClass() == SC_Register &&
  607. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  608. addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  609. D->getLocation()),
  610. OMPC_threadprivate);
  611. }
  612. if (Stack[0].SharingMap.count(D)) {
  613. DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
  614. DVar.CKind = OMPC_threadprivate;
  615. return DVar;
  616. }
  617. if (Stack.size() == 1) {
  618. // Not in OpenMP execution region and top scope was already checked.
  619. return DVar;
  620. }
  621. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  622. // in a Construct, C/C++, predetermined, p.4]
  623. // Static data members are shared.
  624. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  625. // in a Construct, C/C++, predetermined, p.7]
  626. // Variables with static storage duration that are declared in a scope
  627. // inside the construct are shared.
  628. auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
  629. if (VD && VD->isStaticDataMember()) {
  630. DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
  631. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  632. return DVar;
  633. DVar.CKind = OMPC_shared;
  634. return DVar;
  635. }
  636. QualType Type = D->getType().getNonReferenceType().getCanonicalType();
  637. bool IsConstant = Type.isConstant(SemaRef.getASTContext());
  638. Type = SemaRef.getASTContext().getBaseElementType(Type);
  639. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  640. // in a Construct, C/C++, predetermined, p.6]
  641. // Variables with const qualified type having no mutable member are
  642. // shared.
  643. CXXRecordDecl *RD =
  644. SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  645. if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  646. if (auto *CTD = CTSD->getSpecializedTemplate())
  647. RD = CTD->getTemplatedDecl();
  648. if (IsConstant &&
  649. !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
  650. RD->hasMutableFields())) {
  651. // Variables with const-qualified type having no mutable member may be
  652. // listed in a firstprivate clause, even if they are static data members.
  653. DSAVarData DVarTemp = hasDSA(
  654. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
  655. MatchesAlways, FromParent);
  656. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  657. return DVar;
  658. DVar.CKind = OMPC_shared;
  659. return DVar;
  660. }
  661. // Explicitly specified attributes and local variables with predetermined
  662. // attributes.
  663. auto StartI = std::next(Stack.rbegin());
  664. auto EndI = std::prev(Stack.rend());
  665. if (FromParent && StartI != EndI) {
  666. StartI = std::next(StartI);
  667. }
  668. auto I = std::prev(StartI);
  669. if (I->SharingMap.count(D)) {
  670. DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
  671. DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
  672. DVar.CKind = I->SharingMap[D].Attributes;
  673. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  674. }
  675. return DVar;
  676. }
  677. DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  678. bool FromParent) {
  679. D = getCanonicalDecl(D);
  680. auto StartI = Stack.rbegin();
  681. auto EndI = std::prev(Stack.rend());
  682. if (FromParent && StartI != EndI) {
  683. StartI = std::next(StartI);
  684. }
  685. return getDSA(StartI, D);
  686. }
  687. DSAStackTy::DSAVarData
  688. DSAStackTy::hasDSA(ValueDecl *D,
  689. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  690. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  691. bool FromParent) {
  692. D = getCanonicalDecl(D);
  693. auto StartI = std::next(Stack.rbegin());
  694. auto EndI = Stack.rend();
  695. if (FromParent && StartI != EndI) {
  696. StartI = std::next(StartI);
  697. }
  698. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  699. if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
  700. continue;
  701. DSAVarData DVar = getDSA(I, D);
  702. if (CPred(DVar.CKind))
  703. return DVar;
  704. }
  705. return DSAVarData();
  706. }
  707. DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  708. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  709. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  710. bool FromParent) {
  711. D = getCanonicalDecl(D);
  712. auto StartI = std::next(Stack.rbegin());
  713. auto EndI = Stack.rend();
  714. if (FromParent && StartI != EndI)
  715. StartI = std::next(StartI);
  716. if (StartI == EndI || !DPred(StartI->Directive))
  717. return DSAVarData();
  718. DSAVarData DVar = getDSA(StartI, D);
  719. return CPred(DVar.CKind) ? DVar : DSAVarData();
  720. }
  721. bool DSAStackTy::hasExplicitDSA(
  722. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  723. unsigned Level, bool NotLastprivate) {
  724. if (CPred(ClauseKindMode))
  725. return true;
  726. D = getCanonicalDecl(D);
  727. auto StartI = std::next(Stack.begin());
  728. auto EndI = Stack.end();
  729. if (std::distance(StartI, EndI) <= (int)Level)
  730. return false;
  731. std::advance(StartI, Level);
  732. return (StartI->SharingMap.count(D) > 0) &&
  733. StartI->SharingMap[D].RefExpr.getPointer() &&
  734. CPred(StartI->SharingMap[D].Attributes) &&
  735. (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
  736. }
  737. bool DSAStackTy::hasExplicitDirective(
  738. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  739. unsigned Level) {
  740. auto StartI = std::next(Stack.begin());
  741. auto EndI = Stack.end();
  742. if (std::distance(StartI, EndI) <= (int)Level)
  743. return false;
  744. std::advance(StartI, Level);
  745. return DPred(StartI->Directive);
  746. }
  747. bool DSAStackTy::hasDirective(
  748. const llvm::function_ref<bool(OpenMPDirectiveKind,
  749. const DeclarationNameInfo &, SourceLocation)>
  750. &DPred,
  751. bool FromParent) {
  752. // We look only in the enclosing region.
  753. if (Stack.size() < 2)
  754. return false;
  755. auto StartI = std::next(Stack.rbegin());
  756. auto EndI = std::prev(Stack.rend());
  757. if (FromParent && StartI != EndI) {
  758. StartI = std::next(StartI);
  759. }
  760. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  761. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  762. return true;
  763. }
  764. return false;
  765. }
  766. void Sema::InitDataSharingAttributesStack() {
  767. VarDataSharingAttributesStack = new DSAStackTy(*this);
  768. }
  769. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  770. bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
  771. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  772. auto &Ctx = getASTContext();
  773. bool IsByRef = true;
  774. // Find the directive that is associated with the provided scope.
  775. auto Ty = D->getType();
  776. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  777. // This table summarizes how a given variable should be passed to the device
  778. // given its type and the clauses where it appears. This table is based on
  779. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  780. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  781. //
  782. // =========================================================================
  783. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  784. // | |(tofrom:scalar)| | pvt | | | |
  785. // =========================================================================
  786. // | scl | | | | - | | bycopy|
  787. // | scl | | - | x | - | - | bycopy|
  788. // | scl | | x | - | - | - | null |
  789. // | scl | x | | | - | | byref |
  790. // | scl | x | - | x | - | - | bycopy|
  791. // | scl | x | x | - | - | - | null |
  792. // | scl | | - | - | - | x | byref |
  793. // | scl | x | - | - | - | x | byref |
  794. //
  795. // | agg | n.a. | | | - | | byref |
  796. // | agg | n.a. | - | x | - | - | byref |
  797. // | agg | n.a. | x | - | - | - | null |
  798. // | agg | n.a. | - | - | - | x | byref |
  799. // | agg | n.a. | - | - | - | x[] | byref |
  800. //
  801. // | ptr | n.a. | | | - | | bycopy|
  802. // | ptr | n.a. | - | x | - | - | bycopy|
  803. // | ptr | n.a. | x | - | - | - | null |
  804. // | ptr | n.a. | - | - | - | x | byref |
  805. // | ptr | n.a. | - | - | - | x[] | bycopy|
  806. // | ptr | n.a. | - | - | x | | bycopy|
  807. // | ptr | n.a. | - | - | x | x | bycopy|
  808. // | ptr | n.a. | - | - | x | x[] | bycopy|
  809. // =========================================================================
  810. // Legend:
  811. // scl - scalar
  812. // ptr - pointer
  813. // agg - aggregate
  814. // x - applies
  815. // - - invalid in this combination
  816. // [] - mapped with an array section
  817. // byref - should be mapped by reference
  818. // byval - should be mapped by value
  819. // null - initialize a local variable to null on the device
  820. //
  821. // Observations:
  822. // - All scalar declarations that show up in a map clause have to be passed
  823. // by reference, because they may have been mapped in the enclosing data
  824. // environment.
  825. // - If the scalar value does not fit the size of uintptr, it has to be
  826. // passed by reference, regardless the result in the table above.
  827. // - For pointers mapped by value that have either an implicit map or an
  828. // array section, the runtime library may pass the NULL value to the
  829. // device instead of the value passed to it by the compiler.
  830. if (Ty->isReferenceType())
  831. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  832. // Locate map clauses and see if the variable being captured is referred to
  833. // in any of those clauses. Here we only care about variables, not fields,
  834. // because fields are part of aggregates.
  835. bool IsVariableUsedInMapClause = false;
  836. bool IsVariableAssociatedWithSection = false;
  837. DSAStack->checkMappableExprComponentListsForDecl(
  838. D, /*CurrentRegionOnly=*/true,
  839. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
  840. MapExprComponents,
  841. OpenMPClauseKind WhereFoundClauseKind) {
  842. // Only the map clause information influences how a variable is
  843. // captured. E.g. is_device_ptr does not require changing the default
  844. // behavior.
  845. if (WhereFoundClauseKind != OMPC_map)
  846. return false;
  847. auto EI = MapExprComponents.rbegin();
  848. auto EE = MapExprComponents.rend();
  849. assert(EI != EE && "Invalid map expression!");
  850. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  851. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  852. ++EI;
  853. if (EI == EE)
  854. return false;
  855. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  856. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  857. isa<MemberExpr>(EI->getAssociatedExpression())) {
  858. IsVariableAssociatedWithSection = true;
  859. // There is nothing more we need to know about this variable.
  860. return true;
  861. }
  862. // Keep looking for more map info.
  863. return false;
  864. });
  865. if (IsVariableUsedInMapClause) {
  866. // If variable is identified in a map clause it is always captured by
  867. // reference except if it is a pointer that is dereferenced somehow.
  868. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  869. } else {
  870. // By default, all the data that has a scalar type is mapped by copy.
  871. IsByRef = !Ty->isScalarType();
  872. }
  873. }
  874. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  875. IsByRef = !DSAStack->hasExplicitDSA(
  876. D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  877. Level, /*NotLastprivate=*/true);
  878. }
  879. // When passing data by copy, we need to make sure it fits the uintptr size
  880. // and alignment, because the runtime library only deals with uintptr types.
  881. // If it does not fit the uintptr size, we need to pass the data by reference
  882. // instead.
  883. if (!IsByRef &&
  884. (Ctx.getTypeSizeInChars(Ty) >
  885. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  886. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  887. IsByRef = true;
  888. }
  889. return IsByRef;
  890. }
  891. unsigned Sema::getOpenMPNestingLevel() const {
  892. assert(getLangOpts().OpenMP);
  893. return DSAStack->getNestingLevel();
  894. }
  895. VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
  896. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  897. D = getCanonicalDecl(D);
  898. // If we are attempting to capture a global variable in a directive with
  899. // 'target' we return true so that this global is also mapped to the device.
  900. //
  901. // FIXME: If the declaration is enclosed in a 'declare target' directive,
  902. // then it should not be captured. Therefore, an extra check has to be
  903. // inserted here once support for 'declare target' is added.
  904. //
  905. auto *VD = dyn_cast<VarDecl>(D);
  906. if (VD && !VD->hasLocalStorage()) {
  907. if (DSAStack->getCurrentDirective() == OMPD_target &&
  908. !DSAStack->isClauseParsingMode())
  909. return VD;
  910. if (DSAStack->hasDirective(
  911. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  912. SourceLocation) -> bool {
  913. return isOpenMPTargetExecutionDirective(K);
  914. },
  915. false))
  916. return VD;
  917. }
  918. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  919. (!DSAStack->isClauseParsingMode() ||
  920. DSAStack->getParentDirective() != OMPD_unknown)) {
  921. auto &&Info = DSAStack->isLoopControlVariable(D);
  922. if (Info.first ||
  923. (VD && VD->hasLocalStorage() &&
  924. isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
  925. (VD && DSAStack->isForceVarCapturing()))
  926. return VD ? VD : Info.second;
  927. auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  928. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  929. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  930. DVarPrivate = DSAStack->hasDSA(
  931. D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
  932. DSAStack->isClauseParsingMode());
  933. if (DVarPrivate.CKind != OMPC_unknown)
  934. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  935. }
  936. return nullptr;
  937. }
  938. bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
  939. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  940. return DSAStack->hasExplicitDSA(
  941. D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
  942. }
  943. bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
  944. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  945. // Return true if the current level is no longer enclosed in a target region.
  946. auto *VD = dyn_cast<VarDecl>(D);
  947. return VD && !VD->hasLocalStorage() &&
  948. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  949. Level);
  950. }
  951. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  952. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  953. const DeclarationNameInfo &DirName,
  954. Scope *CurScope, SourceLocation Loc) {
  955. DSAStack->push(DKind, DirName, CurScope, Loc);
  956. PushExpressionEvaluationContext(PotentiallyEvaluated);
  957. }
  958. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  959. DSAStack->setClauseParsingMode(K);
  960. }
  961. void Sema::EndOpenMPClause() {
  962. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  963. }
  964. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  965. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  966. // A variable of class type (or array thereof) that appears in a lastprivate
  967. // clause requires an accessible, unambiguous default constructor for the
  968. // class type, unless the list item is also specified in a firstprivate
  969. // clause.
  970. if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  971. for (auto *C : D->clauses()) {
  972. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  973. SmallVector<Expr *, 8> PrivateCopies;
  974. for (auto *DE : Clause->varlists()) {
  975. if (DE->isValueDependent() || DE->isTypeDependent()) {
  976. PrivateCopies.push_back(nullptr);
  977. continue;
  978. }
  979. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  980. VarDecl *VD = cast<VarDecl>(DRE->getDecl());
  981. QualType Type = VD->getType().getNonReferenceType();
  982. auto DVar = DSAStack->getTopDSA(VD, false);
  983. if (DVar.CKind == OMPC_lastprivate) {
  984. // Generate helper private variable and initialize it with the
  985. // default value. The address of the original variable is replaced
  986. // by the address of the new private variable in CodeGen. This new
  987. // variable is not added to IdResolver, so the code in the OpenMP
  988. // region uses original variable for proper diagnostics.
  989. auto *VDPrivate = buildVarDecl(
  990. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  991. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  992. ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
  993. if (VDPrivate->isInvalidDecl())
  994. continue;
  995. PrivateCopies.push_back(buildDeclRefExpr(
  996. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  997. } else {
  998. // The variable is also a firstprivate, so initialization sequence
  999. // for private copy is generated already.
  1000. PrivateCopies.push_back(nullptr);
  1001. }
  1002. }
  1003. // Set initializers to private copies if no errors were found.
  1004. if (PrivateCopies.size() == Clause->varlist_size())
  1005. Clause->setPrivateCopies(PrivateCopies);
  1006. }
  1007. }
  1008. }
  1009. DSAStack->pop();
  1010. DiscardCleanupsInEvaluationContext();
  1011. PopExpressionEvaluationContext();
  1012. }
  1013. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1014. Expr *NumIterations, Sema &SemaRef,
  1015. Scope *S, DSAStackTy *Stack);
  1016. namespace {
  1017. class VarDeclFilterCCC : public CorrectionCandidateCallback {
  1018. private:
  1019. Sema &SemaRef;
  1020. public:
  1021. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1022. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1023. NamedDecl *ND = Candidate.getCorrectionDecl();
  1024. if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1025. return VD->hasGlobalStorage() &&
  1026. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1027. SemaRef.getCurScope());
  1028. }
  1029. return false;
  1030. }
  1031. };
  1032. class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
  1033. private:
  1034. Sema &SemaRef;
  1035. public:
  1036. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1037. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1038. NamedDecl *ND = Candidate.getCorrectionDecl();
  1039. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
  1040. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1041. SemaRef.getCurScope());
  1042. }
  1043. return false;
  1044. }
  1045. };
  1046. } // namespace
  1047. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1048. CXXScopeSpec &ScopeSpec,
  1049. const DeclarationNameInfo &Id) {
  1050. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1051. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1052. if (Lookup.isAmbiguous())
  1053. return ExprError();
  1054. VarDecl *VD;
  1055. if (!Lookup.isSingleResult()) {
  1056. if (TypoCorrection Corrected = CorrectTypo(
  1057. Id, LookupOrdinaryName, CurScope, nullptr,
  1058. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1059. diagnoseTypo(Corrected,
  1060. PDiag(Lookup.empty()
  1061. ? diag::err_undeclared_var_use_suggest
  1062. : diag::err_omp_expected_var_arg_suggest)
  1063. << Id.getName());
  1064. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1065. } else {
  1066. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1067. : diag::err_omp_expected_var_arg)
  1068. << Id.getName();
  1069. return ExprError();
  1070. }
  1071. } else {
  1072. if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1073. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1074. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1075. return ExprError();
  1076. }
  1077. }
  1078. Lookup.suppressDiagnostics();
  1079. // OpenMP [2.9.2, Syntax, C/C++]
  1080. // Variables must be file-scope, namespace-scope, or static block-scope.
  1081. if (!VD->hasGlobalStorage()) {
  1082. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1083. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  1084. bool IsDecl =
  1085. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1086. Diag(VD->getLocation(),
  1087. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1088. << VD;
  1089. return ExprError();
  1090. }
  1091. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1092. NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
  1093. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1094. // A threadprivate directive for file-scope variables must appear outside
  1095. // any definition or declaration.
  1096. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1097. !getCurLexicalContext()->isTranslationUnit()) {
  1098. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1099. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1100. bool IsDecl =
  1101. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1102. Diag(VD->getLocation(),
  1103. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1104. << VD;
  1105. return ExprError();
  1106. }
  1107. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1108. // A threadprivate directive for static class member variables must appear
  1109. // in the class definition, in the same scope in which the member
  1110. // variables are declared.
  1111. if (CanonicalVD->isStaticDataMember() &&
  1112. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1113. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1114. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1115. bool IsDecl =
  1116. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1117. Diag(VD->getLocation(),
  1118. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1119. << VD;
  1120. return ExprError();
  1121. }
  1122. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1123. // A threadprivate directive for namespace-scope variables must appear
  1124. // outside any definition or declaration other than the namespace
  1125. // definition itself.
  1126. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1127. (!getCurLexicalContext()->isFileContext() ||
  1128. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1129. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1130. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  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. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1139. // A threadprivate directive for static block-scope variables must appear
  1140. // in the scope of the variable and not in a nested scope.
  1141. if (CanonicalVD->isStaticLocal() && CurScope &&
  1142. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1143. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1144. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1145. bool IsDecl =
  1146. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1147. Diag(VD->getLocation(),
  1148. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1149. << VD;
  1150. return ExprError();
  1151. }
  1152. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1153. // A threadprivate directive must lexically precede all references to any
  1154. // of the variables in its list.
  1155. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1156. Diag(Id.getLoc(), diag::err_omp_var_used)
  1157. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1158. return ExprError();
  1159. }
  1160. QualType ExprType = VD->getType().getNonReferenceType();
  1161. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  1162. SourceLocation(), VD,
  1163. /*RefersToEnclosingVariableOrCapture=*/false,
  1164. Id.getLoc(), ExprType, VK_LValue);
  1165. }
  1166. Sema::DeclGroupPtrTy
  1167. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1168. ArrayRef<Expr *> VarList) {
  1169. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1170. CurContext->addDecl(D);
  1171. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1172. }
  1173. return nullptr;
  1174. }
  1175. namespace {
  1176. class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1177. Sema &SemaRef;
  1178. public:
  1179. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1180. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1181. if (VD->hasLocalStorage()) {
  1182. SemaRef.Diag(E->getLocStart(),
  1183. diag::err_omp_local_var_in_threadprivate_init)
  1184. << E->getSourceRange();
  1185. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1186. << VD << VD->getSourceRange();
  1187. return true;
  1188. }
  1189. }
  1190. return false;
  1191. }
  1192. bool VisitStmt(const Stmt *S) {
  1193. for (auto Child : S->children()) {
  1194. if (Child && Visit(Child))
  1195. return true;
  1196. }
  1197. return false;
  1198. }
  1199. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1200. };
  1201. } // namespace
  1202. OMPThreadPrivateDecl *
  1203. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1204. SmallVector<Expr *, 8> Vars;
  1205. for (auto &RefExpr : VarList) {
  1206. DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
  1207. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  1208. SourceLocation ILoc = DE->getExprLoc();
  1209. // Mark variable as used.
  1210. VD->setReferenced();
  1211. VD->markUsed(Context);
  1212. QualType QType = VD->getType();
  1213. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1214. // It will be analyzed later.
  1215. Vars.push_back(DE);
  1216. continue;
  1217. }
  1218. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1219. // A threadprivate variable must not have an incomplete type.
  1220. if (RequireCompleteType(ILoc, VD->getType(),
  1221. diag::err_omp_threadprivate_incomplete_type)) {
  1222. continue;
  1223. }
  1224. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1225. // A threadprivate variable must not have a reference type.
  1226. if (VD->getType()->isReferenceType()) {
  1227. Diag(ILoc, diag::err_omp_ref_type_arg)
  1228. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1229. bool IsDecl =
  1230. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1231. Diag(VD->getLocation(),
  1232. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1233. << VD;
  1234. continue;
  1235. }
  1236. // Check if this is a TLS variable. If TLS is not being supported, produce
  1237. // the corresponding diagnostic.
  1238. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1239. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1240. getLangOpts().OpenMPUseTLS &&
  1241. getASTContext().getTargetInfo().isTLSSupported())) ||
  1242. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1243. !VD->isLocalVarDecl())) {
  1244. Diag(ILoc, diag::err_omp_var_thread_local)
  1245. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1246. bool IsDecl =
  1247. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1248. Diag(VD->getLocation(),
  1249. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1250. << VD;
  1251. continue;
  1252. }
  1253. // Check if initial value of threadprivate variable reference variable with
  1254. // local storage (it is not supported by runtime).
  1255. if (auto Init = VD->getAnyInitializer()) {
  1256. LocalVarRefChecker Checker(*this);
  1257. if (Checker.Visit(Init))
  1258. continue;
  1259. }
  1260. Vars.push_back(RefExpr);
  1261. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1262. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1263. Context, SourceRange(Loc, Loc)));
  1264. if (auto *ML = Context.getASTMutationListener())
  1265. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1266. }
  1267. OMPThreadPrivateDecl *D = nullptr;
  1268. if (!Vars.empty()) {
  1269. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1270. Vars);
  1271. D->setAccess(AS_public);
  1272. }
  1273. return D;
  1274. }
  1275. static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
  1276. const ValueDecl *D, DSAStackTy::DSAVarData DVar,
  1277. bool IsLoopIterVar = false) {
  1278. if (DVar.RefExpr) {
  1279. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  1280. << getOpenMPClauseName(DVar.CKind);
  1281. return;
  1282. }
  1283. enum {
  1284. PDSA_StaticMemberShared,
  1285. PDSA_StaticLocalVarShared,
  1286. PDSA_LoopIterVarPrivate,
  1287. PDSA_LoopIterVarLinear,
  1288. PDSA_LoopIterVarLastprivate,
  1289. PDSA_ConstVarShared,
  1290. PDSA_GlobalVarShared,
  1291. PDSA_TaskVarFirstprivate,
  1292. PDSA_LocalVarPrivate,
  1293. PDSA_Implicit
  1294. } Reason = PDSA_Implicit;
  1295. bool ReportHint = false;
  1296. auto ReportLoc = D->getLocation();
  1297. auto *VD = dyn_cast<VarDecl>(D);
  1298. if (IsLoopIterVar) {
  1299. if (DVar.CKind == OMPC_private)
  1300. Reason = PDSA_LoopIterVarPrivate;
  1301. else if (DVar.CKind == OMPC_lastprivate)
  1302. Reason = PDSA_LoopIterVarLastprivate;
  1303. else
  1304. Reason = PDSA_LoopIterVarLinear;
  1305. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  1306. DVar.CKind == OMPC_firstprivate) {
  1307. Reason = PDSA_TaskVarFirstprivate;
  1308. ReportLoc = DVar.ImplicitDSALoc;
  1309. } else if (VD && VD->isStaticLocal())
  1310. Reason = PDSA_StaticLocalVarShared;
  1311. else if (VD && VD->isStaticDataMember())
  1312. Reason = PDSA_StaticMemberShared;
  1313. else if (VD && VD->isFileVarDecl())
  1314. Reason = PDSA_GlobalVarShared;
  1315. else if (D->getType().isConstant(SemaRef.getASTContext()))
  1316. Reason = PDSA_ConstVarShared;
  1317. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  1318. ReportHint = true;
  1319. Reason = PDSA_LocalVarPrivate;
  1320. }
  1321. if (Reason != PDSA_Implicit) {
  1322. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  1323. << Reason << ReportHint
  1324. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  1325. } else if (DVar.ImplicitDSALoc.isValid()) {
  1326. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  1327. << getOpenMPClauseName(DVar.CKind);
  1328. }
  1329. }
  1330. namespace {
  1331. class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
  1332. DSAStackTy *Stack;
  1333. Sema &SemaRef;
  1334. bool ErrorFound;
  1335. CapturedStmt *CS;
  1336. llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
  1337. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  1338. public:
  1339. void VisitDeclRefExpr(DeclRefExpr *E) {
  1340. if (E->isTypeDependent() || E->isValueDependent() ||
  1341. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1342. return;
  1343. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1344. // Skip internally declared variables.
  1345. if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
  1346. return;
  1347. auto DVar = Stack->getTopDSA(VD, false);
  1348. // Check if the variable has explicit DSA set and stop analysis if it so.
  1349. if (DVar.RefExpr)
  1350. return;
  1351. auto ELoc = E->getExprLoc();
  1352. auto DKind = Stack->getCurrentDirective();
  1353. // The default(none) clause requires that each variable that is referenced
  1354. // in the construct, and does not have a predetermined data-sharing
  1355. // attribute, must have its data-sharing attribute explicitly determined
  1356. // by being listed in a data-sharing attribute clause.
  1357. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  1358. isParallelOrTaskRegion(DKind) &&
  1359. VarsWithInheritedDSA.count(VD) == 0) {
  1360. VarsWithInheritedDSA[VD] = E;
  1361. return;
  1362. }
  1363. // OpenMP [2.9.3.6, Restrictions, p.2]
  1364. // A list item that appears in a reduction clause of the innermost
  1365. // enclosing worksharing or parallel construct may not be accessed in an
  1366. // explicit task.
  1367. DVar = Stack->hasInnermostDSA(
  1368. VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  1369. [](OpenMPDirectiveKind K) -> bool {
  1370. return isOpenMPParallelDirective(K) ||
  1371. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  1372. },
  1373. false);
  1374. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1375. ErrorFound = true;
  1376. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1377. ReportOriginalDSA(SemaRef, Stack, VD, DVar);
  1378. return;
  1379. }
  1380. // Define implicit data-sharing attributes for task.
  1381. DVar = Stack->getImplicitDSA(VD, false);
  1382. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1383. !Stack->isLoopControlVariable(VD).first)
  1384. ImplicitFirstprivate.push_back(E);
  1385. }
  1386. }
  1387. void VisitMemberExpr(MemberExpr *E) {
  1388. if (E->isTypeDependent() || E->isValueDependent() ||
  1389. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1390. return;
  1391. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  1392. if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  1393. auto DVar = Stack->getTopDSA(FD, false);
  1394. // Check if the variable has explicit DSA set and stop analysis if it
  1395. // so.
  1396. if (DVar.RefExpr)
  1397. return;
  1398. auto ELoc = E->getExprLoc();
  1399. auto DKind = Stack->getCurrentDirective();
  1400. // OpenMP [2.9.3.6, Restrictions, p.2]
  1401. // A list item that appears in a reduction clause of the innermost
  1402. // enclosing worksharing or parallel construct may not be accessed in
  1403. // an explicit task.
  1404. DVar = Stack->hasInnermostDSA(
  1405. FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  1406. [](OpenMPDirectiveKind K) -> bool {
  1407. return isOpenMPParallelDirective(K) ||
  1408. isOpenMPWorksharingDirective(K) ||
  1409. isOpenMPTeamsDirective(K);
  1410. },
  1411. false);
  1412. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1413. ErrorFound = true;
  1414. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1415. ReportOriginalDSA(SemaRef, Stack, FD, DVar);
  1416. return;
  1417. }
  1418. // Define implicit data-sharing attributes for task.
  1419. DVar = Stack->getImplicitDSA(FD, false);
  1420. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1421. !Stack->isLoopControlVariable(FD).first)
  1422. ImplicitFirstprivate.push_back(E);
  1423. }
  1424. } else
  1425. Visit(E->getBase());
  1426. }
  1427. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  1428. for (auto *C : S->clauses()) {
  1429. // Skip analysis of arguments of implicitly defined firstprivate clause
  1430. // for task directives.
  1431. if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
  1432. for (auto *CC : C->children()) {
  1433. if (CC)
  1434. Visit(CC);
  1435. }
  1436. }
  1437. }
  1438. void VisitStmt(Stmt *S) {
  1439. for (auto *C : S->children()) {
  1440. if (C && !isa<OMPExecutableDirective>(C))
  1441. Visit(C);
  1442. }
  1443. }
  1444. bool isErrorFound() { return ErrorFound; }
  1445. ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
  1446. llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
  1447. return VarsWithInheritedDSA;
  1448. }
  1449. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  1450. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  1451. };
  1452. } // namespace
  1453. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  1454. switch (DKind) {
  1455. case OMPD_parallel:
  1456. case OMPD_parallel_for:
  1457. case OMPD_parallel_for_simd:
  1458. case OMPD_parallel_sections:
  1459. case OMPD_teams:
  1460. case OMPD_target_teams: {
  1461. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1462. QualType KmpInt32PtrTy =
  1463. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1464. Sema::CapturedParamNameType Params[] = {
  1465. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1466. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1467. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1468. };
  1469. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1470. Params);
  1471. break;
  1472. }
  1473. case OMPD_simd:
  1474. case OMPD_for:
  1475. case OMPD_for_simd:
  1476. case OMPD_sections:
  1477. case OMPD_section:
  1478. case OMPD_single:
  1479. case OMPD_master:
  1480. case OMPD_critical:
  1481. case OMPD_taskgroup:
  1482. case OMPD_distribute:
  1483. case OMPD_ordered:
  1484. case OMPD_atomic:
  1485. case OMPD_target_data:
  1486. case OMPD_target:
  1487. case OMPD_target_parallel:
  1488. case OMPD_target_parallel_for:
  1489. case OMPD_target_parallel_for_simd:
  1490. case OMPD_target_simd: {
  1491. Sema::CapturedParamNameType Params[] = {
  1492. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1493. };
  1494. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1495. Params);
  1496. break;
  1497. }
  1498. case OMPD_task: {
  1499. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1500. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  1501. FunctionProtoType::ExtProtoInfo EPI;
  1502. EPI.Variadic = true;
  1503. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  1504. Sema::CapturedParamNameType Params[] = {
  1505. std::make_pair(".global_tid.", KmpInt32Ty),
  1506. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  1507. std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
  1508. std::make_pair(".copy_fn.",
  1509. Context.getPointerType(CopyFnType).withConst()),
  1510. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  1511. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1512. };
  1513. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1514. Params);
  1515. // Mark this captured region as inlined, because we don't use outlined
  1516. // function directly.
  1517. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  1518. AlwaysInlineAttr::CreateImplicit(
  1519. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  1520. break;
  1521. }
  1522. case OMPD_taskloop:
  1523. case OMPD_taskloop_simd: {
  1524. QualType KmpInt32Ty =
  1525. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  1526. QualType KmpUInt64Ty =
  1527. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  1528. QualType KmpInt64Ty =
  1529. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  1530. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  1531. FunctionProtoType::ExtProtoInfo EPI;
  1532. EPI.Variadic = true;
  1533. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  1534. Sema::CapturedParamNameType Params[] = {
  1535. std::make_pair(".global_tid.", KmpInt32Ty),
  1536. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  1537. std::make_pair(".privates.",
  1538. Context.VoidPtrTy.withConst().withRestrict()),
  1539. std::make_pair(
  1540. ".copy_fn.",
  1541. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  1542. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  1543. std::make_pair(".lb.", KmpUInt64Ty),
  1544. std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
  1545. std::make_pair(".liter.", KmpInt32Ty),
  1546. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1547. };
  1548. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1549. Params);
  1550. // Mark this captured region as inlined, because we don't use outlined
  1551. // function directly.
  1552. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  1553. AlwaysInlineAttr::CreateImplicit(
  1554. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  1555. break;
  1556. }
  1557. case OMPD_distribute_parallel_for_simd:
  1558. case OMPD_distribute_simd:
  1559. case OMPD_distribute_parallel_for:
  1560. case OMPD_teams_distribute:
  1561. case OMPD_teams_distribute_simd:
  1562. case OMPD_teams_distribute_parallel_for_simd:
  1563. case OMPD_teams_distribute_parallel_for:
  1564. case OMPD_target_teams_distribute:
  1565. case OMPD_target_teams_distribute_parallel_for: {
  1566. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1567. QualType KmpInt32PtrTy =
  1568. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1569. Sema::CapturedParamNameType Params[] = {
  1570. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1571. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1572. std::make_pair(".previous.lb.", Context.getSizeType()),
  1573. std::make_pair(".previous.ub.", Context.getSizeType()),
  1574. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1575. };
  1576. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1577. Params);
  1578. break;
  1579. }
  1580. case OMPD_threadprivate:
  1581. case OMPD_taskyield:
  1582. case OMPD_barrier:
  1583. case OMPD_taskwait:
  1584. case OMPD_cancellation_point:
  1585. case OMPD_cancel:
  1586. case OMPD_flush:
  1587. case OMPD_target_enter_data:
  1588. case OMPD_target_exit_data:
  1589. case OMPD_declare_reduction:
  1590. case OMPD_declare_simd:
  1591. case OMPD_declare_target:
  1592. case OMPD_end_declare_target:
  1593. case OMPD_target_update:
  1594. llvm_unreachable("OpenMP Directive is not allowed");
  1595. case OMPD_unknown:
  1596. llvm_unreachable("Unknown OpenMP directive");
  1597. }
  1598. }
  1599. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  1600. Expr *CaptureExpr, bool WithInit,
  1601. bool AsExpression) {
  1602. assert(CaptureExpr);
  1603. ASTContext &C = S.getASTContext();
  1604. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  1605. QualType Ty = Init->getType();
  1606. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  1607. if (S.getLangOpts().CPlusPlus)
  1608. Ty = C.getLValueReferenceType(Ty);
  1609. else {
  1610. Ty = C.getPointerType(Ty);
  1611. ExprResult Res =
  1612. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  1613. if (!Res.isUsable())
  1614. return nullptr;
  1615. Init = Res.get();
  1616. }
  1617. WithInit = true;
  1618. }
  1619. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  1620. CaptureExpr->getLocStart());
  1621. if (!WithInit)
  1622. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
  1623. S.CurContext->addHiddenDecl(CED);
  1624. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
  1625. /*TypeMayContainAuto=*/true);
  1626. return CED;
  1627. }
  1628. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  1629. bool WithInit) {
  1630. OMPCapturedExprDecl *CD;
  1631. if (auto *VD = S.IsOpenMPCapturedDecl(D))
  1632. CD = cast<OMPCapturedExprDecl>(VD);
  1633. else
  1634. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  1635. /*AsExpression=*/false);
  1636. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  1637. CaptureExpr->getExprLoc());
  1638. }
  1639. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  1640. if (!Ref) {
  1641. auto *CD =
  1642. buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
  1643. CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
  1644. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  1645. CaptureExpr->getExprLoc());
  1646. }
  1647. ExprResult Res = Ref;
  1648. if (!S.getLangOpts().CPlusPlus &&
  1649. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  1650. Ref->getType()->isPointerType())
  1651. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  1652. if (!Res.isUsable())
  1653. return ExprError();
  1654. return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
  1655. }
  1656. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  1657. ArrayRef<OMPClause *> Clauses) {
  1658. if (!S.isUsable()) {
  1659. ActOnCapturedRegionError();
  1660. return StmtError();
  1661. }
  1662. OMPOrderedClause *OC = nullptr;
  1663. OMPScheduleClause *SC = nullptr;
  1664. SmallVector<OMPLinearClause *, 4> LCs;
  1665. // This is required for proper codegen.
  1666. for (auto *Clause : Clauses) {
  1667. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  1668. Clause->getClauseKind() == OMPC_copyprivate ||
  1669. (getLangOpts().OpenMPUseTLS &&
  1670. getASTContext().getTargetInfo().isTLSSupported() &&
  1671. Clause->getClauseKind() == OMPC_copyin)) {
  1672. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  1673. // Mark all variables in private list clauses as used in inner region.
  1674. for (auto *VarRef : Clause->children()) {
  1675. if (auto *E = cast_or_null<Expr>(VarRef)) {
  1676. MarkDeclarationsReferencedInExpr(E);
  1677. }
  1678. }
  1679. DSAStack->setForceVarCapturing(/*V=*/false);
  1680. } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
  1681. // Mark all variables in private list clauses as used in inner region.
  1682. // Required for proper codegen of combined directives.
  1683. // TODO: add processing for other clauses.
  1684. if (auto *C = OMPClauseWithPreInit::get(Clause)) {
  1685. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  1686. for (auto *D : DS->decls())
  1687. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  1688. }
  1689. }
  1690. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  1691. if (auto *E = C->getPostUpdateExpr())
  1692. MarkDeclarationsReferencedInExpr(E);
  1693. }
  1694. }
  1695. if (Clause->getClauseKind() == OMPC_schedule)
  1696. SC = cast<OMPScheduleClause>(Clause);
  1697. else if (Clause->getClauseKind() == OMPC_ordered)
  1698. OC = cast<OMPOrderedClause>(Clause);
  1699. else if (Clause->getClauseKind() == OMPC_linear)
  1700. LCs.push_back(cast<OMPLinearClause>(Clause));
  1701. }
  1702. bool ErrorFound = false;
  1703. // OpenMP, 2.7.1 Loop Construct, Restrictions
  1704. // The nonmonotonic modifier cannot be specified if an ordered clause is
  1705. // specified.
  1706. if (SC &&
  1707. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  1708. SC->getSecondScheduleModifier() ==
  1709. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  1710. OC) {
  1711. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  1712. ? SC->getFirstScheduleModifierLoc()
  1713. : SC->getSecondScheduleModifierLoc(),
  1714. diag::err_omp_schedule_nonmonotonic_ordered)
  1715. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  1716. ErrorFound = true;
  1717. }
  1718. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  1719. for (auto *C : LCs) {
  1720. Diag(C->getLocStart(), diag::err_omp_linear_ordered)
  1721. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  1722. }
  1723. ErrorFound = true;
  1724. }
  1725. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  1726. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  1727. OC->getNumForLoops()) {
  1728. Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
  1729. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  1730. ErrorFound = true;
  1731. }
  1732. if (ErrorFound) {
  1733. ActOnCapturedRegionError();
  1734. return StmtError();
  1735. }
  1736. return ActOnCapturedRegionEnd(S.get());
  1737. }
  1738. static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
  1739. OpenMPDirectiveKind CurrentRegion,
  1740. const DeclarationNameInfo &CurrentName,
  1741. OpenMPDirectiveKind CancelRegion,
  1742. SourceLocation StartLoc) {
  1743. if (Stack->getCurScope()) {
  1744. auto ParentRegion = Stack->getParentDirective();
  1745. auto OffendingRegion = ParentRegion;
  1746. bool NestingProhibited = false;
  1747. bool CloseNesting = true;
  1748. bool OrphanSeen = false;
  1749. enum {
  1750. NoRecommend,
  1751. ShouldBeInParallelRegion,
  1752. ShouldBeInOrderedRegion,
  1753. ShouldBeInTargetRegion,
  1754. ShouldBeInTeamsRegion
  1755. } Recommend = NoRecommend;
  1756. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  1757. // OpenMP [2.16, Nesting of Regions]
  1758. // OpenMP constructs may not be nested inside a simd region.
  1759. // OpenMP [2.8.1,simd Construct, Restrictions]
  1760. // An ordered construct with the simd clause is the only OpenMP
  1761. // construct that can appear in the simd region.
  1762. // Allowing a SIMD construct nested in another SIMD construct is an
  1763. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  1764. // message.
  1765. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  1766. ? diag::err_omp_prohibited_region_simd
  1767. : diag::warn_omp_nesting_simd);
  1768. return CurrentRegion != OMPD_simd;
  1769. }
  1770. if (ParentRegion == OMPD_atomic) {
  1771. // OpenMP [2.16, Nesting of Regions]
  1772. // OpenMP constructs may not be nested inside an atomic region.
  1773. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  1774. return true;
  1775. }
  1776. if (CurrentRegion == OMPD_section) {
  1777. // OpenMP [2.7.2, sections Construct, Restrictions]
  1778. // Orphaned section directives are prohibited. That is, the section
  1779. // directives must appear within the sections construct and must not be
  1780. // encountered elsewhere in the sections region.
  1781. if (ParentRegion != OMPD_sections &&
  1782. ParentRegion != OMPD_parallel_sections) {
  1783. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  1784. << (ParentRegion != OMPD_unknown)
  1785. << getOpenMPDirectiveName(ParentRegion);
  1786. return true;
  1787. }
  1788. return false;
  1789. }
  1790. // Allow some constructs (except teams) to be orphaned (they could be
  1791. // used in functions, called from OpenMP regions with the required
  1792. // preconditions).
  1793. if (ParentRegion == OMPD_unknown &&
  1794. !isOpenMPNestingTeamsDirective(CurrentRegion))
  1795. return false;
  1796. if (CurrentRegion == OMPD_cancellation_point ||
  1797. CurrentRegion == OMPD_cancel) {
  1798. // OpenMP [2.16, Nesting of Regions]
  1799. // A cancellation point construct for which construct-type-clause is
  1800. // taskgroup must be nested inside a task construct. A cancellation
  1801. // point construct for which construct-type-clause is not taskgroup must
  1802. // be closely nested inside an OpenMP construct that matches the type
  1803. // specified in construct-type-clause.
  1804. // A cancel construct for which construct-type-clause is taskgroup must be
  1805. // nested inside a task construct. A cancel construct for which
  1806. // construct-type-clause is not taskgroup must be closely nested inside an
  1807. // OpenMP construct that matches the type specified in
  1808. // construct-type-clause.
  1809. NestingProhibited =
  1810. !((CancelRegion == OMPD_parallel &&
  1811. (ParentRegion == OMPD_parallel ||
  1812. ParentRegion == OMPD_target_parallel)) ||
  1813. (CancelRegion == OMPD_for &&
  1814. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  1815. ParentRegion == OMPD_target_parallel_for)) ||
  1816. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  1817. (CancelRegion == OMPD_sections &&
  1818. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  1819. ParentRegion == OMPD_parallel_sections)));
  1820. } else if (CurrentRegion == OMPD_master) {
  1821. // OpenMP [2.16, Nesting of Regions]
  1822. // A master region may not be closely nested inside a worksharing,
  1823. // atomic, or explicit task region.
  1824. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  1825. isOpenMPTaskingDirective(ParentRegion);
  1826. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  1827. // OpenMP [2.16, Nesting of Regions]
  1828. // A critical region may not be nested (closely or otherwise) inside a
  1829. // critical region with the same name. Note that this restriction is not
  1830. // sufficient to prevent deadlock.
  1831. SourceLocation PreviousCriticalLoc;
  1832. bool DeadLock = Stack->hasDirective(
  1833. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  1834. const DeclarationNameInfo &DNI,
  1835. SourceLocation Loc) -> bool {
  1836. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  1837. PreviousCriticalLoc = Loc;
  1838. return true;
  1839. } else
  1840. return false;
  1841. },
  1842. false /* skip top directive */);
  1843. if (DeadLock) {
  1844. SemaRef.Diag(StartLoc,
  1845. diag::err_omp_prohibited_region_critical_same_name)
  1846. << CurrentName.getName();
  1847. if (PreviousCriticalLoc.isValid())
  1848. SemaRef.Diag(PreviousCriticalLoc,
  1849. diag::note_omp_previous_critical_region);
  1850. return true;
  1851. }
  1852. } else if (CurrentRegion == OMPD_barrier) {
  1853. // OpenMP [2.16, Nesting of Regions]
  1854. // A barrier region may not be closely nested inside a worksharing,
  1855. // explicit task, critical, ordered, atomic, or master region.
  1856. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  1857. isOpenMPTaskingDirective(ParentRegion) ||
  1858. ParentRegion == OMPD_master ||
  1859. ParentRegion == OMPD_critical ||
  1860. ParentRegion == OMPD_ordered;
  1861. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  1862. !isOpenMPParallelDirective(CurrentRegion) &&
  1863. !isOpenMPTeamsDirective(CurrentRegion)) {
  1864. // OpenMP [2.16, Nesting of Regions]
  1865. // A worksharing region may not be closely nested inside a worksharing,
  1866. // explicit task, critical, ordered, atomic, or master region.
  1867. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  1868. isOpenMPTaskingDirective(ParentRegion) ||
  1869. ParentRegion == OMPD_master ||
  1870. ParentRegion == OMPD_critical ||
  1871. ParentRegion == OMPD_ordered;
  1872. Recommend = ShouldBeInParallelRegion;
  1873. } else if (CurrentRegion == OMPD_ordered) {
  1874. // OpenMP [2.16, Nesting of Regions]
  1875. // An ordered region may not be closely nested inside a critical,
  1876. // atomic, or explicit task region.
  1877. // An ordered region must be closely nested inside a loop region (or
  1878. // parallel loop region) with an ordered clause.
  1879. // OpenMP [2.8.1,simd Construct, Restrictions]
  1880. // An ordered construct with the simd clause is the only OpenMP construct
  1881. // that can appear in the simd region.
  1882. NestingProhibited = ParentRegion == OMPD_critical ||
  1883. isOpenMPTaskingDirective(ParentRegion) ||
  1884. !(isOpenMPSimdDirective(ParentRegion) ||
  1885. Stack->isParentOrderedRegion());
  1886. Recommend = ShouldBeInOrderedRegion;
  1887. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  1888. // OpenMP [2.16, Nesting of Regions]
  1889. // If specified, a teams construct must be contained within a target
  1890. // construct.
  1891. NestingProhibited = ParentRegion != OMPD_target;
  1892. OrphanSeen = ParentRegion == OMPD_unknown;
  1893. Recommend = ShouldBeInTargetRegion;
  1894. Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
  1895. }
  1896. if (!NestingProhibited &&
  1897. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  1898. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  1899. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  1900. // OpenMP [2.16, Nesting of Regions]
  1901. // distribute, parallel, parallel sections, parallel workshare, and the
  1902. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  1903. // constructs that can be closely nested in the teams region.
  1904. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  1905. !isOpenMPDistributeDirective(CurrentRegion);
  1906. Recommend = ShouldBeInParallelRegion;
  1907. }
  1908. if (!NestingProhibited &&
  1909. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  1910. // OpenMP 4.5 [2.17 Nesting of Regions]
  1911. // The region associated with the distribute construct must be strictly
  1912. // nested inside a teams region
  1913. NestingProhibited =
  1914. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  1915. Recommend = ShouldBeInTeamsRegion;
  1916. }
  1917. if (!NestingProhibited &&
  1918. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  1919. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  1920. // OpenMP 4.5 [2.17 Nesting of Regions]
  1921. // If a target, target update, target data, target enter data, or
  1922. // target exit data construct is encountered during execution of a
  1923. // target region, the behavior is unspecified.
  1924. NestingProhibited = Stack->hasDirective(
  1925. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1926. SourceLocation) -> bool {
  1927. if (isOpenMPTargetExecutionDirective(K)) {
  1928. OffendingRegion = K;
  1929. return true;
  1930. } else
  1931. return false;
  1932. },
  1933. false /* don't skip top directive */);
  1934. CloseNesting = false;
  1935. }
  1936. if (NestingProhibited) {
  1937. if (OrphanSeen) {
  1938. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  1939. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  1940. } else {
  1941. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  1942. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  1943. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  1944. }
  1945. return true;
  1946. }
  1947. }
  1948. return false;
  1949. }
  1950. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  1951. ArrayRef<OMPClause *> Clauses,
  1952. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  1953. bool ErrorFound = false;
  1954. unsigned NamedModifiersNumber = 0;
  1955. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  1956. OMPD_unknown + 1);
  1957. SmallVector<SourceLocation, 4> NameModifierLoc;
  1958. for (const auto *C : Clauses) {
  1959. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  1960. // At most one if clause without a directive-name-modifier can appear on
  1961. // the directive.
  1962. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  1963. if (FoundNameModifiers[CurNM]) {
  1964. S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  1965. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  1966. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  1967. ErrorFound = true;
  1968. } else if (CurNM != OMPD_unknown) {
  1969. NameModifierLoc.push_back(IC->getNameModifierLoc());
  1970. ++NamedModifiersNumber;
  1971. }
  1972. FoundNameModifiers[CurNM] = IC;
  1973. if (CurNM == OMPD_unknown)
  1974. continue;
  1975. // Check if the specified name modifier is allowed for the current
  1976. // directive.
  1977. // At most one if clause with the particular directive-name-modifier can
  1978. // appear on the directive.
  1979. bool MatchFound = false;
  1980. for (auto NM : AllowedNameModifiers) {
  1981. if (CurNM == NM) {
  1982. MatchFound = true;
  1983. break;
  1984. }
  1985. }
  1986. if (!MatchFound) {
  1987. S.Diag(IC->getNameModifierLoc(),
  1988. diag::err_omp_wrong_if_directive_name_modifier)
  1989. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  1990. ErrorFound = true;
  1991. }
  1992. }
  1993. }
  1994. // If any if clause on the directive includes a directive-name-modifier then
  1995. // all if clauses on the directive must include a directive-name-modifier.
  1996. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  1997. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  1998. S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
  1999. diag::err_omp_no_more_if_clause);
  2000. } else {
  2001. std::string Values;
  2002. std::string Sep(", ");
  2003. unsigned AllowedCnt = 0;
  2004. unsigned TotalAllowedNum =
  2005. AllowedNameModifiers.size() - NamedModifiersNumber;
  2006. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  2007. ++Cnt) {
  2008. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  2009. if (!FoundNameModifiers[NM]) {
  2010. Values += "'";
  2011. Values += getOpenMPDirectiveName(NM);
  2012. Values += "'";
  2013. if (AllowedCnt + 2 == TotalAllowedNum)
  2014. Values += " or ";
  2015. else if (AllowedCnt + 1 != TotalAllowedNum)
  2016. Values += Sep;
  2017. ++AllowedCnt;
  2018. }
  2019. }
  2020. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
  2021. diag::err_omp_unnamed_if_clause)
  2022. << (TotalAllowedNum > 1) << Values;
  2023. }
  2024. for (auto Loc : NameModifierLoc) {
  2025. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  2026. }
  2027. ErrorFound = true;
  2028. }
  2029. return ErrorFound;
  2030. }
  2031. StmtResult Sema::ActOnOpenMPExecutableDirective(
  2032. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  2033. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  2034. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  2035. StmtResult Res = StmtError();
  2036. if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  2037. StartLoc))
  2038. return StmtError();
  2039. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  2040. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  2041. bool ErrorFound = false;
  2042. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  2043. if (AStmt) {
  2044. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2045. // Check default data sharing attributes for referenced variables.
  2046. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  2047. DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
  2048. if (DSAChecker.isErrorFound())
  2049. return StmtError();
  2050. // Generate list of implicitly defined firstprivate variables.
  2051. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  2052. if (!DSAChecker.getImplicitFirstprivate().empty()) {
  2053. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  2054. DSAChecker.getImplicitFirstprivate(), SourceLocation(),
  2055. SourceLocation(), SourceLocation())) {
  2056. ClausesWithImplicit.push_back(Implicit);
  2057. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  2058. DSAChecker.getImplicitFirstprivate().size();
  2059. } else
  2060. ErrorFound = true;
  2061. }
  2062. }
  2063. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  2064. switch (Kind) {
  2065. case OMPD_parallel:
  2066. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  2067. EndLoc);
  2068. AllowedNameModifiers.push_back(OMPD_parallel);
  2069. break;
  2070. case OMPD_simd:
  2071. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2072. VarsWithInheritedDSA);
  2073. break;
  2074. case OMPD_for:
  2075. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2076. VarsWithInheritedDSA);
  2077. break;
  2078. case OMPD_for_simd:
  2079. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2080. EndLoc, VarsWithInheritedDSA);
  2081. break;
  2082. case OMPD_sections:
  2083. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2084. EndLoc);
  2085. break;
  2086. case OMPD_section:
  2087. assert(ClausesWithImplicit.empty() &&
  2088. "No clauses are allowed for 'omp section' directive");
  2089. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  2090. break;
  2091. case OMPD_single:
  2092. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  2093. EndLoc);
  2094. break;
  2095. case OMPD_master:
  2096. assert(ClausesWithImplicit.empty() &&
  2097. "No clauses are allowed for 'omp master' directive");
  2098. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  2099. break;
  2100. case OMPD_critical:
  2101. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  2102. StartLoc, EndLoc);
  2103. break;
  2104. case OMPD_parallel_for:
  2105. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  2106. EndLoc, VarsWithInheritedDSA);
  2107. AllowedNameModifiers.push_back(OMPD_parallel);
  2108. break;
  2109. case OMPD_parallel_for_simd:
  2110. Res = ActOnOpenMPParallelForSimdDirective(
  2111. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2112. AllowedNameModifiers.push_back(OMPD_parallel);
  2113. break;
  2114. case OMPD_parallel_sections:
  2115. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  2116. StartLoc, EndLoc);
  2117. AllowedNameModifiers.push_back(OMPD_parallel);
  2118. break;
  2119. case OMPD_task:
  2120. Res =
  2121. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2122. AllowedNameModifiers.push_back(OMPD_task);
  2123. break;
  2124. case OMPD_taskyield:
  2125. assert(ClausesWithImplicit.empty() &&
  2126. "No clauses are allowed for 'omp taskyield' directive");
  2127. assert(AStmt == nullptr &&
  2128. "No associated statement allowed for 'omp taskyield' directive");
  2129. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  2130. break;
  2131. case OMPD_barrier:
  2132. assert(ClausesWithImplicit.empty() &&
  2133. "No clauses are allowed for 'omp barrier' directive");
  2134. assert(AStmt == nullptr &&
  2135. "No associated statement allowed for 'omp barrier' directive");
  2136. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  2137. break;
  2138. case OMPD_taskwait:
  2139. assert(ClausesWithImplicit.empty() &&
  2140. "No clauses are allowed for 'omp taskwait' directive");
  2141. assert(AStmt == nullptr &&
  2142. "No associated statement allowed for 'omp taskwait' directive");
  2143. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  2144. break;
  2145. case OMPD_taskgroup:
  2146. assert(ClausesWithImplicit.empty() &&
  2147. "No clauses are allowed for 'omp taskgroup' directive");
  2148. Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
  2149. break;
  2150. case OMPD_flush:
  2151. assert(AStmt == nullptr &&
  2152. "No associated statement allowed for 'omp flush' directive");
  2153. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  2154. break;
  2155. case OMPD_ordered:
  2156. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  2157. EndLoc);
  2158. break;
  2159. case OMPD_atomic:
  2160. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  2161. EndLoc);
  2162. break;
  2163. case OMPD_teams:
  2164. Res =
  2165. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2166. break;
  2167. case OMPD_target:
  2168. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  2169. EndLoc);
  2170. AllowedNameModifiers.push_back(OMPD_target);
  2171. break;
  2172. case OMPD_target_parallel:
  2173. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  2174. StartLoc, EndLoc);
  2175. AllowedNameModifiers.push_back(OMPD_target);
  2176. AllowedNameModifiers.push_back(OMPD_parallel);
  2177. break;
  2178. case OMPD_target_parallel_for:
  2179. Res = ActOnOpenMPTargetParallelForDirective(
  2180. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2181. AllowedNameModifiers.push_back(OMPD_target);
  2182. AllowedNameModifiers.push_back(OMPD_parallel);
  2183. break;
  2184. case OMPD_cancellation_point:
  2185. assert(ClausesWithImplicit.empty() &&
  2186. "No clauses are allowed for 'omp cancellation point' directive");
  2187. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  2188. "cancellation point' directive");
  2189. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  2190. break;
  2191. case OMPD_cancel:
  2192. assert(AStmt == nullptr &&
  2193. "No associated statement allowed for 'omp cancel' directive");
  2194. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  2195. CancelRegion);
  2196. AllowedNameModifiers.push_back(OMPD_cancel);
  2197. break;
  2198. case OMPD_target_data:
  2199. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  2200. EndLoc);
  2201. AllowedNameModifiers.push_back(OMPD_target_data);
  2202. break;
  2203. case OMPD_target_enter_data:
  2204. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  2205. EndLoc);
  2206. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  2207. break;
  2208. case OMPD_target_exit_data:
  2209. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  2210. EndLoc);
  2211. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  2212. break;
  2213. case OMPD_taskloop:
  2214. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  2215. EndLoc, VarsWithInheritedDSA);
  2216. AllowedNameModifiers.push_back(OMPD_taskloop);
  2217. break;
  2218. case OMPD_taskloop_simd:
  2219. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2220. EndLoc, VarsWithInheritedDSA);
  2221. AllowedNameModifiers.push_back(OMPD_taskloop);
  2222. break;
  2223. case OMPD_distribute:
  2224. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  2225. EndLoc, VarsWithInheritedDSA);
  2226. break;
  2227. case OMPD_target_update:
  2228. assert(!AStmt && "Statement is not allowed for target update");
  2229. Res =
  2230. ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
  2231. AllowedNameModifiers.push_back(OMPD_target_update);
  2232. break;
  2233. case OMPD_distribute_parallel_for:
  2234. Res = ActOnOpenMPDistributeParallelForDirective(
  2235. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2236. AllowedNameModifiers.push_back(OMPD_parallel);
  2237. break;
  2238. case OMPD_distribute_parallel_for_simd:
  2239. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  2240. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2241. AllowedNameModifiers.push_back(OMPD_parallel);
  2242. break;
  2243. case OMPD_distribute_simd:
  2244. Res = ActOnOpenMPDistributeSimdDirective(
  2245. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2246. break;
  2247. case OMPD_target_parallel_for_simd:
  2248. Res = ActOnOpenMPTargetParallelForSimdDirective(
  2249. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2250. AllowedNameModifiers.push_back(OMPD_target);
  2251. AllowedNameModifiers.push_back(OMPD_parallel);
  2252. break;
  2253. case OMPD_target_simd:
  2254. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2255. EndLoc, VarsWithInheritedDSA);
  2256. AllowedNameModifiers.push_back(OMPD_target);
  2257. break;
  2258. case OMPD_teams_distribute:
  2259. Res = ActOnOpenMPTeamsDistributeDirective(
  2260. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2261. break;
  2262. case OMPD_teams_distribute_simd:
  2263. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  2264. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2265. break;
  2266. case OMPD_teams_distribute_parallel_for_simd:
  2267. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  2268. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2269. AllowedNameModifiers.push_back(OMPD_parallel);
  2270. break;
  2271. case OMPD_teams_distribute_parallel_for:
  2272. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  2273. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2274. AllowedNameModifiers.push_back(OMPD_parallel);
  2275. break;
  2276. case OMPD_target_teams:
  2277. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2278. EndLoc);
  2279. AllowedNameModifiers.push_back(OMPD_target);
  2280. break;
  2281. case OMPD_target_teams_distribute:
  2282. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  2283. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2284. AllowedNameModifiers.push_back(OMPD_target);
  2285. break;
  2286. case OMPD_target_teams_distribute_parallel_for:
  2287. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  2288. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2289. AllowedNameModifiers.push_back(OMPD_target);
  2290. AllowedNameModifiers.push_back(OMPD_parallel);
  2291. break;
  2292. case OMPD_declare_target:
  2293. case OMPD_end_declare_target:
  2294. case OMPD_threadprivate:
  2295. case OMPD_declare_reduction:
  2296. case OMPD_declare_simd:
  2297. llvm_unreachable("OpenMP Directive is not allowed");
  2298. case OMPD_unknown:
  2299. llvm_unreachable("Unknown OpenMP directive");
  2300. }
  2301. for (auto P : VarsWithInheritedDSA) {
  2302. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  2303. << P.first << P.second->getSourceRange();
  2304. }
  2305. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  2306. if (!AllowedNameModifiers.empty())
  2307. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  2308. ErrorFound;
  2309. if (ErrorFound)
  2310. return StmtError();
  2311. return Res;
  2312. }
  2313. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  2314. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  2315. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  2316. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  2317. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  2318. assert(Aligneds.size() == Alignments.size());
  2319. assert(Linears.size() == LinModifiers.size());
  2320. assert(Linears.size() == Steps.size());
  2321. if (!DG || DG.get().isNull())
  2322. return DeclGroupPtrTy();
  2323. if (!DG.get().isSingleDecl()) {
  2324. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  2325. return DG;
  2326. }
  2327. auto *ADecl = DG.get().getSingleDecl();
  2328. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  2329. ADecl = FTD->getTemplatedDecl();
  2330. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  2331. if (!FD) {
  2332. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  2333. return DeclGroupPtrTy();
  2334. }
  2335. // OpenMP [2.8.2, declare simd construct, Description]
  2336. // The parameter of the simdlen clause must be a constant positive integer
  2337. // expression.
  2338. ExprResult SL;
  2339. if (Simdlen)
  2340. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  2341. // OpenMP [2.8.2, declare simd construct, Description]
  2342. // The special this pointer can be used as if was one of the arguments to the
  2343. // function in any of the linear, aligned, or uniform clauses.
  2344. // The uniform clause declares one or more arguments to have an invariant
  2345. // value for all concurrent invocations of the function in the execution of a
  2346. // single SIMD loop.
  2347. llvm::DenseMap<Decl *, Expr *> UniformedArgs;
  2348. Expr *UniformedLinearThis = nullptr;
  2349. for (auto *E : Uniforms) {
  2350. E = E->IgnoreParenImpCasts();
  2351. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  2352. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  2353. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  2354. FD->getParamDecl(PVD->getFunctionScopeIndex())
  2355. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  2356. UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
  2357. continue;
  2358. }
  2359. if (isa<CXXThisExpr>(E)) {
  2360. UniformedLinearThis = E;
  2361. continue;
  2362. }
  2363. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  2364. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  2365. }
  2366. // OpenMP [2.8.2, declare simd construct, Description]
  2367. // The aligned clause declares that the object to which each list item points
  2368. // is aligned to the number of bytes expressed in the optional parameter of
  2369. // the aligned clause.
  2370. // The special this pointer can be used as if was one of the arguments to the
  2371. // function in any of the linear, aligned, or uniform clauses.
  2372. // The type of list items appearing in the aligned clause must be array,
  2373. // pointer, reference to array, or reference to pointer.
  2374. llvm::DenseMap<Decl *, Expr *> AlignedArgs;
  2375. Expr *AlignedThis = nullptr;
  2376. for (auto *E : Aligneds) {
  2377. E = E->IgnoreParenImpCasts();
  2378. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  2379. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  2380. auto *CanonPVD = PVD->getCanonicalDecl();
  2381. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  2382. FD->getParamDecl(PVD->getFunctionScopeIndex())
  2383. ->getCanonicalDecl() == CanonPVD) {
  2384. // OpenMP [2.8.1, simd construct, Restrictions]
  2385. // A list-item cannot appear in more than one aligned clause.
  2386. if (AlignedArgs.count(CanonPVD) > 0) {
  2387. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  2388. << 1 << E->getSourceRange();
  2389. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  2390. diag::note_omp_explicit_dsa)
  2391. << getOpenMPClauseName(OMPC_aligned);
  2392. continue;
  2393. }
  2394. AlignedArgs[CanonPVD] = E;
  2395. QualType QTy = PVD->getType()
  2396. .getNonReferenceType()
  2397. .getUnqualifiedType()
  2398. .getCanonicalType();
  2399. const Type *Ty = QTy.getTypePtrOrNull();
  2400. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  2401. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  2402. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  2403. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  2404. }
  2405. continue;
  2406. }
  2407. }
  2408. if (isa<CXXThisExpr>(E)) {
  2409. if (AlignedThis) {
  2410. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  2411. << 2 << E->getSourceRange();
  2412. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  2413. << getOpenMPClauseName(OMPC_aligned);
  2414. }
  2415. AlignedThis = E;
  2416. continue;
  2417. }
  2418. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  2419. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  2420. }
  2421. // The optional parameter of the aligned clause, alignment, must be a constant
  2422. // positive integer expression. If no optional parameter is specified,
  2423. // implementation-defined default alignments for SIMD instructions on the
  2424. // target platforms are assumed.
  2425. SmallVector<Expr *, 4> NewAligns;
  2426. for (auto *E : Alignments) {
  2427. ExprResult Align;
  2428. if (E)
  2429. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  2430. NewAligns.push_back(Align.get());
  2431. }
  2432. // OpenMP [2.8.2, declare simd construct, Description]
  2433. // The linear clause declares one or more list items to be private to a SIMD
  2434. // lane and to have a linear relationship with respect to the iteration space
  2435. // of a loop.
  2436. // The special this pointer can be used as if was one of the arguments to the
  2437. // function in any of the linear, aligned, or uniform clauses.
  2438. // When a linear-step expression is specified in a linear clause it must be
  2439. // either a constant integer expression or an integer-typed parameter that is
  2440. // specified in a uniform clause on the directive.
  2441. llvm::DenseMap<Decl *, Expr *> LinearArgs;
  2442. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  2443. auto MI = LinModifiers.begin();
  2444. for (auto *E : Linears) {
  2445. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  2446. ++MI;
  2447. E = E->IgnoreParenImpCasts();
  2448. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  2449. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  2450. auto *CanonPVD = PVD->getCanonicalDecl();
  2451. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  2452. FD->getParamDecl(PVD->getFunctionScopeIndex())
  2453. ->getCanonicalDecl() == CanonPVD) {
  2454. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  2455. // A list-item cannot appear in more than one linear clause.
  2456. if (LinearArgs.count(CanonPVD) > 0) {
  2457. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  2458. << getOpenMPClauseName(OMPC_linear)
  2459. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  2460. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  2461. diag::note_omp_explicit_dsa)
  2462. << getOpenMPClauseName(OMPC_linear);
  2463. continue;
  2464. }
  2465. // Each argument can appear in at most one uniform or linear clause.
  2466. if (UniformedArgs.count(CanonPVD) > 0) {
  2467. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  2468. << getOpenMPClauseName(OMPC_linear)
  2469. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  2470. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  2471. diag::note_omp_explicit_dsa)
  2472. << getOpenMPClauseName(OMPC_uniform);
  2473. continue;
  2474. }
  2475. LinearArgs[CanonPVD] = E;
  2476. if (E->isValueDependent() || E->isTypeDependent() ||
  2477. E->isInstantiationDependent() ||
  2478. E->containsUnexpandedParameterPack())
  2479. continue;
  2480. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  2481. PVD->getOriginalType());
  2482. continue;
  2483. }
  2484. }
  2485. if (isa<CXXThisExpr>(E)) {
  2486. if (UniformedLinearThis) {
  2487. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  2488. << getOpenMPClauseName(OMPC_linear)
  2489. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  2490. << E->getSourceRange();
  2491. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  2492. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  2493. : OMPC_linear);
  2494. continue;
  2495. }
  2496. UniformedLinearThis = E;
  2497. if (E->isValueDependent() || E->isTypeDependent() ||
  2498. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  2499. continue;
  2500. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  2501. E->getType());
  2502. continue;
  2503. }
  2504. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  2505. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  2506. }
  2507. Expr *Step = nullptr;
  2508. Expr *NewStep = nullptr;
  2509. SmallVector<Expr *, 4> NewSteps;
  2510. for (auto *E : Steps) {
  2511. // Skip the same step expression, it was checked already.
  2512. if (Step == E || !E) {
  2513. NewSteps.push_back(E ? NewStep : nullptr);
  2514. continue;
  2515. }
  2516. Step = E;
  2517. if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
  2518. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  2519. auto *CanonPVD = PVD->getCanonicalDecl();
  2520. if (UniformedArgs.count(CanonPVD) == 0) {
  2521. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  2522. << Step->getSourceRange();
  2523. } else if (E->isValueDependent() || E->isTypeDependent() ||
  2524. E->isInstantiationDependent() ||
  2525. E->containsUnexpandedParameterPack() ||
  2526. CanonPVD->getType()->hasIntegerRepresentation())
  2527. NewSteps.push_back(Step);
  2528. else {
  2529. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  2530. << Step->getSourceRange();
  2531. }
  2532. continue;
  2533. }
  2534. NewStep = Step;
  2535. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  2536. !Step->isInstantiationDependent() &&
  2537. !Step->containsUnexpandedParameterPack()) {
  2538. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  2539. .get();
  2540. if (NewStep)
  2541. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  2542. }
  2543. NewSteps.push_back(NewStep);
  2544. }
  2545. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  2546. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  2547. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  2548. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  2549. const_cast<Expr **>(Linears.data()), Linears.size(),
  2550. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  2551. NewSteps.data(), NewSteps.size(), SR);
  2552. ADecl->addAttr(NewAttr);
  2553. return ConvertDeclToDeclGroup(ADecl);
  2554. }
  2555. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  2556. Stmt *AStmt,
  2557. SourceLocation StartLoc,
  2558. SourceLocation EndLoc) {
  2559. if (!AStmt)
  2560. return StmtError();
  2561. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  2562. // 1.2.2 OpenMP Language Terminology
  2563. // Structured block - An executable statement with a single entry at the
  2564. // top and a single exit at the bottom.
  2565. // The point of exit cannot be a branch out of the structured block.
  2566. // longjmp() and throw() must not violate the entry/exit criteria.
  2567. CS->getCapturedDecl()->setNothrow();
  2568. getCurFunction()->setHasBranchProtectedScope();
  2569. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  2570. DSAStack->isCancelRegion());
  2571. }
  2572. namespace {
  2573. /// \brief Helper class for checking canonical form of the OpenMP loops and
  2574. /// extracting iteration space of each loop in the loop nest, that will be used
  2575. /// for IR generation.
  2576. class OpenMPIterationSpaceChecker {
  2577. /// \brief Reference to Sema.
  2578. Sema &SemaRef;
  2579. /// \brief A location for diagnostics (when there is no some better location).
  2580. SourceLocation DefaultLoc;
  2581. /// \brief A location for diagnostics (when increment is not compatible).
  2582. SourceLocation ConditionLoc;
  2583. /// \brief A source location for referring to loop init later.
  2584. SourceRange InitSrcRange;
  2585. /// \brief A source location for referring to condition later.
  2586. SourceRange ConditionSrcRange;
  2587. /// \brief A source location for referring to increment later.
  2588. SourceRange IncrementSrcRange;
  2589. /// \brief Loop variable.
  2590. ValueDecl *LCDecl = nullptr;
  2591. /// \brief Reference to loop variable.
  2592. Expr *LCRef = nullptr;
  2593. /// \brief Lower bound (initializer for the var).
  2594. Expr *LB = nullptr;
  2595. /// \brief Upper bound.
  2596. Expr *UB = nullptr;
  2597. /// \brief Loop step (increment).
  2598. Expr *Step = nullptr;
  2599. /// \brief This flag is true when condition is one of:
  2600. /// Var < UB
  2601. /// Var <= UB
  2602. /// UB > Var
  2603. /// UB >= Var
  2604. bool TestIsLessOp = false;
  2605. /// \brief This flag is true when condition is strict ( < or > ).
  2606. bool TestIsStrictOp = false;
  2607. /// \brief This flag is true when step is subtracted on each iteration.
  2608. bool SubtractStep = false;
  2609. public:
  2610. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  2611. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  2612. /// \brief Check init-expr for canonical loop form and save loop counter
  2613. /// variable - #Var and its initialization value - #LB.
  2614. bool CheckInit(Stmt *S, bool EmitDiags = true);
  2615. /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
  2616. /// for less/greater and for strict/non-strict comparison.
  2617. bool CheckCond(Expr *S);
  2618. /// \brief Check incr-expr for canonical loop form and return true if it
  2619. /// does not conform, otherwise save loop step (#Step).
  2620. bool CheckInc(Expr *S);
  2621. /// \brief Return the loop counter variable.
  2622. ValueDecl *GetLoopDecl() const { return LCDecl; }
  2623. /// \brief Return the reference expression to loop counter variable.
  2624. Expr *GetLoopDeclRefExpr() const { return LCRef; }
  2625. /// \brief Source range of the loop init.
  2626. SourceRange GetInitSrcRange() const { return InitSrcRange; }
  2627. /// \brief Source range of the loop condition.
  2628. SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
  2629. /// \brief Source range of the loop increment.
  2630. SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
  2631. /// \brief True if the step should be subtracted.
  2632. bool ShouldSubtractStep() const { return SubtractStep; }
  2633. /// \brief Build the expression to calculate the number of iterations.
  2634. Expr *
  2635. BuildNumIterations(Scope *S, const bool LimitedType,
  2636. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
  2637. /// \brief Build the precondition expression for the loops.
  2638. Expr *BuildPreCond(Scope *S, Expr *Cond,
  2639. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
  2640. /// \brief Build reference expression to the counter be used for codegen.
  2641. DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
  2642. DSAStackTy &DSA) const;
  2643. /// \brief Build reference expression to the private counter be used for
  2644. /// codegen.
  2645. Expr *BuildPrivateCounterVar() const;
  2646. /// \brief Build initialization of the counter be used for codegen.
  2647. Expr *BuildCounterInit() const;
  2648. /// \brief Build step of the counter be used for codegen.
  2649. Expr *BuildCounterStep() const;
  2650. /// \brief Return true if any expression is dependent.
  2651. bool Dependent() const;
  2652. private:
  2653. /// \brief Check the right-hand side of an assignment in the increment
  2654. /// expression.
  2655. bool CheckIncRHS(Expr *RHS);
  2656. /// \brief Helper to set loop counter variable and its initializer.
  2657. bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
  2658. /// \brief Helper to set upper bound.
  2659. bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
  2660. SourceLocation SL);
  2661. /// \brief Helper to set loop increment.
  2662. bool SetStep(Expr *NewStep, bool Subtract);
  2663. };
  2664. bool OpenMPIterationSpaceChecker::Dependent() const {
  2665. if (!LCDecl) {
  2666. assert(!LB && !UB && !Step);
  2667. return false;
  2668. }
  2669. return LCDecl->getType()->isDependentType() ||
  2670. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  2671. (Step && Step->isValueDependent());
  2672. }
  2673. static Expr *getExprAsWritten(Expr *E) {
  2674. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
  2675. E = ExprTemp->getSubExpr();
  2676. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  2677. E = MTE->GetTemporaryExpr();
  2678. while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  2679. E = Binder->getSubExpr();
  2680. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  2681. E = ICE->getSubExprAsWritten();
  2682. return E->IgnoreParens();
  2683. }
  2684. bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
  2685. Expr *NewLCRefExpr,
  2686. Expr *NewLB) {
  2687. // State consistency checking to ensure correct usage.
  2688. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  2689. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  2690. if (!NewLCDecl || !NewLB)
  2691. return true;
  2692. LCDecl = getCanonicalDecl(NewLCDecl);
  2693. LCRef = NewLCRefExpr;
  2694. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  2695. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  2696. if ((Ctor->isCopyOrMoveConstructor() ||
  2697. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  2698. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  2699. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  2700. LB = NewLB;
  2701. return false;
  2702. }
  2703. bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
  2704. SourceRange SR, SourceLocation SL) {
  2705. // State consistency checking to ensure correct usage.
  2706. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  2707. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  2708. if (!NewUB)
  2709. return true;
  2710. UB = NewUB;
  2711. TestIsLessOp = LessOp;
  2712. TestIsStrictOp = StrictOp;
  2713. ConditionSrcRange = SR;
  2714. ConditionLoc = SL;
  2715. return false;
  2716. }
  2717. bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
  2718. // State consistency checking to ensure correct usage.
  2719. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  2720. if (!NewStep)
  2721. return true;
  2722. if (!NewStep->isValueDependent()) {
  2723. // Check that the step is integer expression.
  2724. SourceLocation StepLoc = NewStep->getLocStart();
  2725. ExprResult Val =
  2726. SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
  2727. if (Val.isInvalid())
  2728. return true;
  2729. NewStep = Val.get();
  2730. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  2731. // If test-expr is of form var relational-op b and relational-op is < or
  2732. // <= then incr-expr must cause var to increase on each iteration of the
  2733. // loop. If test-expr is of form var relational-op b and relational-op is
  2734. // > or >= then incr-expr must cause var to decrease on each iteration of
  2735. // the loop.
  2736. // If test-expr is of form b relational-op var and relational-op is < or
  2737. // <= then incr-expr must cause var to decrease on each iteration of the
  2738. // loop. If test-expr is of form b relational-op var and relational-op is
  2739. // > or >= then incr-expr must cause var to increase on each iteration of
  2740. // the loop.
  2741. llvm::APSInt Result;
  2742. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  2743. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  2744. bool IsConstNeg =
  2745. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  2746. bool IsConstPos =
  2747. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  2748. bool IsConstZero = IsConstant && !Result.getBoolValue();
  2749. if (UB && (IsConstZero ||
  2750. (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
  2751. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  2752. SemaRef.Diag(NewStep->getExprLoc(),
  2753. diag::err_omp_loop_incr_not_compatible)
  2754. << LCDecl << TestIsLessOp << NewStep->getSourceRange();
  2755. SemaRef.Diag(ConditionLoc,
  2756. diag::note_omp_loop_cond_requres_compatible_incr)
  2757. << TestIsLessOp << ConditionSrcRange;
  2758. return true;
  2759. }
  2760. if (TestIsLessOp == Subtract) {
  2761. NewStep =
  2762. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  2763. .get();
  2764. Subtract = !Subtract;
  2765. }
  2766. }
  2767. Step = NewStep;
  2768. SubtractStep = Subtract;
  2769. return false;
  2770. }
  2771. bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
  2772. // Check init-expr for canonical loop form and save loop counter
  2773. // variable - #Var and its initialization value - #LB.
  2774. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  2775. // var = lb
  2776. // integer-type var = lb
  2777. // random-access-iterator-type var = lb
  2778. // pointer-type var = lb
  2779. //
  2780. if (!S) {
  2781. if (EmitDiags) {
  2782. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  2783. }
  2784. return true;
  2785. }
  2786. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  2787. if (!ExprTemp->cleanupsHaveSideEffects())
  2788. S = ExprTemp->getSubExpr();
  2789. InitSrcRange = S->getSourceRange();
  2790. if (Expr *E = dyn_cast<Expr>(S))
  2791. S = E->IgnoreParens();
  2792. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  2793. if (BO->getOpcode() == BO_Assign) {
  2794. auto *LHS = BO->getLHS()->IgnoreParens();
  2795. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  2796. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  2797. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  2798. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  2799. return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
  2800. }
  2801. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  2802. if (ME->isArrow() &&
  2803. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  2804. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  2805. }
  2806. }
  2807. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  2808. if (DS->isSingleDecl()) {
  2809. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  2810. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  2811. // Accept non-canonical init form here but emit ext. warning.
  2812. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  2813. SemaRef.Diag(S->getLocStart(),
  2814. diag::ext_omp_loop_not_canonical_init)
  2815. << S->getSourceRange();
  2816. return SetLCDeclAndLB(Var, nullptr, Var->getInit());
  2817. }
  2818. }
  2819. }
  2820. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  2821. if (CE->getOperator() == OO_Equal) {
  2822. auto *LHS = CE->getArg(0);
  2823. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  2824. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  2825. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  2826. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  2827. return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
  2828. }
  2829. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  2830. if (ME->isArrow() &&
  2831. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  2832. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  2833. }
  2834. }
  2835. }
  2836. if (Dependent() || SemaRef.CurContext->isDependentContext())
  2837. return false;
  2838. if (EmitDiags) {
  2839. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
  2840. << S->getSourceRange();
  2841. }
  2842. return true;
  2843. }
  2844. /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
  2845. /// variable (which may be the loop variable) if possible.
  2846. static const ValueDecl *GetInitLCDecl(Expr *E) {
  2847. if (!E)
  2848. return nullptr;
  2849. E = getExprAsWritten(E);
  2850. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  2851. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  2852. if ((Ctor->isCopyOrMoveConstructor() ||
  2853. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  2854. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  2855. E = CE->getArg(0)->IgnoreParenImpCasts();
  2856. if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  2857. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  2858. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
  2859. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  2860. return getCanonicalDecl(ME->getMemberDecl());
  2861. return getCanonicalDecl(VD);
  2862. }
  2863. }
  2864. if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
  2865. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  2866. return getCanonicalDecl(ME->getMemberDecl());
  2867. return nullptr;
  2868. }
  2869. bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
  2870. // Check test-expr for canonical form, save upper-bound UB, flags for
  2871. // less/greater and for strict/non-strict comparison.
  2872. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  2873. // var relational-op b
  2874. // b relational-op var
  2875. //
  2876. if (!S) {
  2877. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  2878. return true;
  2879. }
  2880. S = getExprAsWritten(S);
  2881. SourceLocation CondLoc = S->getLocStart();
  2882. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  2883. if (BO->isRelationalOp()) {
  2884. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  2885. return SetUB(BO->getRHS(),
  2886. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  2887. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  2888. BO->getSourceRange(), BO->getOperatorLoc());
  2889. if (GetInitLCDecl(BO->getRHS()) == LCDecl)
  2890. return SetUB(BO->getLHS(),
  2891. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  2892. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  2893. BO->getSourceRange(), BO->getOperatorLoc());
  2894. }
  2895. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  2896. if (CE->getNumArgs() == 2) {
  2897. auto Op = CE->getOperator();
  2898. switch (Op) {
  2899. case OO_Greater:
  2900. case OO_GreaterEqual:
  2901. case OO_Less:
  2902. case OO_LessEqual:
  2903. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  2904. return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  2905. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  2906. CE->getOperatorLoc());
  2907. if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
  2908. return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  2909. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  2910. CE->getOperatorLoc());
  2911. break;
  2912. default:
  2913. break;
  2914. }
  2915. }
  2916. }
  2917. if (Dependent() || SemaRef.CurContext->isDependentContext())
  2918. return false;
  2919. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  2920. << S->getSourceRange() << LCDecl;
  2921. return true;
  2922. }
  2923. bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
  2924. // RHS of canonical loop form increment can be:
  2925. // var + incr
  2926. // incr + var
  2927. // var - incr
  2928. //
  2929. RHS = RHS->IgnoreParenImpCasts();
  2930. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  2931. if (BO->isAdditiveOp()) {
  2932. bool IsAdd = BO->getOpcode() == BO_Add;
  2933. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  2934. return SetStep(BO->getRHS(), !IsAdd);
  2935. if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
  2936. return SetStep(BO->getLHS(), false);
  2937. }
  2938. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  2939. bool IsAdd = CE->getOperator() == OO_Plus;
  2940. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  2941. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  2942. return SetStep(CE->getArg(1), !IsAdd);
  2943. if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
  2944. return SetStep(CE->getArg(0), false);
  2945. }
  2946. }
  2947. if (Dependent() || SemaRef.CurContext->isDependentContext())
  2948. return false;
  2949. SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  2950. << RHS->getSourceRange() << LCDecl;
  2951. return true;
  2952. }
  2953. bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
  2954. // Check incr-expr for canonical loop form and return true if it
  2955. // does not conform.
  2956. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  2957. // ++var
  2958. // var++
  2959. // --var
  2960. // var--
  2961. // var += incr
  2962. // var -= incr
  2963. // var = var + incr
  2964. // var = incr + var
  2965. // var = var - incr
  2966. //
  2967. if (!S) {
  2968. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  2969. return true;
  2970. }
  2971. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  2972. if (!ExprTemp->cleanupsHaveSideEffects())
  2973. S = ExprTemp->getSubExpr();
  2974. IncrementSrcRange = S->getSourceRange();
  2975. S = S->IgnoreParens();
  2976. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  2977. if (UO->isIncrementDecrementOp() &&
  2978. GetInitLCDecl(UO->getSubExpr()) == LCDecl)
  2979. return SetStep(SemaRef
  2980. .ActOnIntegerConstant(UO->getLocStart(),
  2981. (UO->isDecrementOp() ? -1 : 1))
  2982. .get(),
  2983. false);
  2984. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  2985. switch (BO->getOpcode()) {
  2986. case BO_AddAssign:
  2987. case BO_SubAssign:
  2988. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  2989. return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  2990. break;
  2991. case BO_Assign:
  2992. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  2993. return CheckIncRHS(BO->getRHS());
  2994. break;
  2995. default:
  2996. break;
  2997. }
  2998. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  2999. switch (CE->getOperator()) {
  3000. case OO_PlusPlus:
  3001. case OO_MinusMinus:
  3002. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3003. return SetStep(SemaRef
  3004. .ActOnIntegerConstant(
  3005. CE->getLocStart(),
  3006. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  3007. .get(),
  3008. false);
  3009. break;
  3010. case OO_PlusEqual:
  3011. case OO_MinusEqual:
  3012. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3013. return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  3014. break;
  3015. case OO_Equal:
  3016. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3017. return CheckIncRHS(CE->getArg(1));
  3018. break;
  3019. default:
  3020. break;
  3021. }
  3022. }
  3023. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3024. return false;
  3025. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3026. << S->getSourceRange() << LCDecl;
  3027. return true;
  3028. }
  3029. static ExprResult
  3030. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  3031. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3032. if (SemaRef.CurContext->isDependentContext())
  3033. return ExprResult(Capture);
  3034. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  3035. return SemaRef.PerformImplicitConversion(
  3036. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  3037. /*AllowExplicit=*/true);
  3038. auto I = Captures.find(Capture);
  3039. if (I != Captures.end())
  3040. return buildCapture(SemaRef, Capture, I->second);
  3041. DeclRefExpr *Ref = nullptr;
  3042. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  3043. Captures[Capture] = Ref;
  3044. return Res;
  3045. }
  3046. /// \brief Build the expression to calculate the number of iterations.
  3047. Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
  3048. Scope *S, const bool LimitedType,
  3049. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
  3050. ExprResult Diff;
  3051. auto VarType = LCDecl->getType().getNonReferenceType();
  3052. if (VarType->isIntegerType() || VarType->isPointerType() ||
  3053. SemaRef.getLangOpts().CPlusPlus) {
  3054. // Upper - Lower
  3055. auto *UBExpr = TestIsLessOp ? UB : LB;
  3056. auto *LBExpr = TestIsLessOp ? LB : UB;
  3057. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  3058. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  3059. if (!Upper || !Lower)
  3060. return nullptr;
  3061. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  3062. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  3063. // BuildBinOp already emitted error, this one is to point user to upper
  3064. // and lower bound, and to tell what is passed to 'operator-'.
  3065. SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
  3066. << Upper->getSourceRange() << Lower->getSourceRange();
  3067. return nullptr;
  3068. }
  3069. }
  3070. if (!Diff.isUsable())
  3071. return nullptr;
  3072. // Upper - Lower [- 1]
  3073. if (TestIsStrictOp)
  3074. Diff = SemaRef.BuildBinOp(
  3075. S, DefaultLoc, BO_Sub, Diff.get(),
  3076. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3077. if (!Diff.isUsable())
  3078. return nullptr;
  3079. // Upper - Lower [- 1] + Step
  3080. auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
  3081. if (!NewStep.isUsable())
  3082. return nullptr;
  3083. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  3084. if (!Diff.isUsable())
  3085. return nullptr;
  3086. // Parentheses (for dumping/debugging purposes only).
  3087. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  3088. if (!Diff.isUsable())
  3089. return nullptr;
  3090. // (Upper - Lower [- 1] + Step) / Step
  3091. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  3092. if (!Diff.isUsable())
  3093. return nullptr;
  3094. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  3095. QualType Type = Diff.get()->getType();
  3096. auto &C = SemaRef.Context;
  3097. bool UseVarType = VarType->hasIntegerRepresentation() &&
  3098. C.getTypeSize(Type) > C.getTypeSize(VarType);
  3099. if (!Type->isIntegerType() || UseVarType) {
  3100. unsigned NewSize =
  3101. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  3102. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  3103. : Type->hasSignedIntegerRepresentation();
  3104. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  3105. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  3106. Diff = SemaRef.PerformImplicitConversion(
  3107. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  3108. if (!Diff.isUsable())
  3109. return nullptr;
  3110. }
  3111. }
  3112. if (LimitedType) {
  3113. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  3114. if (NewSize != C.getTypeSize(Type)) {
  3115. if (NewSize < C.getTypeSize(Type)) {
  3116. assert(NewSize == 64 && "incorrect loop var size");
  3117. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  3118. << InitSrcRange << ConditionSrcRange;
  3119. }
  3120. QualType NewType = C.getIntTypeForBitwidth(
  3121. NewSize, Type->hasSignedIntegerRepresentation() ||
  3122. C.getTypeSize(Type) < NewSize);
  3123. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  3124. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  3125. Sema::AA_Converting, true);
  3126. if (!Diff.isUsable())
  3127. return nullptr;
  3128. }
  3129. }
  3130. }
  3131. return Diff.get();
  3132. }
  3133. Expr *OpenMPIterationSpaceChecker::BuildPreCond(
  3134. Scope *S, Expr *Cond,
  3135. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
  3136. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  3137. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  3138. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  3139. auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
  3140. auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
  3141. if (!NewLB.isUsable() || !NewUB.isUsable())
  3142. return nullptr;
  3143. auto CondExpr = SemaRef.BuildBinOp(
  3144. S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
  3145. : (TestIsStrictOp ? BO_GT : BO_GE),
  3146. NewLB.get(), NewUB.get());
  3147. if (CondExpr.isUsable()) {
  3148. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  3149. SemaRef.Context.BoolTy))
  3150. CondExpr = SemaRef.PerformImplicitConversion(
  3151. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  3152. /*AllowExplicit=*/true);
  3153. }
  3154. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  3155. // Otherwise use original loop conditon and evaluate it in runtime.
  3156. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  3157. }
  3158. /// \brief Build reference expression to the counter be used for codegen.
  3159. DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
  3160. llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
  3161. auto *VD = dyn_cast<VarDecl>(LCDecl);
  3162. if (!VD) {
  3163. VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
  3164. auto *Ref = buildDeclRefExpr(
  3165. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  3166. DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  3167. // If the loop control decl is explicitly marked as private, do not mark it
  3168. // as captured again.
  3169. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  3170. Captures.insert(std::make_pair(LCRef, Ref));
  3171. return Ref;
  3172. }
  3173. return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
  3174. DefaultLoc);
  3175. }
  3176. Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
  3177. if (LCDecl && !LCDecl->isInvalidDecl()) {
  3178. auto Type = LCDecl->getType().getNonReferenceType();
  3179. auto *PrivateVar =
  3180. buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
  3181. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
  3182. if (PrivateVar->isInvalidDecl())
  3183. return nullptr;
  3184. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  3185. }
  3186. return nullptr;
  3187. }
  3188. /// \brief Build initialization of the counter to be used for codegen.
  3189. Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
  3190. /// \brief Build step of the counter be used for codegen.
  3191. Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
  3192. /// \brief Iteration space of a single for loop.
  3193. struct LoopIterationSpace final {
  3194. /// \brief Condition of the loop.
  3195. Expr *PreCond = nullptr;
  3196. /// \brief This expression calculates the number of iterations in the loop.
  3197. /// It is always possible to calculate it before starting the loop.
  3198. Expr *NumIterations = nullptr;
  3199. /// \brief The loop counter variable.
  3200. Expr *CounterVar = nullptr;
  3201. /// \brief Private loop counter variable.
  3202. Expr *PrivateCounterVar = nullptr;
  3203. /// \brief This is initializer for the initial value of #CounterVar.
  3204. Expr *CounterInit = nullptr;
  3205. /// \brief This is step for the #CounterVar used to generate its update:
  3206. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  3207. Expr *CounterStep = nullptr;
  3208. /// \brief Should step be subtracted?
  3209. bool Subtract = false;
  3210. /// \brief Source range of the loop init.
  3211. SourceRange InitSrcRange;
  3212. /// \brief Source range of the loop condition.
  3213. SourceRange CondSrcRange;
  3214. /// \brief Source range of the loop increment.
  3215. SourceRange IncSrcRange;
  3216. };
  3217. } // namespace
  3218. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  3219. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  3220. assert(Init && "Expected loop in canonical form.");
  3221. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  3222. if (AssociatedLoops > 0 &&
  3223. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  3224. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  3225. if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
  3226. if (auto *D = ISC.GetLoopDecl()) {
  3227. auto *VD = dyn_cast<VarDecl>(D);
  3228. if (!VD) {
  3229. if (auto *Private = IsOpenMPCapturedDecl(D))
  3230. VD = Private;
  3231. else {
  3232. auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
  3233. /*WithInit=*/false);
  3234. VD = cast<VarDecl>(Ref->getDecl());
  3235. }
  3236. }
  3237. DSAStack->addLoopControlVariable(D, VD);
  3238. }
  3239. }
  3240. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  3241. }
  3242. }
  3243. /// \brief Called on a for stmt to check and extract its iteration space
  3244. /// for further processing (such as collapsing).
  3245. static bool CheckOpenMPIterationSpace(
  3246. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  3247. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  3248. Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
  3249. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  3250. LoopIterationSpace &ResultIterSpace,
  3251. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3252. // OpenMP [2.6, Canonical Loop Form]
  3253. // for (init-expr; test-expr; incr-expr) structured-block
  3254. auto *For = dyn_cast_or_null<ForStmt>(S);
  3255. if (!For) {
  3256. SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
  3257. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  3258. << getOpenMPDirectiveName(DKind) << NestedLoopCount
  3259. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  3260. if (NestedLoopCount > 1) {
  3261. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  3262. SemaRef.Diag(DSA.getConstructLoc(),
  3263. diag::note_omp_collapse_ordered_expr)
  3264. << 2 << CollapseLoopCountExpr->getSourceRange()
  3265. << OrderedLoopCountExpr->getSourceRange();
  3266. else if (CollapseLoopCountExpr)
  3267. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  3268. diag::note_omp_collapse_ordered_expr)
  3269. << 0 << CollapseLoopCountExpr->getSourceRange();
  3270. else
  3271. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  3272. diag::note_omp_collapse_ordered_expr)
  3273. << 1 << OrderedLoopCountExpr->getSourceRange();
  3274. }
  3275. return true;
  3276. }
  3277. assert(For->getBody());
  3278. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  3279. // Check init.
  3280. auto Init = For->getInit();
  3281. if (ISC.CheckInit(Init))
  3282. return true;
  3283. bool HasErrors = false;
  3284. // Check loop variable's type.
  3285. if (auto *LCDecl = ISC.GetLoopDecl()) {
  3286. auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
  3287. // OpenMP [2.6, Canonical Loop Form]
  3288. // Var is one of the following:
  3289. // A variable of signed or unsigned integer type.
  3290. // For C++, a variable of a random access iterator type.
  3291. // For C, a variable of a pointer type.
  3292. auto VarType = LCDecl->getType().getNonReferenceType();
  3293. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  3294. !VarType->isPointerType() &&
  3295. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  3296. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
  3297. << SemaRef.getLangOpts().CPlusPlus;
  3298. HasErrors = true;
  3299. }
  3300. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  3301. // a Construct
  3302. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3303. // parallel for construct is (are) private.
  3304. // The loop iteration variable in the associated for-loop of a simd
  3305. // construct with just one associated for-loop is linear with a
  3306. // constant-linear-step that is the increment of the associated for-loop.
  3307. // Exclude loop var from the list of variables with implicitly defined data
  3308. // sharing attributes.
  3309. VarsWithImplicitDSA.erase(LCDecl);
  3310. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  3311. // in a Construct, C/C++].
  3312. // The loop iteration variable in the associated for-loop of a simd
  3313. // construct with just one associated for-loop may be listed in a linear
  3314. // clause with a constant-linear-step that is the increment of the
  3315. // associated for-loop.
  3316. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3317. // parallel for construct may be listed in a private or lastprivate clause.
  3318. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  3319. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  3320. // declared in the loop and it is predetermined as a private.
  3321. auto PredeterminedCKind =
  3322. isOpenMPSimdDirective(DKind)
  3323. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  3324. : OMPC_private;
  3325. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3326. DVar.CKind != PredeterminedCKind) ||
  3327. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  3328. isOpenMPDistributeDirective(DKind)) &&
  3329. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3330. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  3331. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  3332. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
  3333. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  3334. << getOpenMPClauseName(PredeterminedCKind);
  3335. if (DVar.RefExpr == nullptr)
  3336. DVar.CKind = PredeterminedCKind;
  3337. ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  3338. HasErrors = true;
  3339. } else if (LoopDeclRefExpr != nullptr) {
  3340. // Make the loop iteration variable private (for worksharing constructs),
  3341. // linear (for simd directives with the only one associated loop) or
  3342. // lastprivate (for simd directives with several collapsed or ordered
  3343. // loops).
  3344. if (DVar.CKind == OMPC_unknown)
  3345. DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
  3346. [](OpenMPDirectiveKind) -> bool { return true; },
  3347. /*FromParent=*/false);
  3348. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  3349. }
  3350. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  3351. // Check test-expr.
  3352. HasErrors |= ISC.CheckCond(For->getCond());
  3353. // Check incr-expr.
  3354. HasErrors |= ISC.CheckInc(For->getInc());
  3355. }
  3356. if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  3357. return HasErrors;
  3358. // Build the loop's iteration space representation.
  3359. ResultIterSpace.PreCond =
  3360. ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  3361. ResultIterSpace.NumIterations = ISC.BuildNumIterations(
  3362. DSA.getCurScope(),
  3363. (isOpenMPWorksharingDirective(DKind) ||
  3364. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  3365. Captures);
  3366. ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
  3367. ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
  3368. ResultIterSpace.CounterInit = ISC.BuildCounterInit();
  3369. ResultIterSpace.CounterStep = ISC.BuildCounterStep();
  3370. ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
  3371. ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
  3372. ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
  3373. ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
  3374. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  3375. ResultIterSpace.NumIterations == nullptr ||
  3376. ResultIterSpace.CounterVar == nullptr ||
  3377. ResultIterSpace.PrivateCounterVar == nullptr ||
  3378. ResultIterSpace.CounterInit == nullptr ||
  3379. ResultIterSpace.CounterStep == nullptr);
  3380. return HasErrors;
  3381. }
  3382. /// \brief Build 'VarRef = Start.
  3383. static ExprResult
  3384. BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  3385. ExprResult Start,
  3386. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3387. // Build 'VarRef = Start.
  3388. auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  3389. if (!NewStart.isUsable())
  3390. return ExprError();
  3391. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  3392. VarRef.get()->getType())) {
  3393. NewStart = SemaRef.PerformImplicitConversion(
  3394. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  3395. /*AllowExplicit=*/true);
  3396. if (!NewStart.isUsable())
  3397. return ExprError();
  3398. }
  3399. auto Init =
  3400. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  3401. return Init;
  3402. }
  3403. /// \brief Build 'VarRef = Start + Iter * Step'.
  3404. static ExprResult
  3405. BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
  3406. ExprResult VarRef, ExprResult Start, ExprResult Iter,
  3407. ExprResult Step, bool Subtract,
  3408. llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
  3409. // Add parentheses (for debugging purposes only).
  3410. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  3411. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  3412. !Step.isUsable())
  3413. return ExprError();
  3414. ExprResult NewStep = Step;
  3415. if (Captures)
  3416. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  3417. if (NewStep.isInvalid())
  3418. return ExprError();
  3419. ExprResult Update =
  3420. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  3421. if (!Update.isUsable())
  3422. return ExprError();
  3423. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  3424. // 'VarRef = Start (+|-) Iter * Step'.
  3425. ExprResult NewStart = Start;
  3426. if (Captures)
  3427. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  3428. if (NewStart.isInvalid())
  3429. return ExprError();
  3430. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  3431. ExprResult SavedUpdate = Update;
  3432. ExprResult UpdateVal;
  3433. if (VarRef.get()->getType()->isOverloadableType() ||
  3434. NewStart.get()->getType()->isOverloadableType() ||
  3435. Update.get()->getType()->isOverloadableType()) {
  3436. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  3437. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  3438. Update =
  3439. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  3440. if (Update.isUsable()) {
  3441. UpdateVal =
  3442. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  3443. VarRef.get(), SavedUpdate.get());
  3444. if (UpdateVal.isUsable()) {
  3445. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  3446. UpdateVal.get());
  3447. }
  3448. }
  3449. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  3450. }
  3451. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  3452. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  3453. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  3454. NewStart.get(), SavedUpdate.get());
  3455. if (!Update.isUsable())
  3456. return ExprError();
  3457. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  3458. VarRef.get()->getType())) {
  3459. Update = SemaRef.PerformImplicitConversion(
  3460. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  3461. if (!Update.isUsable())
  3462. return ExprError();
  3463. }
  3464. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  3465. }
  3466. return Update;
  3467. }
  3468. /// \brief Convert integer expression \a E to make it have at least \a Bits
  3469. /// bits.
  3470. static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  3471. if (E == nullptr)
  3472. return ExprError();
  3473. auto &C = SemaRef.Context;
  3474. QualType OldType = E->getType();
  3475. unsigned HasBits = C.getTypeSize(OldType);
  3476. if (HasBits >= Bits)
  3477. return ExprResult(E);
  3478. // OK to convert to signed, because new type has more bits than old.
  3479. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  3480. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  3481. true);
  3482. }
  3483. /// \brief Check if the given expression \a E is a constant integer that fits
  3484. /// into \a Bits bits.
  3485. static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
  3486. if (E == nullptr)
  3487. return false;
  3488. llvm::APSInt Result;
  3489. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  3490. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  3491. return false;
  3492. }
  3493. /// Build preinits statement for the given declarations.
  3494. static Stmt *buildPreInits(ASTContext &Context,
  3495. SmallVectorImpl<Decl *> &PreInits) {
  3496. if (!PreInits.empty()) {
  3497. return new (Context) DeclStmt(
  3498. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  3499. SourceLocation(), SourceLocation());
  3500. }
  3501. return nullptr;
  3502. }
  3503. /// Build preinits statement for the given declarations.
  3504. static Stmt *buildPreInits(ASTContext &Context,
  3505. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3506. if (!Captures.empty()) {
  3507. SmallVector<Decl *, 16> PreInits;
  3508. for (auto &Pair : Captures)
  3509. PreInits.push_back(Pair.second->getDecl());
  3510. return buildPreInits(Context, PreInits);
  3511. }
  3512. return nullptr;
  3513. }
  3514. /// Build postupdate expression for the given list of postupdates expressions.
  3515. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  3516. Expr *PostUpdate = nullptr;
  3517. if (!PostUpdates.empty()) {
  3518. for (auto *E : PostUpdates) {
  3519. Expr *ConvE = S.BuildCStyleCastExpr(
  3520. E->getExprLoc(),
  3521. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  3522. E->getExprLoc(), E)
  3523. .get();
  3524. PostUpdate = PostUpdate
  3525. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  3526. PostUpdate, ConvE)
  3527. .get()
  3528. : ConvE;
  3529. }
  3530. }
  3531. return PostUpdate;
  3532. }
  3533. /// \brief Called on a for stmt to check itself and nested loops (if any).
  3534. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  3535. /// number of collapsed loops otherwise.
  3536. static unsigned
  3537. CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  3538. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  3539. DSAStackTy &DSA,
  3540. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  3541. OMPLoopDirective::HelperExprs &Built) {
  3542. unsigned NestedLoopCount = 1;
  3543. if (CollapseLoopCountExpr) {
  3544. // Found 'collapse' clause - calculate collapse number.
  3545. llvm::APSInt Result;
  3546. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  3547. NestedLoopCount = Result.getLimitedValue();
  3548. }
  3549. if (OrderedLoopCountExpr) {
  3550. // Found 'ordered' clause - calculate collapse number.
  3551. llvm::APSInt Result;
  3552. if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  3553. if (Result.getLimitedValue() < NestedLoopCount) {
  3554. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  3555. diag::err_omp_wrong_ordered_loop_count)
  3556. << OrderedLoopCountExpr->getSourceRange();
  3557. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  3558. diag::note_collapse_loop_count)
  3559. << CollapseLoopCountExpr->getSourceRange();
  3560. }
  3561. NestedLoopCount = Result.getLimitedValue();
  3562. }
  3563. }
  3564. // This is helper routine for loop directives (e.g., 'for', 'simd',
  3565. // 'for simd', etc.).
  3566. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  3567. SmallVector<LoopIterationSpace, 4> IterSpaces;
  3568. IterSpaces.resize(NestedLoopCount);
  3569. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  3570. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  3571. if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
  3572. NestedLoopCount, CollapseLoopCountExpr,
  3573. OrderedLoopCountExpr, VarsWithImplicitDSA,
  3574. IterSpaces[Cnt], Captures))
  3575. return 0;
  3576. // Move on to the next nested for loop, or to the loop body.
  3577. // OpenMP [2.8.1, simd construct, Restrictions]
  3578. // All loops associated with the construct must be perfectly nested; that
  3579. // is, there must be no intervening code nor any OpenMP directive between
  3580. // any two loops.
  3581. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  3582. }
  3583. Built.clear(/* size */ NestedLoopCount);
  3584. if (SemaRef.CurContext->isDependentContext())
  3585. return NestedLoopCount;
  3586. // An example of what is generated for the following code:
  3587. //
  3588. // #pragma omp simd collapse(2) ordered(2)
  3589. // for (i = 0; i < NI; ++i)
  3590. // for (k = 0; k < NK; ++k)
  3591. // for (j = J0; j < NJ; j+=2) {
  3592. // <loop body>
  3593. // }
  3594. //
  3595. // We generate the code below.
  3596. // Note: the loop body may be outlined in CodeGen.
  3597. // Note: some counters may be C++ classes, operator- is used to find number of
  3598. // iterations and operator+= to calculate counter value.
  3599. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  3600. // or i64 is currently supported).
  3601. //
  3602. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  3603. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  3604. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  3605. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  3606. // // similar updates for vars in clauses (e.g. 'linear')
  3607. // <loop body (using local i and j)>
  3608. // }
  3609. // i = NI; // assign final values of counters
  3610. // j = NJ;
  3611. //
  3612. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  3613. // the iteration counts of the collapsed for loops.
  3614. // Precondition tests if there is at least one iteration (all conditions are
  3615. // true).
  3616. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  3617. auto N0 = IterSpaces[0].NumIterations;
  3618. ExprResult LastIteration32 = WidenIterationCount(
  3619. 32 /* Bits */, SemaRef
  3620. .PerformImplicitConversion(
  3621. N0->IgnoreImpCasts(), N0->getType(),
  3622. Sema::AA_Converting, /*AllowExplicit=*/true)
  3623. .get(),
  3624. SemaRef);
  3625. ExprResult LastIteration64 = WidenIterationCount(
  3626. 64 /* Bits */, SemaRef
  3627. .PerformImplicitConversion(
  3628. N0->IgnoreImpCasts(), N0->getType(),
  3629. Sema::AA_Converting, /*AllowExplicit=*/true)
  3630. .get(),
  3631. SemaRef);
  3632. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  3633. return NestedLoopCount;
  3634. auto &C = SemaRef.Context;
  3635. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  3636. Scope *CurScope = DSA.getCurScope();
  3637. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  3638. if (PreCond.isUsable()) {
  3639. PreCond =
  3640. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  3641. PreCond.get(), IterSpaces[Cnt].PreCond);
  3642. }
  3643. auto N = IterSpaces[Cnt].NumIterations;
  3644. SourceLocation Loc = N->getExprLoc();
  3645. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  3646. if (LastIteration32.isUsable())
  3647. LastIteration32 = SemaRef.BuildBinOp(
  3648. CurScope, Loc, BO_Mul, LastIteration32.get(),
  3649. SemaRef
  3650. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  3651. Sema::AA_Converting,
  3652. /*AllowExplicit=*/true)
  3653. .get());
  3654. if (LastIteration64.isUsable())
  3655. LastIteration64 = SemaRef.BuildBinOp(
  3656. CurScope, Loc, BO_Mul, LastIteration64.get(),
  3657. SemaRef
  3658. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  3659. Sema::AA_Converting,
  3660. /*AllowExplicit=*/true)
  3661. .get());
  3662. }
  3663. // Choose either the 32-bit or 64-bit version.
  3664. ExprResult LastIteration = LastIteration64;
  3665. if (LastIteration32.isUsable() &&
  3666. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  3667. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  3668. FitsInto(
  3669. 32 /* Bits */,
  3670. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  3671. LastIteration64.get(), SemaRef)))
  3672. LastIteration = LastIteration32;
  3673. QualType VType = LastIteration.get()->getType();
  3674. QualType RealVType = VType;
  3675. QualType StrideVType = VType;
  3676. if (isOpenMPTaskLoopDirective(DKind)) {
  3677. VType =
  3678. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  3679. StrideVType =
  3680. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  3681. }
  3682. if (!LastIteration.isUsable())
  3683. return 0;
  3684. // Save the number of iterations.
  3685. ExprResult NumIterations = LastIteration;
  3686. {
  3687. LastIteration = SemaRef.BuildBinOp(
  3688. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  3689. LastIteration.get(),
  3690. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3691. if (!LastIteration.isUsable())
  3692. return 0;
  3693. }
  3694. // Calculate the last iteration number beforehand instead of doing this on
  3695. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  3696. llvm::APSInt Result;
  3697. bool IsConstant =
  3698. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  3699. ExprResult CalcLastIteration;
  3700. if (!IsConstant) {
  3701. ExprResult SaveRef =
  3702. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  3703. LastIteration = SaveRef;
  3704. // Prepare SaveRef + 1.
  3705. NumIterations = SemaRef.BuildBinOp(
  3706. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  3707. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3708. if (!NumIterations.isUsable())
  3709. return 0;
  3710. }
  3711. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  3712. // Build variables passed into runtime, necessary for worksharing directives.
  3713. ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
  3714. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  3715. isOpenMPDistributeDirective(DKind)) {
  3716. // Lower bound variable, initialized with zero.
  3717. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  3718. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  3719. SemaRef.AddInitializerToDecl(
  3720. LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  3721. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  3722. // Upper bound variable, initialized with last iteration number.
  3723. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  3724. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  3725. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  3726. /*DirectInit*/ false,
  3727. /*TypeMayContainAuto*/ false);
  3728. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  3729. // This will be used to implement clause 'lastprivate'.
  3730. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  3731. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  3732. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  3733. SemaRef.AddInitializerToDecl(
  3734. ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  3735. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  3736. // Stride variable returned by runtime (we initialize it to 1 by default).
  3737. VarDecl *STDecl =
  3738. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  3739. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  3740. SemaRef.AddInitializerToDecl(
  3741. STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  3742. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  3743. // Build expression: UB = min(UB, LastIteration)
  3744. // It is necessary for CodeGen of directives with static scheduling.
  3745. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  3746. UB.get(), LastIteration.get());
  3747. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  3748. InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
  3749. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  3750. CondOp.get());
  3751. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  3752. // If we have a combined directive that combines 'distribute', 'for' or
  3753. // 'simd' we need to be able to access the bounds of the schedule of the
  3754. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  3755. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  3756. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  3757. auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  3758. // We expect to have at least 2 more parameters than the 'parallel'
  3759. // directive does - the lower and upper bounds of the previous schedule.
  3760. assert(CD->getNumParams() >= 4 &&
  3761. "Unexpected number of parameters in loop combined directive");
  3762. // Set the proper type for the bounds given what we learned from the
  3763. // enclosed loops.
  3764. auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  3765. auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  3766. // Previous lower and upper bounds are obtained from the region
  3767. // parameters.
  3768. PrevLB =
  3769. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  3770. PrevUB =
  3771. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  3772. }
  3773. }
  3774. // Build the iteration variable and its initialization before loop.
  3775. ExprResult IV;
  3776. ExprResult Init;
  3777. {
  3778. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  3779. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  3780. Expr *RHS =
  3781. (isOpenMPWorksharingDirective(DKind) ||
  3782. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  3783. ? LB.get()
  3784. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  3785. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  3786. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  3787. }
  3788. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  3789. SourceLocation CondLoc;
  3790. ExprResult Cond =
  3791. (isOpenMPWorksharingDirective(DKind) ||
  3792. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  3793. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  3794. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  3795. NumIterations.get());
  3796. // Loop increment (IV = IV + 1)
  3797. SourceLocation IncLoc;
  3798. ExprResult Inc =
  3799. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  3800. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  3801. if (!Inc.isUsable())
  3802. return 0;
  3803. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  3804. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  3805. if (!Inc.isUsable())
  3806. return 0;
  3807. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  3808. // Used for directives with static scheduling.
  3809. ExprResult NextLB, NextUB;
  3810. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  3811. isOpenMPDistributeDirective(DKind)) {
  3812. // LB + ST
  3813. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  3814. if (!NextLB.isUsable())
  3815. return 0;
  3816. // LB = LB + ST
  3817. NextLB =
  3818. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  3819. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  3820. if (!NextLB.isUsable())
  3821. return 0;
  3822. // UB + ST
  3823. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  3824. if (!NextUB.isUsable())
  3825. return 0;
  3826. // UB = UB + ST
  3827. NextUB =
  3828. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  3829. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  3830. if (!NextUB.isUsable())
  3831. return 0;
  3832. }
  3833. // Build updates and final values of the loop counters.
  3834. bool HasErrors = false;
  3835. Built.Counters.resize(NestedLoopCount);
  3836. Built.Inits.resize(NestedLoopCount);
  3837. Built.Updates.resize(NestedLoopCount);
  3838. Built.Finals.resize(NestedLoopCount);
  3839. SmallVector<Expr *, 4> LoopMultipliers;
  3840. {
  3841. ExprResult Div;
  3842. // Go from inner nested loop to outer.
  3843. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  3844. LoopIterationSpace &IS = IterSpaces[Cnt];
  3845. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  3846. // Build: Iter = (IV / Div) % IS.NumIters
  3847. // where Div is product of previous iterations' IS.NumIters.
  3848. ExprResult Iter;
  3849. if (Div.isUsable()) {
  3850. Iter =
  3851. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  3852. } else {
  3853. Iter = IV;
  3854. assert((Cnt == (int)NestedLoopCount - 1) &&
  3855. "unusable div expected on first iteration only");
  3856. }
  3857. if (Cnt != 0 && Iter.isUsable())
  3858. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  3859. IS.NumIterations);
  3860. if (!Iter.isUsable()) {
  3861. HasErrors = true;
  3862. break;
  3863. }
  3864. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  3865. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  3866. auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
  3867. IS.CounterVar->getExprLoc(),
  3868. /*RefersToCapture=*/true);
  3869. ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  3870. IS.CounterInit, Captures);
  3871. if (!Init.isUsable()) {
  3872. HasErrors = true;
  3873. break;
  3874. }
  3875. ExprResult Update = BuildCounterUpdate(
  3876. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  3877. IS.CounterStep, IS.Subtract, &Captures);
  3878. if (!Update.isUsable()) {
  3879. HasErrors = true;
  3880. break;
  3881. }
  3882. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  3883. ExprResult Final = BuildCounterUpdate(
  3884. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  3885. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  3886. if (!Final.isUsable()) {
  3887. HasErrors = true;
  3888. break;
  3889. }
  3890. // Build Div for the next iteration: Div <- Div * IS.NumIters
  3891. if (Cnt != 0) {
  3892. if (Div.isUnset())
  3893. Div = IS.NumIterations;
  3894. else
  3895. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  3896. IS.NumIterations);
  3897. // Add parentheses (for debugging purposes only).
  3898. if (Div.isUsable())
  3899. Div = tryBuildCapture(SemaRef, Div.get(), Captures);
  3900. if (!Div.isUsable()) {
  3901. HasErrors = true;
  3902. break;
  3903. }
  3904. LoopMultipliers.push_back(Div.get());
  3905. }
  3906. if (!Update.isUsable() || !Final.isUsable()) {
  3907. HasErrors = true;
  3908. break;
  3909. }
  3910. // Save results
  3911. Built.Counters[Cnt] = IS.CounterVar;
  3912. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  3913. Built.Inits[Cnt] = Init.get();
  3914. Built.Updates[Cnt] = Update.get();
  3915. Built.Finals[Cnt] = Final.get();
  3916. }
  3917. }
  3918. if (HasErrors)
  3919. return 0;
  3920. // Save results
  3921. Built.IterationVarRef = IV.get();
  3922. Built.LastIteration = LastIteration.get();
  3923. Built.NumIterations = NumIterations.get();
  3924. Built.CalcLastIteration =
  3925. SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
  3926. Built.PreCond = PreCond.get();
  3927. Built.PreInits = buildPreInits(C, Captures);
  3928. Built.Cond = Cond.get();
  3929. Built.Init = Init.get();
  3930. Built.Inc = Inc.get();
  3931. Built.LB = LB.get();
  3932. Built.UB = UB.get();
  3933. Built.IL = IL.get();
  3934. Built.ST = ST.get();
  3935. Built.EUB = EUB.get();
  3936. Built.NLB = NextLB.get();
  3937. Built.NUB = NextUB.get();
  3938. Built.PrevLB = PrevLB.get();
  3939. Built.PrevUB = PrevUB.get();
  3940. Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
  3941. // Fill data for doacross depend clauses.
  3942. for (auto Pair : DSA.getDoacrossDependClauses()) {
  3943. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  3944. Pair.first->setCounterValue(CounterVal);
  3945. else {
  3946. if (NestedLoopCount != Pair.second.size() ||
  3947. NestedLoopCount != LoopMultipliers.size() + 1) {
  3948. // Erroneous case - clause has some problems.
  3949. Pair.first->setCounterValue(CounterVal);
  3950. continue;
  3951. }
  3952. assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
  3953. auto I = Pair.second.rbegin();
  3954. auto IS = IterSpaces.rbegin();
  3955. auto ILM = LoopMultipliers.rbegin();
  3956. Expr *UpCounterVal = CounterVal;
  3957. Expr *Multiplier = nullptr;
  3958. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  3959. if (I->first) {
  3960. assert(IS->CounterStep);
  3961. Expr *NormalizedOffset =
  3962. SemaRef
  3963. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
  3964. I->first, IS->CounterStep)
  3965. .get();
  3966. if (Multiplier) {
  3967. NormalizedOffset =
  3968. SemaRef
  3969. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
  3970. NormalizedOffset, Multiplier)
  3971. .get();
  3972. }
  3973. assert(I->second == OO_Plus || I->second == OO_Minus);
  3974. BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
  3975. UpCounterVal = SemaRef
  3976. .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
  3977. UpCounterVal, NormalizedOffset)
  3978. .get();
  3979. }
  3980. Multiplier = *ILM;
  3981. ++I;
  3982. ++IS;
  3983. ++ILM;
  3984. }
  3985. Pair.first->setCounterValue(UpCounterVal);
  3986. }
  3987. }
  3988. return NestedLoopCount;
  3989. }
  3990. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  3991. auto CollapseClauses =
  3992. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  3993. if (CollapseClauses.begin() != CollapseClauses.end())
  3994. return (*CollapseClauses.begin())->getNumForLoops();
  3995. return nullptr;
  3996. }
  3997. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  3998. auto OrderedClauses =
  3999. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  4000. if (OrderedClauses.begin() != OrderedClauses.end())
  4001. return (*OrderedClauses.begin())->getNumForLoops();
  4002. return nullptr;
  4003. }
  4004. static bool checkSimdlenSafelenSpecified(Sema &S,
  4005. const ArrayRef<OMPClause *> Clauses) {
  4006. OMPSafelenClause *Safelen = nullptr;
  4007. OMPSimdlenClause *Simdlen = nullptr;
  4008. for (auto *Clause : Clauses) {
  4009. if (Clause->getClauseKind() == OMPC_safelen)
  4010. Safelen = cast<OMPSafelenClause>(Clause);
  4011. else if (Clause->getClauseKind() == OMPC_simdlen)
  4012. Simdlen = cast<OMPSimdlenClause>(Clause);
  4013. if (Safelen && Simdlen)
  4014. break;
  4015. }
  4016. if (Simdlen && Safelen) {
  4017. llvm::APSInt SimdlenRes, SafelenRes;
  4018. auto SimdlenLength = Simdlen->getSimdlen();
  4019. auto SafelenLength = Safelen->getSafelen();
  4020. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  4021. SimdlenLength->isInstantiationDependent() ||
  4022. SimdlenLength->containsUnexpandedParameterPack())
  4023. return false;
  4024. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  4025. SafelenLength->isInstantiationDependent() ||
  4026. SafelenLength->containsUnexpandedParameterPack())
  4027. return false;
  4028. SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
  4029. SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
  4030. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  4031. // If both simdlen and safelen clauses are specified, the value of the
  4032. // simdlen parameter must be less than or equal to the value of the safelen
  4033. // parameter.
  4034. if (SimdlenRes > SafelenRes) {
  4035. S.Diag(SimdlenLength->getExprLoc(),
  4036. diag::err_omp_wrong_simdlen_safelen_values)
  4037. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  4038. return true;
  4039. }
  4040. }
  4041. return false;
  4042. }
  4043. StmtResult Sema::ActOnOpenMPSimdDirective(
  4044. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4045. SourceLocation EndLoc,
  4046. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4047. if (!AStmt)
  4048. return StmtError();
  4049. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4050. OMPLoopDirective::HelperExprs B;
  4051. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4052. // define the nested loops number.
  4053. unsigned NestedLoopCount = CheckOpenMPLoop(
  4054. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4055. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4056. if (NestedLoopCount == 0)
  4057. return StmtError();
  4058. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4059. "omp simd loop exprs were not built");
  4060. if (!CurContext->isDependentContext()) {
  4061. // Finalize the clauses that need pre-built expressions for CodeGen.
  4062. for (auto C : Clauses) {
  4063. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4064. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4065. B.NumIterations, *this, CurScope,
  4066. DSAStack))
  4067. return StmtError();
  4068. }
  4069. }
  4070. if (checkSimdlenSafelenSpecified(*this, Clauses))
  4071. return StmtError();
  4072. getCurFunction()->setHasBranchProtectedScope();
  4073. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4074. Clauses, AStmt, B);
  4075. }
  4076. StmtResult Sema::ActOnOpenMPForDirective(
  4077. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4078. SourceLocation EndLoc,
  4079. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4080. if (!AStmt)
  4081. return StmtError();
  4082. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4083. OMPLoopDirective::HelperExprs B;
  4084. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4085. // define the nested loops number.
  4086. unsigned NestedLoopCount = CheckOpenMPLoop(
  4087. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4088. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4089. if (NestedLoopCount == 0)
  4090. return StmtError();
  4091. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4092. "omp for loop exprs were not built");
  4093. if (!CurContext->isDependentContext()) {
  4094. // Finalize the clauses that need pre-built expressions for CodeGen.
  4095. for (auto C : Clauses) {
  4096. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4097. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4098. B.NumIterations, *this, CurScope,
  4099. DSAStack))
  4100. return StmtError();
  4101. }
  4102. }
  4103. getCurFunction()->setHasBranchProtectedScope();
  4104. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4105. Clauses, AStmt, B, DSAStack->isCancelRegion());
  4106. }
  4107. StmtResult Sema::ActOnOpenMPForSimdDirective(
  4108. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4109. SourceLocation EndLoc,
  4110. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4111. if (!AStmt)
  4112. return StmtError();
  4113. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4114. OMPLoopDirective::HelperExprs B;
  4115. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4116. // define the nested loops number.
  4117. unsigned NestedLoopCount =
  4118. CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  4119. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  4120. VarsWithImplicitDSA, B);
  4121. if (NestedLoopCount == 0)
  4122. return StmtError();
  4123. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4124. "omp for simd loop exprs were not built");
  4125. if (!CurContext->isDependentContext()) {
  4126. // Finalize the clauses that need pre-built expressions for CodeGen.
  4127. for (auto C : Clauses) {
  4128. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4129. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4130. B.NumIterations, *this, CurScope,
  4131. DSAStack))
  4132. return StmtError();
  4133. }
  4134. }
  4135. if (checkSimdlenSafelenSpecified(*this, Clauses))
  4136. return StmtError();
  4137. getCurFunction()->setHasBranchProtectedScope();
  4138. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4139. Clauses, AStmt, B);
  4140. }
  4141. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  4142. Stmt *AStmt,
  4143. SourceLocation StartLoc,
  4144. SourceLocation EndLoc) {
  4145. if (!AStmt)
  4146. return StmtError();
  4147. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4148. auto BaseStmt = AStmt;
  4149. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  4150. BaseStmt = CS->getCapturedStmt();
  4151. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  4152. auto S = C->children();
  4153. if (S.begin() == S.end())
  4154. return StmtError();
  4155. // All associated statements must be '#pragma omp section' except for
  4156. // the first one.
  4157. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  4158. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  4159. if (SectionStmt)
  4160. Diag(SectionStmt->getLocStart(),
  4161. diag::err_omp_sections_substmt_not_section);
  4162. return StmtError();
  4163. }
  4164. cast<OMPSectionDirective>(SectionStmt)
  4165. ->setHasCancel(DSAStack->isCancelRegion());
  4166. }
  4167. } else {
  4168. Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
  4169. return StmtError();
  4170. }
  4171. getCurFunction()->setHasBranchProtectedScope();
  4172. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4173. DSAStack->isCancelRegion());
  4174. }
  4175. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  4176. SourceLocation StartLoc,
  4177. SourceLocation EndLoc) {
  4178. if (!AStmt)
  4179. return StmtError();
  4180. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4181. getCurFunction()->setHasBranchProtectedScope();
  4182. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  4183. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  4184. DSAStack->isCancelRegion());
  4185. }
  4186. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  4187. Stmt *AStmt,
  4188. SourceLocation StartLoc,
  4189. SourceLocation EndLoc) {
  4190. if (!AStmt)
  4191. return StmtError();
  4192. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4193. getCurFunction()->setHasBranchProtectedScope();
  4194. // OpenMP [2.7.3, single Construct, Restrictions]
  4195. // The copyprivate clause must not be used with the nowait clause.
  4196. OMPClause *Nowait = nullptr;
  4197. OMPClause *Copyprivate = nullptr;
  4198. for (auto *Clause : Clauses) {
  4199. if (Clause->getClauseKind() == OMPC_nowait)
  4200. Nowait = Clause;
  4201. else if (Clause->getClauseKind() == OMPC_copyprivate)
  4202. Copyprivate = Clause;
  4203. if (Copyprivate && Nowait) {
  4204. Diag(Copyprivate->getLocStart(),
  4205. diag::err_omp_single_copyprivate_with_nowait);
  4206. Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
  4207. return StmtError();
  4208. }
  4209. }
  4210. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  4211. }
  4212. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  4213. SourceLocation StartLoc,
  4214. SourceLocation EndLoc) {
  4215. if (!AStmt)
  4216. return StmtError();
  4217. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4218. getCurFunction()->setHasBranchProtectedScope();
  4219. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  4220. }
  4221. StmtResult Sema::ActOnOpenMPCriticalDirective(
  4222. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  4223. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  4224. if (!AStmt)
  4225. return StmtError();
  4226. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4227. bool ErrorFound = false;
  4228. llvm::APSInt Hint;
  4229. SourceLocation HintLoc;
  4230. bool DependentHint = false;
  4231. for (auto *C : Clauses) {
  4232. if (C->getClauseKind() == OMPC_hint) {
  4233. if (!DirName.getName()) {
  4234. Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
  4235. ErrorFound = true;
  4236. }
  4237. Expr *E = cast<OMPHintClause>(C)->getHint();
  4238. if (E->isTypeDependent() || E->isValueDependent() ||
  4239. E->isInstantiationDependent())
  4240. DependentHint = true;
  4241. else {
  4242. Hint = E->EvaluateKnownConstInt(Context);
  4243. HintLoc = C->getLocStart();
  4244. }
  4245. }
  4246. }
  4247. if (ErrorFound)
  4248. return StmtError();
  4249. auto Pair = DSAStack->getCriticalWithHint(DirName);
  4250. if (Pair.first && DirName.getName() && !DependentHint) {
  4251. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  4252. Diag(StartLoc, diag::err_omp_critical_with_hint);
  4253. if (HintLoc.isValid()) {
  4254. Diag(HintLoc, diag::note_omp_critical_hint_here)
  4255. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  4256. } else
  4257. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  4258. if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  4259. Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
  4260. << 1
  4261. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  4262. /*Radix=*/10, /*Signed=*/false);
  4263. } else
  4264. Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
  4265. }
  4266. }
  4267. getCurFunction()->setHasBranchProtectedScope();
  4268. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  4269. Clauses, AStmt);
  4270. if (!Pair.first && DirName.getName() && !DependentHint)
  4271. DSAStack->addCriticalWithHint(Dir, Hint);
  4272. return Dir;
  4273. }
  4274. StmtResult Sema::ActOnOpenMPParallelForDirective(
  4275. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4276. SourceLocation EndLoc,
  4277. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4278. if (!AStmt)
  4279. return StmtError();
  4280. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  4281. // 1.2.2 OpenMP Language Terminology
  4282. // Structured block - An executable statement with a single entry at the
  4283. // top and a single exit at the bottom.
  4284. // The point of exit cannot be a branch out of the structured block.
  4285. // longjmp() and throw() must not violate the entry/exit criteria.
  4286. CS->getCapturedDecl()->setNothrow();
  4287. OMPLoopDirective::HelperExprs B;
  4288. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4289. // define the nested loops number.
  4290. unsigned NestedLoopCount =
  4291. CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  4292. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  4293. VarsWithImplicitDSA, B);
  4294. if (NestedLoopCount == 0)
  4295. return StmtError();
  4296. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4297. "omp parallel for loop exprs were not built");
  4298. if (!CurContext->isDependentContext()) {
  4299. // Finalize the clauses that need pre-built expressions for CodeGen.
  4300. for (auto C : Clauses) {
  4301. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4302. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4303. B.NumIterations, *this, CurScope,
  4304. DSAStack))
  4305. return StmtError();
  4306. }
  4307. }
  4308. getCurFunction()->setHasBranchProtectedScope();
  4309. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  4310. NestedLoopCount, Clauses, AStmt, B,
  4311. DSAStack->isCancelRegion());
  4312. }
  4313. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  4314. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4315. SourceLocation EndLoc,
  4316. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4317. if (!AStmt)
  4318. return StmtError();
  4319. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  4320. // 1.2.2 OpenMP Language Terminology
  4321. // Structured block - An executable statement with a single entry at the
  4322. // top and a single exit at the bottom.
  4323. // The point of exit cannot be a branch out of the structured block.
  4324. // longjmp() and throw() must not violate the entry/exit criteria.
  4325. CS->getCapturedDecl()->setNothrow();
  4326. OMPLoopDirective::HelperExprs B;
  4327. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4328. // define the nested loops number.
  4329. unsigned NestedLoopCount =
  4330. CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  4331. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  4332. VarsWithImplicitDSA, B);
  4333. if (NestedLoopCount == 0)
  4334. return StmtError();
  4335. if (!CurContext->isDependentContext()) {
  4336. // Finalize the clauses that need pre-built expressions for CodeGen.
  4337. for (auto C : Clauses) {
  4338. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4339. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4340. B.NumIterations, *this, CurScope,
  4341. DSAStack))
  4342. return StmtError();
  4343. }
  4344. }
  4345. if (checkSimdlenSafelenSpecified(*this, Clauses))
  4346. return StmtError();
  4347. getCurFunction()->setHasBranchProtectedScope();
  4348. return OMPParallelForSimdDirective::Create(
  4349. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  4350. }
  4351. StmtResult
  4352. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  4353. Stmt *AStmt, SourceLocation StartLoc,
  4354. SourceLocation EndLoc) {
  4355. if (!AStmt)
  4356. return StmtError();
  4357. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4358. auto BaseStmt = AStmt;
  4359. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  4360. BaseStmt = CS->getCapturedStmt();
  4361. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  4362. auto S = C->children();
  4363. if (S.begin() == S.end())
  4364. return StmtError();
  4365. // All associated statements must be '#pragma omp section' except for
  4366. // the first one.
  4367. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  4368. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  4369. if (SectionStmt)
  4370. Diag(SectionStmt->getLocStart(),
  4371. diag::err_omp_parallel_sections_substmt_not_section);
  4372. return StmtError();
  4373. }
  4374. cast<OMPSectionDirective>(SectionStmt)
  4375. ->setHasCancel(DSAStack->isCancelRegion());
  4376. }
  4377. } else {
  4378. Diag(AStmt->getLocStart(),
  4379. diag::err_omp_parallel_sections_not_compound_stmt);
  4380. return StmtError();
  4381. }
  4382. getCurFunction()->setHasBranchProtectedScope();
  4383. return OMPParallelSectionsDirective::Create(
  4384. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  4385. }
  4386. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  4387. Stmt *AStmt, SourceLocation StartLoc,
  4388. SourceLocation EndLoc) {
  4389. if (!AStmt)
  4390. return StmtError();
  4391. auto *CS = cast<CapturedStmt>(AStmt);
  4392. // 1.2.2 OpenMP Language Terminology
  4393. // Structured block - An executable statement with a single entry at the
  4394. // top and a single exit at the bottom.
  4395. // The point of exit cannot be a branch out of the structured block.
  4396. // longjmp() and throw() must not violate the entry/exit criteria.
  4397. CS->getCapturedDecl()->setNothrow();
  4398. getCurFunction()->setHasBranchProtectedScope();
  4399. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4400. DSAStack->isCancelRegion());
  4401. }
  4402. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  4403. SourceLocation EndLoc) {
  4404. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  4405. }
  4406. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  4407. SourceLocation EndLoc) {
  4408. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  4409. }
  4410. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  4411. SourceLocation EndLoc) {
  4412. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  4413. }
  4414. StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
  4415. SourceLocation StartLoc,
  4416. SourceLocation EndLoc) {
  4417. if (!AStmt)
  4418. return StmtError();
  4419. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4420. getCurFunction()->setHasBranchProtectedScope();
  4421. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
  4422. }
  4423. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  4424. SourceLocation StartLoc,
  4425. SourceLocation EndLoc) {
  4426. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  4427. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  4428. }
  4429. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  4430. Stmt *AStmt,
  4431. SourceLocation StartLoc,
  4432. SourceLocation EndLoc) {
  4433. OMPClause *DependFound = nullptr;
  4434. OMPClause *DependSourceClause = nullptr;
  4435. OMPClause *DependSinkClause = nullptr;
  4436. bool ErrorFound = false;
  4437. OMPThreadsClause *TC = nullptr;
  4438. OMPSIMDClause *SC = nullptr;
  4439. for (auto *C : Clauses) {
  4440. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  4441. DependFound = C;
  4442. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  4443. if (DependSourceClause) {
  4444. Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  4445. << getOpenMPDirectiveName(OMPD_ordered)
  4446. << getOpenMPClauseName(OMPC_depend) << 2;
  4447. ErrorFound = true;
  4448. } else
  4449. DependSourceClause = C;
  4450. if (DependSinkClause) {
  4451. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  4452. << 0;
  4453. ErrorFound = true;
  4454. }
  4455. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  4456. if (DependSourceClause) {
  4457. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  4458. << 1;
  4459. ErrorFound = true;
  4460. }
  4461. DependSinkClause = C;
  4462. }
  4463. } else if (C->getClauseKind() == OMPC_threads)
  4464. TC = cast<OMPThreadsClause>(C);
  4465. else if (C->getClauseKind() == OMPC_simd)
  4466. SC = cast<OMPSIMDClause>(C);
  4467. }
  4468. if (!ErrorFound && !SC &&
  4469. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  4470. // OpenMP [2.8.1,simd Construct, Restrictions]
  4471. // An ordered construct with the simd clause is the only OpenMP construct
  4472. // that can appear in the simd region.
  4473. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  4474. ErrorFound = true;
  4475. } else if (DependFound && (TC || SC)) {
  4476. Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
  4477. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  4478. ErrorFound = true;
  4479. } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
  4480. Diag(DependFound->getLocStart(),
  4481. diag::err_omp_ordered_directive_without_param);
  4482. ErrorFound = true;
  4483. } else if (TC || Clauses.empty()) {
  4484. if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
  4485. SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
  4486. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  4487. << (TC != nullptr);
  4488. Diag(Param->getLocStart(), diag::note_omp_ordered_param);
  4489. ErrorFound = true;
  4490. }
  4491. }
  4492. if ((!AStmt && !DependFound) || ErrorFound)
  4493. return StmtError();
  4494. if (AStmt) {
  4495. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4496. getCurFunction()->setHasBranchProtectedScope();
  4497. }
  4498. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  4499. }
  4500. namespace {
  4501. /// \brief Helper class for checking expression in 'omp atomic [update]'
  4502. /// construct.
  4503. class OpenMPAtomicUpdateChecker {
  4504. /// \brief Error results for atomic update expressions.
  4505. enum ExprAnalysisErrorCode {
  4506. /// \brief A statement is not an expression statement.
  4507. NotAnExpression,
  4508. /// \brief Expression is not builtin binary or unary operation.
  4509. NotABinaryOrUnaryExpression,
  4510. /// \brief Unary operation is not post-/pre- increment/decrement operation.
  4511. NotAnUnaryIncDecExpression,
  4512. /// \brief An expression is not of scalar type.
  4513. NotAScalarType,
  4514. /// \brief A binary operation is not an assignment operation.
  4515. NotAnAssignmentOp,
  4516. /// \brief RHS part of the binary operation is not a binary expression.
  4517. NotABinaryExpression,
  4518. /// \brief RHS part is not additive/multiplicative/shift/biwise binary
  4519. /// expression.
  4520. NotABinaryOperator,
  4521. /// \brief RHS binary operation does not have reference to the updated LHS
  4522. /// part.
  4523. NotAnUpdateExpression,
  4524. /// \brief No errors is found.
  4525. NoError
  4526. };
  4527. /// \brief Reference to Sema.
  4528. Sema &SemaRef;
  4529. /// \brief A location for note diagnostics (when error is found).
  4530. SourceLocation NoteLoc;
  4531. /// \brief 'x' lvalue part of the source atomic expression.
  4532. Expr *X;
  4533. /// \brief 'expr' rvalue part of the source atomic expression.
  4534. Expr *E;
  4535. /// \brief Helper expression of the form
  4536. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  4537. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  4538. Expr *UpdateExpr;
  4539. /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
  4540. /// important for non-associative operations.
  4541. bool IsXLHSInRHSPart;
  4542. BinaryOperatorKind Op;
  4543. SourceLocation OpLoc;
  4544. /// \brief true if the source expression is a postfix unary operation, false
  4545. /// if it is a prefix unary operation.
  4546. bool IsPostfixUpdate;
  4547. public:
  4548. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  4549. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  4550. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  4551. /// \brief Check specified statement that it is suitable for 'atomic update'
  4552. /// constructs and extract 'x', 'expr' and Operation from the original
  4553. /// expression. If DiagId and NoteId == 0, then only check is performed
  4554. /// without error notification.
  4555. /// \param DiagId Diagnostic which should be emitted if error is found.
  4556. /// \param NoteId Diagnostic note for the main error message.
  4557. /// \return true if statement is not an update expression, false otherwise.
  4558. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  4559. /// \brief Return the 'x' lvalue part of the source atomic expression.
  4560. Expr *getX() const { return X; }
  4561. /// \brief Return the 'expr' rvalue part of the source atomic expression.
  4562. Expr *getExpr() const { return E; }
  4563. /// \brief Return the update expression used in calculation of the updated
  4564. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  4565. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  4566. Expr *getUpdateExpr() const { return UpdateExpr; }
  4567. /// \brief Return true if 'x' is LHS in RHS part of full update expression,
  4568. /// false otherwise.
  4569. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  4570. /// \brief true if the source expression is a postfix unary operation, false
  4571. /// if it is a prefix unary operation.
  4572. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  4573. private:
  4574. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  4575. unsigned NoteId = 0);
  4576. };
  4577. } // namespace
  4578. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  4579. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  4580. ExprAnalysisErrorCode ErrorFound = NoError;
  4581. SourceLocation ErrorLoc, NoteLoc;
  4582. SourceRange ErrorRange, NoteRange;
  4583. // Allowed constructs are:
  4584. // x = x binop expr;
  4585. // x = expr binop x;
  4586. if (AtomicBinOp->getOpcode() == BO_Assign) {
  4587. X = AtomicBinOp->getLHS();
  4588. if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  4589. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  4590. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  4591. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  4592. AtomicInnerBinOp->isBitwiseOp()) {
  4593. Op = AtomicInnerBinOp->getOpcode();
  4594. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  4595. auto *LHS = AtomicInnerBinOp->getLHS();
  4596. auto *RHS = AtomicInnerBinOp->getRHS();
  4597. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  4598. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  4599. /*Canonical=*/true);
  4600. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  4601. /*Canonical=*/true);
  4602. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  4603. /*Canonical=*/true);
  4604. if (XId == LHSId) {
  4605. E = RHS;
  4606. IsXLHSInRHSPart = true;
  4607. } else if (XId == RHSId) {
  4608. E = LHS;
  4609. IsXLHSInRHSPart = false;
  4610. } else {
  4611. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  4612. ErrorRange = AtomicInnerBinOp->getSourceRange();
  4613. NoteLoc = X->getExprLoc();
  4614. NoteRange = X->getSourceRange();
  4615. ErrorFound = NotAnUpdateExpression;
  4616. }
  4617. } else {
  4618. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  4619. ErrorRange = AtomicInnerBinOp->getSourceRange();
  4620. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  4621. NoteRange = SourceRange(NoteLoc, NoteLoc);
  4622. ErrorFound = NotABinaryOperator;
  4623. }
  4624. } else {
  4625. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  4626. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  4627. ErrorFound = NotABinaryExpression;
  4628. }
  4629. } else {
  4630. ErrorLoc = AtomicBinOp->getExprLoc();
  4631. ErrorRange = AtomicBinOp->getSourceRange();
  4632. NoteLoc = AtomicBinOp->getOperatorLoc();
  4633. NoteRange = SourceRange(NoteLoc, NoteLoc);
  4634. ErrorFound = NotAnAssignmentOp;
  4635. }
  4636. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  4637. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  4638. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  4639. return true;
  4640. } else if (SemaRef.CurContext->isDependentContext())
  4641. E = X = UpdateExpr = nullptr;
  4642. return ErrorFound != NoError;
  4643. }
  4644. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  4645. unsigned NoteId) {
  4646. ExprAnalysisErrorCode ErrorFound = NoError;
  4647. SourceLocation ErrorLoc, NoteLoc;
  4648. SourceRange ErrorRange, NoteRange;
  4649. // Allowed constructs are:
  4650. // x++;
  4651. // x--;
  4652. // ++x;
  4653. // --x;
  4654. // x binop= expr;
  4655. // x = x binop expr;
  4656. // x = expr binop x;
  4657. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  4658. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  4659. if (AtomicBody->getType()->isScalarType() ||
  4660. AtomicBody->isInstantiationDependent()) {
  4661. if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  4662. AtomicBody->IgnoreParenImpCasts())) {
  4663. // Check for Compound Assignment Operation
  4664. Op = BinaryOperator::getOpForCompoundAssignment(
  4665. AtomicCompAssignOp->getOpcode());
  4666. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  4667. E = AtomicCompAssignOp->getRHS();
  4668. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  4669. IsXLHSInRHSPart = true;
  4670. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  4671. AtomicBody->IgnoreParenImpCasts())) {
  4672. // Check for Binary Operation
  4673. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  4674. return true;
  4675. } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  4676. AtomicBody->IgnoreParenImpCasts())) {
  4677. // Check for Unary Operation
  4678. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  4679. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  4680. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  4681. OpLoc = AtomicUnaryOp->getOperatorLoc();
  4682. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  4683. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  4684. IsXLHSInRHSPart = true;
  4685. } else {
  4686. ErrorFound = NotAnUnaryIncDecExpression;
  4687. ErrorLoc = AtomicUnaryOp->getExprLoc();
  4688. ErrorRange = AtomicUnaryOp->getSourceRange();
  4689. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  4690. NoteRange = SourceRange(NoteLoc, NoteLoc);
  4691. }
  4692. } else if (!AtomicBody->isInstantiationDependent()) {
  4693. ErrorFound = NotABinaryOrUnaryExpression;
  4694. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  4695. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  4696. }
  4697. } else {
  4698. ErrorFound = NotAScalarType;
  4699. NoteLoc = ErrorLoc = AtomicBody->getLocStart();
  4700. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4701. }
  4702. } else {
  4703. ErrorFound = NotAnExpression;
  4704. NoteLoc = ErrorLoc = S->getLocStart();
  4705. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4706. }
  4707. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  4708. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  4709. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  4710. return true;
  4711. } else if (SemaRef.CurContext->isDependentContext())
  4712. E = X = UpdateExpr = nullptr;
  4713. if (ErrorFound == NoError && E && X) {
  4714. // Build an update expression of form 'OpaqueValueExpr(x) binop
  4715. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  4716. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  4717. auto *OVEX = new (SemaRef.getASTContext())
  4718. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  4719. auto *OVEExpr = new (SemaRef.getASTContext())
  4720. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  4721. auto Update =
  4722. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  4723. IsXLHSInRHSPart ? OVEExpr : OVEX);
  4724. if (Update.isInvalid())
  4725. return true;
  4726. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  4727. Sema::AA_Casting);
  4728. if (Update.isInvalid())
  4729. return true;
  4730. UpdateExpr = Update.get();
  4731. }
  4732. return ErrorFound != NoError;
  4733. }
  4734. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  4735. Stmt *AStmt,
  4736. SourceLocation StartLoc,
  4737. SourceLocation EndLoc) {
  4738. if (!AStmt)
  4739. return StmtError();
  4740. auto *CS = cast<CapturedStmt>(AStmt);
  4741. // 1.2.2 OpenMP Language Terminology
  4742. // Structured block - An executable statement with a single entry at the
  4743. // top and a single exit at the bottom.
  4744. // The point of exit cannot be a branch out of the structured block.
  4745. // longjmp() and throw() must not violate the entry/exit criteria.
  4746. OpenMPClauseKind AtomicKind = OMPC_unknown;
  4747. SourceLocation AtomicKindLoc;
  4748. for (auto *C : Clauses) {
  4749. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  4750. C->getClauseKind() == OMPC_update ||
  4751. C->getClauseKind() == OMPC_capture) {
  4752. if (AtomicKind != OMPC_unknown) {
  4753. Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
  4754. << SourceRange(C->getLocStart(), C->getLocEnd());
  4755. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  4756. << getOpenMPClauseName(AtomicKind);
  4757. } else {
  4758. AtomicKind = C->getClauseKind();
  4759. AtomicKindLoc = C->getLocStart();
  4760. }
  4761. }
  4762. }
  4763. auto Body = CS->getCapturedStmt();
  4764. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  4765. Body = EWC->getSubExpr();
  4766. Expr *X = nullptr;
  4767. Expr *V = nullptr;
  4768. Expr *E = nullptr;
  4769. Expr *UE = nullptr;
  4770. bool IsXLHSInRHSPart = false;
  4771. bool IsPostfixUpdate = false;
  4772. // OpenMP [2.12.6, atomic Construct]
  4773. // In the next expressions:
  4774. // * x and v (as applicable) are both l-value expressions with scalar type.
  4775. // * During the execution of an atomic region, multiple syntactic
  4776. // occurrences of x must designate the same storage location.
  4777. // * Neither of v and expr (as applicable) may access the storage location
  4778. // designated by x.
  4779. // * Neither of x and expr (as applicable) may access the storage location
  4780. // designated by v.
  4781. // * expr is an expression with scalar type.
  4782. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  4783. // * binop, binop=, ++, and -- are not overloaded operators.
  4784. // * The expression x binop expr must be numerically equivalent to x binop
  4785. // (expr). This requirement is satisfied if the operators in expr have
  4786. // precedence greater than binop, or by using parentheses around expr or
  4787. // subexpressions of expr.
  4788. // * The expression expr binop x must be numerically equivalent to (expr)
  4789. // binop x. This requirement is satisfied if the operators in expr have
  4790. // precedence equal to or greater than binop, or by using parentheses around
  4791. // expr or subexpressions of expr.
  4792. // * For forms that allow multiple occurrences of x, the number of times
  4793. // that x is evaluated is unspecified.
  4794. if (AtomicKind == OMPC_read) {
  4795. enum {
  4796. NotAnExpression,
  4797. NotAnAssignmentOp,
  4798. NotAScalarType,
  4799. NotAnLValue,
  4800. NoError
  4801. } ErrorFound = NoError;
  4802. SourceLocation ErrorLoc, NoteLoc;
  4803. SourceRange ErrorRange, NoteRange;
  4804. // If clause is read:
  4805. // v = x;
  4806. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  4807. auto *AtomicBinOp =
  4808. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  4809. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  4810. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  4811. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  4812. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  4813. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  4814. if (!X->isLValue() || !V->isLValue()) {
  4815. auto NotLValueExpr = X->isLValue() ? V : X;
  4816. ErrorFound = NotAnLValue;
  4817. ErrorLoc = AtomicBinOp->getExprLoc();
  4818. ErrorRange = AtomicBinOp->getSourceRange();
  4819. NoteLoc = NotLValueExpr->getExprLoc();
  4820. NoteRange = NotLValueExpr->getSourceRange();
  4821. }
  4822. } else if (!X->isInstantiationDependent() ||
  4823. !V->isInstantiationDependent()) {
  4824. auto NotScalarExpr =
  4825. (X->isInstantiationDependent() || X->getType()->isScalarType())
  4826. ? V
  4827. : X;
  4828. ErrorFound = NotAScalarType;
  4829. ErrorLoc = AtomicBinOp->getExprLoc();
  4830. ErrorRange = AtomicBinOp->getSourceRange();
  4831. NoteLoc = NotScalarExpr->getExprLoc();
  4832. NoteRange = NotScalarExpr->getSourceRange();
  4833. }
  4834. } else if (!AtomicBody->isInstantiationDependent()) {
  4835. ErrorFound = NotAnAssignmentOp;
  4836. ErrorLoc = AtomicBody->getExprLoc();
  4837. ErrorRange = AtomicBody->getSourceRange();
  4838. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  4839. : AtomicBody->getExprLoc();
  4840. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  4841. : AtomicBody->getSourceRange();
  4842. }
  4843. } else {
  4844. ErrorFound = NotAnExpression;
  4845. NoteLoc = ErrorLoc = Body->getLocStart();
  4846. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4847. }
  4848. if (ErrorFound != NoError) {
  4849. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  4850. << ErrorRange;
  4851. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  4852. << NoteRange;
  4853. return StmtError();
  4854. } else if (CurContext->isDependentContext())
  4855. V = X = nullptr;
  4856. } else if (AtomicKind == OMPC_write) {
  4857. enum {
  4858. NotAnExpression,
  4859. NotAnAssignmentOp,
  4860. NotAScalarType,
  4861. NotAnLValue,
  4862. NoError
  4863. } ErrorFound = NoError;
  4864. SourceLocation ErrorLoc, NoteLoc;
  4865. SourceRange ErrorRange, NoteRange;
  4866. // If clause is write:
  4867. // x = expr;
  4868. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  4869. auto *AtomicBinOp =
  4870. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  4871. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  4872. X = AtomicBinOp->getLHS();
  4873. E = AtomicBinOp->getRHS();
  4874. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  4875. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  4876. if (!X->isLValue()) {
  4877. ErrorFound = NotAnLValue;
  4878. ErrorLoc = AtomicBinOp->getExprLoc();
  4879. ErrorRange = AtomicBinOp->getSourceRange();
  4880. NoteLoc = X->getExprLoc();
  4881. NoteRange = X->getSourceRange();
  4882. }
  4883. } else if (!X->isInstantiationDependent() ||
  4884. !E->isInstantiationDependent()) {
  4885. auto NotScalarExpr =
  4886. (X->isInstantiationDependent() || X->getType()->isScalarType())
  4887. ? E
  4888. : X;
  4889. ErrorFound = NotAScalarType;
  4890. ErrorLoc = AtomicBinOp->getExprLoc();
  4891. ErrorRange = AtomicBinOp->getSourceRange();
  4892. NoteLoc = NotScalarExpr->getExprLoc();
  4893. NoteRange = NotScalarExpr->getSourceRange();
  4894. }
  4895. } else if (!AtomicBody->isInstantiationDependent()) {
  4896. ErrorFound = NotAnAssignmentOp;
  4897. ErrorLoc = AtomicBody->getExprLoc();
  4898. ErrorRange = AtomicBody->getSourceRange();
  4899. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  4900. : AtomicBody->getExprLoc();
  4901. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  4902. : AtomicBody->getSourceRange();
  4903. }
  4904. } else {
  4905. ErrorFound = NotAnExpression;
  4906. NoteLoc = ErrorLoc = Body->getLocStart();
  4907. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4908. }
  4909. if (ErrorFound != NoError) {
  4910. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  4911. << ErrorRange;
  4912. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  4913. << NoteRange;
  4914. return StmtError();
  4915. } else if (CurContext->isDependentContext())
  4916. E = X = nullptr;
  4917. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  4918. // If clause is update:
  4919. // x++;
  4920. // x--;
  4921. // ++x;
  4922. // --x;
  4923. // x binop= expr;
  4924. // x = x binop expr;
  4925. // x = expr binop x;
  4926. OpenMPAtomicUpdateChecker Checker(*this);
  4927. if (Checker.checkStatement(
  4928. Body, (AtomicKind == OMPC_update)
  4929. ? diag::err_omp_atomic_update_not_expression_statement
  4930. : diag::err_omp_atomic_not_expression_statement,
  4931. diag::note_omp_atomic_update))
  4932. return StmtError();
  4933. if (!CurContext->isDependentContext()) {
  4934. E = Checker.getExpr();
  4935. X = Checker.getX();
  4936. UE = Checker.getUpdateExpr();
  4937. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  4938. }
  4939. } else if (AtomicKind == OMPC_capture) {
  4940. enum {
  4941. NotAnAssignmentOp,
  4942. NotACompoundStatement,
  4943. NotTwoSubstatements,
  4944. NotASpecificExpression,
  4945. NoError
  4946. } ErrorFound = NoError;
  4947. SourceLocation ErrorLoc, NoteLoc;
  4948. SourceRange ErrorRange, NoteRange;
  4949. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  4950. // If clause is a capture:
  4951. // v = x++;
  4952. // v = x--;
  4953. // v = ++x;
  4954. // v = --x;
  4955. // v = x binop= expr;
  4956. // v = x = x binop expr;
  4957. // v = x = expr binop x;
  4958. auto *AtomicBinOp =
  4959. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  4960. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  4961. V = AtomicBinOp->getLHS();
  4962. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  4963. OpenMPAtomicUpdateChecker Checker(*this);
  4964. if (Checker.checkStatement(
  4965. Body, diag::err_omp_atomic_capture_not_expression_statement,
  4966. diag::note_omp_atomic_update))
  4967. return StmtError();
  4968. E = Checker.getExpr();
  4969. X = Checker.getX();
  4970. UE = Checker.getUpdateExpr();
  4971. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  4972. IsPostfixUpdate = Checker.isPostfixUpdate();
  4973. } else if (!AtomicBody->isInstantiationDependent()) {
  4974. ErrorLoc = AtomicBody->getExprLoc();
  4975. ErrorRange = AtomicBody->getSourceRange();
  4976. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  4977. : AtomicBody->getExprLoc();
  4978. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  4979. : AtomicBody->getSourceRange();
  4980. ErrorFound = NotAnAssignmentOp;
  4981. }
  4982. if (ErrorFound != NoError) {
  4983. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  4984. << ErrorRange;
  4985. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  4986. return StmtError();
  4987. } else if (CurContext->isDependentContext()) {
  4988. UE = V = E = X = nullptr;
  4989. }
  4990. } else {
  4991. // If clause is a capture:
  4992. // { v = x; x = expr; }
  4993. // { v = x; x++; }
  4994. // { v = x; x--; }
  4995. // { v = x; ++x; }
  4996. // { v = x; --x; }
  4997. // { v = x; x binop= expr; }
  4998. // { v = x; x = x binop expr; }
  4999. // { v = x; x = expr binop x; }
  5000. // { x++; v = x; }
  5001. // { x--; v = x; }
  5002. // { ++x; v = x; }
  5003. // { --x; v = x; }
  5004. // { x binop= expr; v = x; }
  5005. // { x = x binop expr; v = x; }
  5006. // { x = expr binop x; v = x; }
  5007. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  5008. // Check that this is { expr1; expr2; }
  5009. if (CS->size() == 2) {
  5010. auto *First = CS->body_front();
  5011. auto *Second = CS->body_back();
  5012. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  5013. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  5014. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  5015. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  5016. // Need to find what subexpression is 'v' and what is 'x'.
  5017. OpenMPAtomicUpdateChecker Checker(*this);
  5018. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  5019. BinaryOperator *BinOp = nullptr;
  5020. if (IsUpdateExprFound) {
  5021. BinOp = dyn_cast<BinaryOperator>(First);
  5022. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5023. }
  5024. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  5025. // { v = x; x++; }
  5026. // { v = x; x--; }
  5027. // { v = x; ++x; }
  5028. // { v = x; --x; }
  5029. // { v = x; x binop= expr; }
  5030. // { v = x; x = x binop expr; }
  5031. // { v = x; x = expr binop x; }
  5032. // Check that the first expression has form v = x.
  5033. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5034. llvm::FoldingSetNodeID XId, PossibleXId;
  5035. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5036. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5037. IsUpdateExprFound = XId == PossibleXId;
  5038. if (IsUpdateExprFound) {
  5039. V = BinOp->getLHS();
  5040. X = Checker.getX();
  5041. E = Checker.getExpr();
  5042. UE = Checker.getUpdateExpr();
  5043. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5044. IsPostfixUpdate = true;
  5045. }
  5046. }
  5047. if (!IsUpdateExprFound) {
  5048. IsUpdateExprFound = !Checker.checkStatement(First);
  5049. BinOp = nullptr;
  5050. if (IsUpdateExprFound) {
  5051. BinOp = dyn_cast<BinaryOperator>(Second);
  5052. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5053. }
  5054. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  5055. // { x++; v = x; }
  5056. // { x--; v = x; }
  5057. // { ++x; v = x; }
  5058. // { --x; v = x; }
  5059. // { x binop= expr; v = x; }
  5060. // { x = x binop expr; v = x; }
  5061. // { x = expr binop x; v = x; }
  5062. // Check that the second expression has form v = x.
  5063. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5064. llvm::FoldingSetNodeID XId, PossibleXId;
  5065. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5066. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5067. IsUpdateExprFound = XId == PossibleXId;
  5068. if (IsUpdateExprFound) {
  5069. V = BinOp->getLHS();
  5070. X = Checker.getX();
  5071. E = Checker.getExpr();
  5072. UE = Checker.getUpdateExpr();
  5073. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5074. IsPostfixUpdate = false;
  5075. }
  5076. }
  5077. }
  5078. if (!IsUpdateExprFound) {
  5079. // { v = x; x = expr; }
  5080. auto *FirstExpr = dyn_cast<Expr>(First);
  5081. auto *SecondExpr = dyn_cast<Expr>(Second);
  5082. if (!FirstExpr || !SecondExpr ||
  5083. !(FirstExpr->isInstantiationDependent() ||
  5084. SecondExpr->isInstantiationDependent())) {
  5085. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  5086. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  5087. ErrorFound = NotAnAssignmentOp;
  5088. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  5089. : First->getLocStart();
  5090. NoteRange = ErrorRange = FirstBinOp
  5091. ? FirstBinOp->getSourceRange()
  5092. : SourceRange(ErrorLoc, ErrorLoc);
  5093. } else {
  5094. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  5095. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  5096. ErrorFound = NotAnAssignmentOp;
  5097. NoteLoc = ErrorLoc = SecondBinOp
  5098. ? SecondBinOp->getOperatorLoc()
  5099. : Second->getLocStart();
  5100. NoteRange = ErrorRange =
  5101. SecondBinOp ? SecondBinOp->getSourceRange()
  5102. : SourceRange(ErrorLoc, ErrorLoc);
  5103. } else {
  5104. auto *PossibleXRHSInFirst =
  5105. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  5106. auto *PossibleXLHSInSecond =
  5107. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  5108. llvm::FoldingSetNodeID X1Id, X2Id;
  5109. PossibleXRHSInFirst->Profile(X1Id, Context,
  5110. /*Canonical=*/true);
  5111. PossibleXLHSInSecond->Profile(X2Id, Context,
  5112. /*Canonical=*/true);
  5113. IsUpdateExprFound = X1Id == X2Id;
  5114. if (IsUpdateExprFound) {
  5115. V = FirstBinOp->getLHS();
  5116. X = SecondBinOp->getLHS();
  5117. E = SecondBinOp->getRHS();
  5118. UE = nullptr;
  5119. IsXLHSInRHSPart = false;
  5120. IsPostfixUpdate = true;
  5121. } else {
  5122. ErrorFound = NotASpecificExpression;
  5123. ErrorLoc = FirstBinOp->getExprLoc();
  5124. ErrorRange = FirstBinOp->getSourceRange();
  5125. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  5126. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  5127. }
  5128. }
  5129. }
  5130. }
  5131. }
  5132. } else {
  5133. NoteLoc = ErrorLoc = Body->getLocStart();
  5134. NoteRange = ErrorRange =
  5135. SourceRange(Body->getLocStart(), Body->getLocStart());
  5136. ErrorFound = NotTwoSubstatements;
  5137. }
  5138. } else {
  5139. NoteLoc = ErrorLoc = Body->getLocStart();
  5140. NoteRange = ErrorRange =
  5141. SourceRange(Body->getLocStart(), Body->getLocStart());
  5142. ErrorFound = NotACompoundStatement;
  5143. }
  5144. if (ErrorFound != NoError) {
  5145. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  5146. << ErrorRange;
  5147. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5148. return StmtError();
  5149. } else if (CurContext->isDependentContext()) {
  5150. UE = V = E = X = nullptr;
  5151. }
  5152. }
  5153. }
  5154. getCurFunction()->setHasBranchProtectedScope();
  5155. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5156. X, V, E, UE, IsXLHSInRHSPart,
  5157. IsPostfixUpdate);
  5158. }
  5159. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  5160. Stmt *AStmt,
  5161. SourceLocation StartLoc,
  5162. SourceLocation EndLoc) {
  5163. if (!AStmt)
  5164. return StmtError();
  5165. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5166. // 1.2.2 OpenMP Language Terminology
  5167. // Structured block - An executable statement with a single entry at the
  5168. // top and a single exit at the bottom.
  5169. // The point of exit cannot be a branch out of the structured block.
  5170. // longjmp() and throw() must not violate the entry/exit criteria.
  5171. CS->getCapturedDecl()->setNothrow();
  5172. // OpenMP [2.16, Nesting of Regions]
  5173. // If specified, a teams construct must be contained within a target
  5174. // construct. That target construct must contain no statements or directives
  5175. // outside of the teams construct.
  5176. if (DSAStack->hasInnerTeamsRegion()) {
  5177. auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
  5178. bool OMPTeamsFound = true;
  5179. if (auto *CS = dyn_cast<CompoundStmt>(S)) {
  5180. auto I = CS->body_begin();
  5181. while (I != CS->body_end()) {
  5182. auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  5183. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  5184. OMPTeamsFound = false;
  5185. break;
  5186. }
  5187. ++I;
  5188. }
  5189. assert(I != CS->body_end() && "Not found statement");
  5190. S = *I;
  5191. } else {
  5192. auto *OED = dyn_cast<OMPExecutableDirective>(S);
  5193. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  5194. }
  5195. if (!OMPTeamsFound) {
  5196. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  5197. Diag(DSAStack->getInnerTeamsRegionLoc(),
  5198. diag::note_omp_nested_teams_construct_here);
  5199. Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
  5200. << isa<OMPExecutableDirective>(S);
  5201. return StmtError();
  5202. }
  5203. }
  5204. getCurFunction()->setHasBranchProtectedScope();
  5205. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5206. }
  5207. StmtResult
  5208. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  5209. Stmt *AStmt, SourceLocation StartLoc,
  5210. SourceLocation EndLoc) {
  5211. if (!AStmt)
  5212. return StmtError();
  5213. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5214. // 1.2.2 OpenMP Language Terminology
  5215. // Structured block - An executable statement with a single entry at the
  5216. // top and a single exit at the bottom.
  5217. // The point of exit cannot be a branch out of the structured block.
  5218. // longjmp() and throw() must not violate the entry/exit criteria.
  5219. CS->getCapturedDecl()->setNothrow();
  5220. getCurFunction()->setHasBranchProtectedScope();
  5221. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5222. AStmt);
  5223. }
  5224. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  5225. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5226. SourceLocation EndLoc,
  5227. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5228. if (!AStmt)
  5229. return StmtError();
  5230. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5231. // 1.2.2 OpenMP Language Terminology
  5232. // Structured block - An executable statement with a single entry at the
  5233. // top and a single exit at the bottom.
  5234. // The point of exit cannot be a branch out of the structured block.
  5235. // longjmp() and throw() must not violate the entry/exit criteria.
  5236. CS->getCapturedDecl()->setNothrow();
  5237. OMPLoopDirective::HelperExprs B;
  5238. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5239. // define the nested loops number.
  5240. unsigned NestedLoopCount =
  5241. CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  5242. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5243. VarsWithImplicitDSA, B);
  5244. if (NestedLoopCount == 0)
  5245. return StmtError();
  5246. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5247. "omp target parallel for loop exprs were not built");
  5248. if (!CurContext->isDependentContext()) {
  5249. // Finalize the clauses that need pre-built expressions for CodeGen.
  5250. for (auto C : Clauses) {
  5251. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5252. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5253. B.NumIterations, *this, CurScope,
  5254. DSAStack))
  5255. return StmtError();
  5256. }
  5257. }
  5258. getCurFunction()->setHasBranchProtectedScope();
  5259. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  5260. NestedLoopCount, Clauses, AStmt,
  5261. B, DSAStack->isCancelRegion());
  5262. }
  5263. /// \brief Check for existence of a map clause in the list of clauses.
  5264. static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
  5265. for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
  5266. I != E; ++I) {
  5267. if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
  5268. return true;
  5269. }
  5270. }
  5271. return false;
  5272. }
  5273. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  5274. Stmt *AStmt,
  5275. SourceLocation StartLoc,
  5276. SourceLocation EndLoc) {
  5277. if (!AStmt)
  5278. return StmtError();
  5279. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5280. // OpenMP [2.10.1, Restrictions, p. 97]
  5281. // At least one map clause must appear on the directive.
  5282. if (!HasMapClause(Clauses)) {
  5283. Diag(StartLoc, diag::err_omp_no_map_for_directive)
  5284. << getOpenMPDirectiveName(OMPD_target_data);
  5285. return StmtError();
  5286. }
  5287. getCurFunction()->setHasBranchProtectedScope();
  5288. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5289. AStmt);
  5290. }
  5291. StmtResult
  5292. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  5293. SourceLocation StartLoc,
  5294. SourceLocation EndLoc) {
  5295. // OpenMP [2.10.2, Restrictions, p. 99]
  5296. // At least one map clause must appear on the directive.
  5297. if (!HasMapClause(Clauses)) {
  5298. Diag(StartLoc, diag::err_omp_no_map_for_directive)
  5299. << getOpenMPDirectiveName(OMPD_target_enter_data);
  5300. return StmtError();
  5301. }
  5302. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
  5303. Clauses);
  5304. }
  5305. StmtResult
  5306. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  5307. SourceLocation StartLoc,
  5308. SourceLocation EndLoc) {
  5309. // OpenMP [2.10.3, Restrictions, p. 102]
  5310. // At least one map clause must appear on the directive.
  5311. if (!HasMapClause(Clauses)) {
  5312. Diag(StartLoc, diag::err_omp_no_map_for_directive)
  5313. << getOpenMPDirectiveName(OMPD_target_exit_data);
  5314. return StmtError();
  5315. }
  5316. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5317. }
  5318. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  5319. SourceLocation StartLoc,
  5320. SourceLocation EndLoc) {
  5321. bool seenMotionClause = false;
  5322. for (auto *C : Clauses) {
  5323. if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
  5324. seenMotionClause = true;
  5325. }
  5326. if (!seenMotionClause) {
  5327. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  5328. return StmtError();
  5329. }
  5330. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5331. }
  5332. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  5333. Stmt *AStmt, SourceLocation StartLoc,
  5334. SourceLocation EndLoc) {
  5335. if (!AStmt)
  5336. return StmtError();
  5337. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5338. // 1.2.2 OpenMP Language Terminology
  5339. // Structured block - An executable statement with a single entry at the
  5340. // top and a single exit at the bottom.
  5341. // The point of exit cannot be a branch out of the structured block.
  5342. // longjmp() and throw() must not violate the entry/exit criteria.
  5343. CS->getCapturedDecl()->setNothrow();
  5344. getCurFunction()->setHasBranchProtectedScope();
  5345. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5346. }
  5347. StmtResult
  5348. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  5349. SourceLocation EndLoc,
  5350. OpenMPDirectiveKind CancelRegion) {
  5351. if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
  5352. CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
  5353. Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  5354. << getOpenMPDirectiveName(CancelRegion);
  5355. return StmtError();
  5356. }
  5357. if (DSAStack->isParentNowaitRegion()) {
  5358. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  5359. return StmtError();
  5360. }
  5361. if (DSAStack->isParentOrderedRegion()) {
  5362. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  5363. return StmtError();
  5364. }
  5365. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  5366. CancelRegion);
  5367. }
  5368. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  5369. SourceLocation StartLoc,
  5370. SourceLocation EndLoc,
  5371. OpenMPDirectiveKind CancelRegion) {
  5372. if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
  5373. CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
  5374. Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  5375. << getOpenMPDirectiveName(CancelRegion);
  5376. return StmtError();
  5377. }
  5378. if (DSAStack->isParentNowaitRegion()) {
  5379. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  5380. return StmtError();
  5381. }
  5382. if (DSAStack->isParentOrderedRegion()) {
  5383. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  5384. return StmtError();
  5385. }
  5386. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  5387. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5388. CancelRegion);
  5389. }
  5390. static bool checkGrainsizeNumTasksClauses(Sema &S,
  5391. ArrayRef<OMPClause *> Clauses) {
  5392. OMPClause *PrevClause = nullptr;
  5393. bool ErrorFound = false;
  5394. for (auto *C : Clauses) {
  5395. if (C->getClauseKind() == OMPC_grainsize ||
  5396. C->getClauseKind() == OMPC_num_tasks) {
  5397. if (!PrevClause)
  5398. PrevClause = C;
  5399. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  5400. S.Diag(C->getLocStart(),
  5401. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  5402. << getOpenMPClauseName(C->getClauseKind())
  5403. << getOpenMPClauseName(PrevClause->getClauseKind());
  5404. S.Diag(PrevClause->getLocStart(),
  5405. diag::note_omp_previous_grainsize_num_tasks)
  5406. << getOpenMPClauseName(PrevClause->getClauseKind());
  5407. ErrorFound = true;
  5408. }
  5409. }
  5410. }
  5411. return ErrorFound;
  5412. }
  5413. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  5414. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5415. SourceLocation EndLoc,
  5416. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5417. if (!AStmt)
  5418. return StmtError();
  5419. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5420. OMPLoopDirective::HelperExprs B;
  5421. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5422. // define the nested loops number.
  5423. unsigned NestedLoopCount =
  5424. CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  5425. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  5426. VarsWithImplicitDSA, B);
  5427. if (NestedLoopCount == 0)
  5428. return StmtError();
  5429. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5430. "omp for loop exprs were not built");
  5431. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  5432. // The grainsize clause and num_tasks clause are mutually exclusive and may
  5433. // not appear on the same taskloop directive.
  5434. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  5435. return StmtError();
  5436. getCurFunction()->setHasBranchProtectedScope();
  5437. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  5438. NestedLoopCount, Clauses, AStmt, B);
  5439. }
  5440. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  5441. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5442. SourceLocation EndLoc,
  5443. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5444. if (!AStmt)
  5445. return StmtError();
  5446. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5447. OMPLoopDirective::HelperExprs B;
  5448. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5449. // define the nested loops number.
  5450. unsigned NestedLoopCount =
  5451. CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  5452. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  5453. VarsWithImplicitDSA, B);
  5454. if (NestedLoopCount == 0)
  5455. return StmtError();
  5456. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5457. "omp for loop exprs were not built");
  5458. if (!CurContext->isDependentContext()) {
  5459. // Finalize the clauses that need pre-built expressions for CodeGen.
  5460. for (auto C : Clauses) {
  5461. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5462. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5463. B.NumIterations, *this, CurScope,
  5464. DSAStack))
  5465. return StmtError();
  5466. }
  5467. }
  5468. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  5469. // The grainsize clause and num_tasks clause are mutually exclusive and may
  5470. // not appear on the same taskloop directive.
  5471. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  5472. return StmtError();
  5473. getCurFunction()->setHasBranchProtectedScope();
  5474. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  5475. NestedLoopCount, Clauses, AStmt, B);
  5476. }
  5477. StmtResult Sema::ActOnOpenMPDistributeDirective(
  5478. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5479. SourceLocation EndLoc,
  5480. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5481. if (!AStmt)
  5482. return StmtError();
  5483. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5484. OMPLoopDirective::HelperExprs B;
  5485. // In presence of clause 'collapse' with number of loops, it will
  5486. // define the nested loops number.
  5487. unsigned NestedLoopCount =
  5488. CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  5489. nullptr /*ordered not a clause on distribute*/, AStmt,
  5490. *this, *DSAStack, VarsWithImplicitDSA, B);
  5491. if (NestedLoopCount == 0)
  5492. return StmtError();
  5493. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5494. "omp for loop exprs were not built");
  5495. getCurFunction()->setHasBranchProtectedScope();
  5496. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  5497. NestedLoopCount, Clauses, AStmt, B);
  5498. }
  5499. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  5500. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5501. SourceLocation EndLoc,
  5502. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5503. if (!AStmt)
  5504. return StmtError();
  5505. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5506. // 1.2.2 OpenMP Language Terminology
  5507. // Structured block - An executable statement with a single entry at the
  5508. // top and a single exit at the bottom.
  5509. // The point of exit cannot be a branch out of the structured block.
  5510. // longjmp() and throw() must not violate the entry/exit criteria.
  5511. CS->getCapturedDecl()->setNothrow();
  5512. OMPLoopDirective::HelperExprs B;
  5513. // In presence of clause 'collapse' with number of loops, it will
  5514. // define the nested loops number.
  5515. unsigned NestedLoopCount = CheckOpenMPLoop(
  5516. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  5517. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  5518. VarsWithImplicitDSA, B);
  5519. if (NestedLoopCount == 0)
  5520. return StmtError();
  5521. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5522. "omp for loop exprs were not built");
  5523. getCurFunction()->setHasBranchProtectedScope();
  5524. return OMPDistributeParallelForDirective::Create(
  5525. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5526. }
  5527. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  5528. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5529. SourceLocation EndLoc,
  5530. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5531. if (!AStmt)
  5532. return StmtError();
  5533. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5534. // 1.2.2 OpenMP Language Terminology
  5535. // Structured block - An executable statement with a single entry at the
  5536. // top and a single exit at the bottom.
  5537. // The point of exit cannot be a branch out of the structured block.
  5538. // longjmp() and throw() must not violate the entry/exit criteria.
  5539. CS->getCapturedDecl()->setNothrow();
  5540. OMPLoopDirective::HelperExprs B;
  5541. // In presence of clause 'collapse' with number of loops, it will
  5542. // define the nested loops number.
  5543. unsigned NestedLoopCount = CheckOpenMPLoop(
  5544. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5545. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  5546. VarsWithImplicitDSA, B);
  5547. if (NestedLoopCount == 0)
  5548. return StmtError();
  5549. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5550. "omp for loop exprs were not built");
  5551. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5552. return StmtError();
  5553. getCurFunction()->setHasBranchProtectedScope();
  5554. return OMPDistributeParallelForSimdDirective::Create(
  5555. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5556. }
  5557. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  5558. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5559. SourceLocation EndLoc,
  5560. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5561. if (!AStmt)
  5562. return StmtError();
  5563. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5564. // 1.2.2 OpenMP Language Terminology
  5565. // Structured block - An executable statement with a single entry at the
  5566. // top and a single exit at the bottom.
  5567. // The point of exit cannot be a branch out of the structured block.
  5568. // longjmp() and throw() must not violate the entry/exit criteria.
  5569. CS->getCapturedDecl()->setNothrow();
  5570. OMPLoopDirective::HelperExprs B;
  5571. // In presence of clause 'collapse' with number of loops, it will
  5572. // define the nested loops number.
  5573. unsigned NestedLoopCount =
  5574. CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  5575. nullptr /*ordered not a clause on distribute*/, AStmt,
  5576. *this, *DSAStack, VarsWithImplicitDSA, B);
  5577. if (NestedLoopCount == 0)
  5578. return StmtError();
  5579. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5580. "omp for loop exprs were not built");
  5581. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5582. return StmtError();
  5583. getCurFunction()->setHasBranchProtectedScope();
  5584. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  5585. NestedLoopCount, Clauses, AStmt, B);
  5586. }
  5587. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  5588. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5589. SourceLocation EndLoc,
  5590. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5591. if (!AStmt)
  5592. return StmtError();
  5593. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5594. // 1.2.2 OpenMP Language Terminology
  5595. // Structured block - An executable statement with a single entry at the
  5596. // top and a single exit at the bottom.
  5597. // The point of exit cannot be a branch out of the structured block.
  5598. // longjmp() and throw() must not violate the entry/exit criteria.
  5599. CS->getCapturedDecl()->setNothrow();
  5600. OMPLoopDirective::HelperExprs B;
  5601. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5602. // define the nested loops number.
  5603. unsigned NestedLoopCount = CheckOpenMPLoop(
  5604. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5605. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5606. VarsWithImplicitDSA, B);
  5607. if (NestedLoopCount == 0)
  5608. return StmtError();
  5609. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5610. "omp target parallel for simd loop exprs were not built");
  5611. if (!CurContext->isDependentContext()) {
  5612. // Finalize the clauses that need pre-built expressions for CodeGen.
  5613. for (auto C : Clauses) {
  5614. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5615. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5616. B.NumIterations, *this, CurScope,
  5617. DSAStack))
  5618. return StmtError();
  5619. }
  5620. }
  5621. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5622. return StmtError();
  5623. getCurFunction()->setHasBranchProtectedScope();
  5624. return OMPTargetParallelForSimdDirective::Create(
  5625. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5626. }
  5627. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  5628. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5629. SourceLocation EndLoc,
  5630. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5631. if (!AStmt)
  5632. return StmtError();
  5633. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5634. // 1.2.2 OpenMP Language Terminology
  5635. // Structured block - An executable statement with a single entry at the
  5636. // top and a single exit at the bottom.
  5637. // The point of exit cannot be a branch out of the structured block.
  5638. // longjmp() and throw() must not violate the entry/exit criteria.
  5639. CS->getCapturedDecl()->setNothrow();
  5640. OMPLoopDirective::HelperExprs B;
  5641. // In presence of clause 'collapse' with number of loops, it will define the
  5642. // nested loops number.
  5643. unsigned NestedLoopCount =
  5644. CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  5645. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5646. VarsWithImplicitDSA, B);
  5647. if (NestedLoopCount == 0)
  5648. return StmtError();
  5649. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5650. "omp target simd loop exprs were not built");
  5651. if (!CurContext->isDependentContext()) {
  5652. // Finalize the clauses that need pre-built expressions for CodeGen.
  5653. for (auto C : Clauses) {
  5654. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5655. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5656. B.NumIterations, *this, CurScope,
  5657. DSAStack))
  5658. return StmtError();
  5659. }
  5660. }
  5661. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5662. return StmtError();
  5663. getCurFunction()->setHasBranchProtectedScope();
  5664. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  5665. NestedLoopCount, Clauses, AStmt, B);
  5666. }
  5667. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  5668. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5669. SourceLocation EndLoc,
  5670. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5671. if (!AStmt)
  5672. return StmtError();
  5673. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5674. // 1.2.2 OpenMP Language Terminology
  5675. // Structured block - An executable statement with a single entry at the
  5676. // top and a single exit at the bottom.
  5677. // The point of exit cannot be a branch out of the structured block.
  5678. // longjmp() and throw() must not violate the entry/exit criteria.
  5679. CS->getCapturedDecl()->setNothrow();
  5680. OMPLoopDirective::HelperExprs B;
  5681. // In presence of clause 'collapse' with number of loops, it will
  5682. // define the nested loops number.
  5683. unsigned NestedLoopCount =
  5684. CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  5685. nullptr /*ordered not a clause on distribute*/, AStmt,
  5686. *this, *DSAStack, VarsWithImplicitDSA, B);
  5687. if (NestedLoopCount == 0)
  5688. return StmtError();
  5689. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5690. "omp teams distribute loop exprs were not built");
  5691. getCurFunction()->setHasBranchProtectedScope();
  5692. return OMPTeamsDistributeDirective::Create(
  5693. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5694. }
  5695. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  5696. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5697. SourceLocation EndLoc,
  5698. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5699. if (!AStmt)
  5700. return StmtError();
  5701. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5702. // 1.2.2 OpenMP Language Terminology
  5703. // Structured block - An executable statement with a single entry at the
  5704. // top and a single exit at the bottom.
  5705. // The point of exit cannot be a branch out of the structured block.
  5706. // longjmp() and throw() must not violate the entry/exit criteria.
  5707. CS->getCapturedDecl()->setNothrow();
  5708. OMPLoopDirective::HelperExprs B;
  5709. // In presence of clause 'collapse' with number of loops, it will
  5710. // define the nested loops number.
  5711. unsigned NestedLoopCount = CheckOpenMPLoop(
  5712. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  5713. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  5714. VarsWithImplicitDSA, B);
  5715. if (NestedLoopCount == 0)
  5716. return StmtError();
  5717. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5718. "omp teams distribute simd loop exprs were not built");
  5719. if (!CurContext->isDependentContext()) {
  5720. // Finalize the clauses that need pre-built expressions for CodeGen.
  5721. for (auto C : Clauses) {
  5722. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5723. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5724. B.NumIterations, *this, CurScope,
  5725. DSAStack))
  5726. return StmtError();
  5727. }
  5728. }
  5729. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5730. return StmtError();
  5731. getCurFunction()->setHasBranchProtectedScope();
  5732. return OMPTeamsDistributeSimdDirective::Create(
  5733. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5734. }
  5735. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  5736. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5737. SourceLocation EndLoc,
  5738. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5739. if (!AStmt)
  5740. return StmtError();
  5741. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5742. // 1.2.2 OpenMP Language Terminology
  5743. // Structured block - An executable statement with a single entry at the
  5744. // top and a single exit at the bottom.
  5745. // The point of exit cannot be a branch out of the structured block.
  5746. // longjmp() and throw() must not violate the entry/exit criteria.
  5747. CS->getCapturedDecl()->setNothrow();
  5748. OMPLoopDirective::HelperExprs B;
  5749. // In presence of clause 'collapse' with number of loops, it will
  5750. // define the nested loops number.
  5751. auto NestedLoopCount = CheckOpenMPLoop(
  5752. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5753. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  5754. VarsWithImplicitDSA, B);
  5755. if (NestedLoopCount == 0)
  5756. return StmtError();
  5757. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5758. "omp for loop exprs were not built");
  5759. if (!CurContext->isDependentContext()) {
  5760. // Finalize the clauses that need pre-built expressions for CodeGen.
  5761. for (auto C : Clauses) {
  5762. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5763. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5764. B.NumIterations, *this, CurScope,
  5765. DSAStack))
  5766. return StmtError();
  5767. }
  5768. }
  5769. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5770. return StmtError();
  5771. getCurFunction()->setHasBranchProtectedScope();
  5772. return OMPTeamsDistributeParallelForSimdDirective::Create(
  5773. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5774. }
  5775. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  5776. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5777. SourceLocation EndLoc,
  5778. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5779. if (!AStmt)
  5780. return StmtError();
  5781. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5782. // 1.2.2 OpenMP Language Terminology
  5783. // Structured block - An executable statement with a single entry at the
  5784. // top and a single exit at the bottom.
  5785. // The point of exit cannot be a branch out of the structured block.
  5786. // longjmp() and throw() must not violate the entry/exit criteria.
  5787. CS->getCapturedDecl()->setNothrow();
  5788. OMPLoopDirective::HelperExprs B;
  5789. // In presence of clause 'collapse' with number of loops, it will
  5790. // define the nested loops number.
  5791. unsigned NestedLoopCount = CheckOpenMPLoop(
  5792. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  5793. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  5794. VarsWithImplicitDSA, B);
  5795. if (NestedLoopCount == 0)
  5796. return StmtError();
  5797. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5798. "omp for loop exprs were not built");
  5799. if (!CurContext->isDependentContext()) {
  5800. // Finalize the clauses that need pre-built expressions for CodeGen.
  5801. for (auto C : Clauses) {
  5802. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5803. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5804. B.NumIterations, *this, CurScope,
  5805. DSAStack))
  5806. return StmtError();
  5807. }
  5808. }
  5809. getCurFunction()->setHasBranchProtectedScope();
  5810. return OMPTeamsDistributeParallelForDirective::Create(
  5811. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5812. }
  5813. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  5814. Stmt *AStmt,
  5815. SourceLocation StartLoc,
  5816. SourceLocation EndLoc) {
  5817. if (!AStmt)
  5818. return StmtError();
  5819. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5820. // 1.2.2 OpenMP Language Terminology
  5821. // Structured block - An executable statement with a single entry at the
  5822. // top and a single exit at the bottom.
  5823. // The point of exit cannot be a branch out of the structured block.
  5824. // longjmp() and throw() must not violate the entry/exit criteria.
  5825. CS->getCapturedDecl()->setNothrow();
  5826. getCurFunction()->setHasBranchProtectedScope();
  5827. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5828. AStmt);
  5829. }
  5830. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  5831. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5832. SourceLocation EndLoc,
  5833. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5834. if (!AStmt)
  5835. return StmtError();
  5836. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5837. // 1.2.2 OpenMP Language Terminology
  5838. // Structured block - An executable statement with a single entry at the
  5839. // top and a single exit at the bottom.
  5840. // The point of exit cannot be a branch out of the structured block.
  5841. // longjmp() and throw() must not violate the entry/exit criteria.
  5842. CS->getCapturedDecl()->setNothrow();
  5843. OMPLoopDirective::HelperExprs B;
  5844. // In presence of clause 'collapse' with number of loops, it will
  5845. // define the nested loops number.
  5846. auto NestedLoopCount = CheckOpenMPLoop(
  5847. OMPD_target_teams_distribute,
  5848. getCollapseNumberExpr(Clauses),
  5849. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  5850. VarsWithImplicitDSA, B);
  5851. if (NestedLoopCount == 0)
  5852. return StmtError();
  5853. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5854. "omp target teams distribute loop exprs were not built");
  5855. getCurFunction()->setHasBranchProtectedScope();
  5856. return OMPTargetTeamsDistributeDirective::Create(
  5857. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5858. }
  5859. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  5860. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5861. SourceLocation EndLoc,
  5862. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5863. if (!AStmt)
  5864. return StmtError();
  5865. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5866. // 1.2.2 OpenMP Language Terminology
  5867. // Structured block - An executable statement with a single entry at the
  5868. // top and a single exit at the bottom.
  5869. // The point of exit cannot be a branch out of the structured block.
  5870. // longjmp() and throw() must not violate the entry/exit criteria.
  5871. CS->getCapturedDecl()->setNothrow();
  5872. OMPLoopDirective::HelperExprs B;
  5873. // In presence of clause 'collapse' with number of loops, it will
  5874. // define the nested loops number.
  5875. auto NestedLoopCount = CheckOpenMPLoop(
  5876. OMPD_target_teams_distribute_parallel_for,
  5877. getCollapseNumberExpr(Clauses),
  5878. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  5879. VarsWithImplicitDSA, B);
  5880. if (NestedLoopCount == 0)
  5881. return StmtError();
  5882. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5883. "omp target teams distribute parallel for loop exprs were not built");
  5884. if (!CurContext->isDependentContext()) {
  5885. // Finalize the clauses that need pre-built expressions for CodeGen.
  5886. for (auto C : Clauses) {
  5887. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5888. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5889. B.NumIterations, *this, CurScope,
  5890. DSAStack))
  5891. return StmtError();
  5892. }
  5893. }
  5894. getCurFunction()->setHasBranchProtectedScope();
  5895. return OMPTargetTeamsDistributeParallelForDirective::Create(
  5896. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5897. }
  5898. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  5899. SourceLocation StartLoc,
  5900. SourceLocation LParenLoc,
  5901. SourceLocation EndLoc) {
  5902. OMPClause *Res = nullptr;
  5903. switch (Kind) {
  5904. case OMPC_final:
  5905. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  5906. break;
  5907. case OMPC_num_threads:
  5908. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  5909. break;
  5910. case OMPC_safelen:
  5911. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  5912. break;
  5913. case OMPC_simdlen:
  5914. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  5915. break;
  5916. case OMPC_collapse:
  5917. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  5918. break;
  5919. case OMPC_ordered:
  5920. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  5921. break;
  5922. case OMPC_device:
  5923. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  5924. break;
  5925. case OMPC_num_teams:
  5926. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  5927. break;
  5928. case OMPC_thread_limit:
  5929. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  5930. break;
  5931. case OMPC_priority:
  5932. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  5933. break;
  5934. case OMPC_grainsize:
  5935. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  5936. break;
  5937. case OMPC_num_tasks:
  5938. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  5939. break;
  5940. case OMPC_hint:
  5941. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  5942. break;
  5943. case OMPC_if:
  5944. case OMPC_default:
  5945. case OMPC_proc_bind:
  5946. case OMPC_schedule:
  5947. case OMPC_private:
  5948. case OMPC_firstprivate:
  5949. case OMPC_lastprivate:
  5950. case OMPC_shared:
  5951. case OMPC_reduction:
  5952. case OMPC_linear:
  5953. case OMPC_aligned:
  5954. case OMPC_copyin:
  5955. case OMPC_copyprivate:
  5956. case OMPC_nowait:
  5957. case OMPC_untied:
  5958. case OMPC_mergeable:
  5959. case OMPC_threadprivate:
  5960. case OMPC_flush:
  5961. case OMPC_read:
  5962. case OMPC_write:
  5963. case OMPC_update:
  5964. case OMPC_capture:
  5965. case OMPC_seq_cst:
  5966. case OMPC_depend:
  5967. case OMPC_threads:
  5968. case OMPC_simd:
  5969. case OMPC_map:
  5970. case OMPC_nogroup:
  5971. case OMPC_dist_schedule:
  5972. case OMPC_defaultmap:
  5973. case OMPC_unknown:
  5974. case OMPC_uniform:
  5975. case OMPC_to:
  5976. case OMPC_from:
  5977. case OMPC_use_device_ptr:
  5978. case OMPC_is_device_ptr:
  5979. llvm_unreachable("Clause is not allowed.");
  5980. }
  5981. return Res;
  5982. }
  5983. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  5984. Expr *Condition, SourceLocation StartLoc,
  5985. SourceLocation LParenLoc,
  5986. SourceLocation NameModifierLoc,
  5987. SourceLocation ColonLoc,
  5988. SourceLocation EndLoc) {
  5989. Expr *ValExpr = Condition;
  5990. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  5991. !Condition->isInstantiationDependent() &&
  5992. !Condition->containsUnexpandedParameterPack()) {
  5993. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  5994. if (Val.isInvalid())
  5995. return nullptr;
  5996. ValExpr = MakeFullExpr(Val.get()).get();
  5997. }
  5998. return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
  5999. NameModifierLoc, ColonLoc, EndLoc);
  6000. }
  6001. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  6002. SourceLocation StartLoc,
  6003. SourceLocation LParenLoc,
  6004. SourceLocation EndLoc) {
  6005. Expr *ValExpr = Condition;
  6006. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  6007. !Condition->isInstantiationDependent() &&
  6008. !Condition->containsUnexpandedParameterPack()) {
  6009. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  6010. if (Val.isInvalid())
  6011. return nullptr;
  6012. ValExpr = MakeFullExpr(Val.get()).get();
  6013. }
  6014. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  6015. }
  6016. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  6017. Expr *Op) {
  6018. if (!Op)
  6019. return ExprError();
  6020. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  6021. public:
  6022. IntConvertDiagnoser()
  6023. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  6024. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  6025. QualType T) override {
  6026. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  6027. }
  6028. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  6029. QualType T) override {
  6030. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  6031. }
  6032. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  6033. QualType T,
  6034. QualType ConvTy) override {
  6035. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  6036. }
  6037. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  6038. QualType ConvTy) override {
  6039. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  6040. << ConvTy->isEnumeralType() << ConvTy;
  6041. }
  6042. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  6043. QualType T) override {
  6044. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  6045. }
  6046. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  6047. QualType ConvTy) override {
  6048. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  6049. << ConvTy->isEnumeralType() << ConvTy;
  6050. }
  6051. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  6052. QualType) override {
  6053. llvm_unreachable("conversion functions are permitted");
  6054. }
  6055. } ConvertDiagnoser;
  6056. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  6057. }
  6058. static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  6059. OpenMPClauseKind CKind,
  6060. bool StrictlyPositive) {
  6061. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  6062. !ValExpr->isInstantiationDependent()) {
  6063. SourceLocation Loc = ValExpr->getExprLoc();
  6064. ExprResult Value =
  6065. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  6066. if (Value.isInvalid())
  6067. return false;
  6068. ValExpr = Value.get();
  6069. // The expression must evaluate to a non-negative integer value.
  6070. llvm::APSInt Result;
  6071. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  6072. Result.isSigned() &&
  6073. !((!StrictlyPositive && Result.isNonNegative()) ||
  6074. (StrictlyPositive && Result.isStrictlyPositive()))) {
  6075. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  6076. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  6077. << ValExpr->getSourceRange();
  6078. return false;
  6079. }
  6080. }
  6081. return true;
  6082. }
  6083. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  6084. SourceLocation StartLoc,
  6085. SourceLocation LParenLoc,
  6086. SourceLocation EndLoc) {
  6087. Expr *ValExpr = NumThreads;
  6088. // OpenMP [2.5, Restrictions]
  6089. // The num_threads expression must evaluate to a positive integer value.
  6090. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  6091. /*StrictlyPositive=*/true))
  6092. return nullptr;
  6093. return new (Context)
  6094. OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  6095. }
  6096. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  6097. OpenMPClauseKind CKind,
  6098. bool StrictlyPositive) {
  6099. if (!E)
  6100. return ExprError();
  6101. if (E->isValueDependent() || E->isTypeDependent() ||
  6102. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  6103. return E;
  6104. llvm::APSInt Result;
  6105. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  6106. if (ICE.isInvalid())
  6107. return ExprError();
  6108. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  6109. (!StrictlyPositive && !Result.isNonNegative())) {
  6110. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  6111. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  6112. << E->getSourceRange();
  6113. return ExprError();
  6114. }
  6115. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  6116. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  6117. << E->getSourceRange();
  6118. return ExprError();
  6119. }
  6120. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  6121. DSAStack->setAssociatedLoops(Result.getExtValue());
  6122. else if (CKind == OMPC_ordered)
  6123. DSAStack->setAssociatedLoops(Result.getExtValue());
  6124. return ICE;
  6125. }
  6126. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  6127. SourceLocation LParenLoc,
  6128. SourceLocation EndLoc) {
  6129. // OpenMP [2.8.1, simd construct, Description]
  6130. // The parameter of the safelen clause must be a constant
  6131. // positive integer expression.
  6132. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  6133. if (Safelen.isInvalid())
  6134. return nullptr;
  6135. return new (Context)
  6136. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  6137. }
  6138. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  6139. SourceLocation LParenLoc,
  6140. SourceLocation EndLoc) {
  6141. // OpenMP [2.8.1, simd construct, Description]
  6142. // The parameter of the simdlen clause must be a constant
  6143. // positive integer expression.
  6144. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  6145. if (Simdlen.isInvalid())
  6146. return nullptr;
  6147. return new (Context)
  6148. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  6149. }
  6150. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  6151. SourceLocation StartLoc,
  6152. SourceLocation LParenLoc,
  6153. SourceLocation EndLoc) {
  6154. // OpenMP [2.7.1, loop construct, Description]
  6155. // OpenMP [2.8.1, simd construct, Description]
  6156. // OpenMP [2.9.6, distribute construct, Description]
  6157. // The parameter of the collapse clause must be a constant
  6158. // positive integer expression.
  6159. ExprResult NumForLoopsResult =
  6160. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  6161. if (NumForLoopsResult.isInvalid())
  6162. return nullptr;
  6163. return new (Context)
  6164. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  6165. }
  6166. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  6167. SourceLocation EndLoc,
  6168. SourceLocation LParenLoc,
  6169. Expr *NumForLoops) {
  6170. // OpenMP [2.7.1, loop construct, Description]
  6171. // OpenMP [2.8.1, simd construct, Description]
  6172. // OpenMP [2.9.6, distribute construct, Description]
  6173. // The parameter of the ordered clause must be a constant
  6174. // positive integer expression if any.
  6175. if (NumForLoops && LParenLoc.isValid()) {
  6176. ExprResult NumForLoopsResult =
  6177. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  6178. if (NumForLoopsResult.isInvalid())
  6179. return nullptr;
  6180. NumForLoops = NumForLoopsResult.get();
  6181. } else
  6182. NumForLoops = nullptr;
  6183. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
  6184. return new (Context)
  6185. OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
  6186. }
  6187. OMPClause *Sema::ActOnOpenMPSimpleClause(
  6188. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  6189. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  6190. OMPClause *Res = nullptr;
  6191. switch (Kind) {
  6192. case OMPC_default:
  6193. Res =
  6194. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  6195. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  6196. break;
  6197. case OMPC_proc_bind:
  6198. Res = ActOnOpenMPProcBindClause(
  6199. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  6200. LParenLoc, EndLoc);
  6201. break;
  6202. case OMPC_if:
  6203. case OMPC_final:
  6204. case OMPC_num_threads:
  6205. case OMPC_safelen:
  6206. case OMPC_simdlen:
  6207. case OMPC_collapse:
  6208. case OMPC_schedule:
  6209. case OMPC_private:
  6210. case OMPC_firstprivate:
  6211. case OMPC_lastprivate:
  6212. case OMPC_shared:
  6213. case OMPC_reduction:
  6214. case OMPC_linear:
  6215. case OMPC_aligned:
  6216. case OMPC_copyin:
  6217. case OMPC_copyprivate:
  6218. case OMPC_ordered:
  6219. case OMPC_nowait:
  6220. case OMPC_untied:
  6221. case OMPC_mergeable:
  6222. case OMPC_threadprivate:
  6223. case OMPC_flush:
  6224. case OMPC_read:
  6225. case OMPC_write:
  6226. case OMPC_update:
  6227. case OMPC_capture:
  6228. case OMPC_seq_cst:
  6229. case OMPC_depend:
  6230. case OMPC_device:
  6231. case OMPC_threads:
  6232. case OMPC_simd:
  6233. case OMPC_map:
  6234. case OMPC_num_teams:
  6235. case OMPC_thread_limit:
  6236. case OMPC_priority:
  6237. case OMPC_grainsize:
  6238. case OMPC_nogroup:
  6239. case OMPC_num_tasks:
  6240. case OMPC_hint:
  6241. case OMPC_dist_schedule:
  6242. case OMPC_defaultmap:
  6243. case OMPC_unknown:
  6244. case OMPC_uniform:
  6245. case OMPC_to:
  6246. case OMPC_from:
  6247. case OMPC_use_device_ptr:
  6248. case OMPC_is_device_ptr:
  6249. llvm_unreachable("Clause is not allowed.");
  6250. }
  6251. return Res;
  6252. }
  6253. static std::string
  6254. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  6255. ArrayRef<unsigned> Exclude = llvm::None) {
  6256. std::string Values;
  6257. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  6258. unsigned Skipped = Exclude.size();
  6259. auto S = Exclude.begin(), E = Exclude.end();
  6260. for (unsigned i = First; i < Last; ++i) {
  6261. if (std::find(S, E, i) != E) {
  6262. --Skipped;
  6263. continue;
  6264. }
  6265. Values += "'";
  6266. Values += getOpenMPSimpleClauseTypeName(K, i);
  6267. Values += "'";
  6268. if (i == Bound - Skipped)
  6269. Values += " or ";
  6270. else if (i != Bound + 1 - Skipped)
  6271. Values += ", ";
  6272. }
  6273. return Values;
  6274. }
  6275. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  6276. SourceLocation KindKwLoc,
  6277. SourceLocation StartLoc,
  6278. SourceLocation LParenLoc,
  6279. SourceLocation EndLoc) {
  6280. if (Kind == OMPC_DEFAULT_unknown) {
  6281. static_assert(OMPC_DEFAULT_unknown > 0,
  6282. "OMPC_DEFAULT_unknown not greater than 0");
  6283. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  6284. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  6285. /*Last=*/OMPC_DEFAULT_unknown)
  6286. << getOpenMPClauseName(OMPC_default);
  6287. return nullptr;
  6288. }
  6289. switch (Kind) {
  6290. case OMPC_DEFAULT_none:
  6291. DSAStack->setDefaultDSANone(KindKwLoc);
  6292. break;
  6293. case OMPC_DEFAULT_shared:
  6294. DSAStack->setDefaultDSAShared(KindKwLoc);
  6295. break;
  6296. case OMPC_DEFAULT_unknown:
  6297. llvm_unreachable("Clause kind is not allowed.");
  6298. break;
  6299. }
  6300. return new (Context)
  6301. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  6302. }
  6303. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  6304. SourceLocation KindKwLoc,
  6305. SourceLocation StartLoc,
  6306. SourceLocation LParenLoc,
  6307. SourceLocation EndLoc) {
  6308. if (Kind == OMPC_PROC_BIND_unknown) {
  6309. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  6310. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  6311. /*Last=*/OMPC_PROC_BIND_unknown)
  6312. << getOpenMPClauseName(OMPC_proc_bind);
  6313. return nullptr;
  6314. }
  6315. return new (Context)
  6316. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  6317. }
  6318. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  6319. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  6320. SourceLocation StartLoc, SourceLocation LParenLoc,
  6321. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  6322. SourceLocation EndLoc) {
  6323. OMPClause *Res = nullptr;
  6324. switch (Kind) {
  6325. case OMPC_schedule:
  6326. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  6327. assert(Argument.size() == NumberOfElements &&
  6328. ArgumentLoc.size() == NumberOfElements);
  6329. Res = ActOnOpenMPScheduleClause(
  6330. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  6331. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  6332. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  6333. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  6334. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  6335. break;
  6336. case OMPC_if:
  6337. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  6338. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  6339. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  6340. DelimLoc, EndLoc);
  6341. break;
  6342. case OMPC_dist_schedule:
  6343. Res = ActOnOpenMPDistScheduleClause(
  6344. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  6345. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  6346. break;
  6347. case OMPC_defaultmap:
  6348. enum { Modifier, DefaultmapKind };
  6349. Res = ActOnOpenMPDefaultmapClause(
  6350. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  6351. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  6352. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  6353. EndLoc);
  6354. break;
  6355. case OMPC_final:
  6356. case OMPC_num_threads:
  6357. case OMPC_safelen:
  6358. case OMPC_simdlen:
  6359. case OMPC_collapse:
  6360. case OMPC_default:
  6361. case OMPC_proc_bind:
  6362. case OMPC_private:
  6363. case OMPC_firstprivate:
  6364. case OMPC_lastprivate:
  6365. case OMPC_shared:
  6366. case OMPC_reduction:
  6367. case OMPC_linear:
  6368. case OMPC_aligned:
  6369. case OMPC_copyin:
  6370. case OMPC_copyprivate:
  6371. case OMPC_ordered:
  6372. case OMPC_nowait:
  6373. case OMPC_untied:
  6374. case OMPC_mergeable:
  6375. case OMPC_threadprivate:
  6376. case OMPC_flush:
  6377. case OMPC_read:
  6378. case OMPC_write:
  6379. case OMPC_update:
  6380. case OMPC_capture:
  6381. case OMPC_seq_cst:
  6382. case OMPC_depend:
  6383. case OMPC_device:
  6384. case OMPC_threads:
  6385. case OMPC_simd:
  6386. case OMPC_map:
  6387. case OMPC_num_teams:
  6388. case OMPC_thread_limit:
  6389. case OMPC_priority:
  6390. case OMPC_grainsize:
  6391. case OMPC_nogroup:
  6392. case OMPC_num_tasks:
  6393. case OMPC_hint:
  6394. case OMPC_unknown:
  6395. case OMPC_uniform:
  6396. case OMPC_to:
  6397. case OMPC_from:
  6398. case OMPC_use_device_ptr:
  6399. case OMPC_is_device_ptr:
  6400. llvm_unreachable("Clause is not allowed.");
  6401. }
  6402. return Res;
  6403. }
  6404. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  6405. OpenMPScheduleClauseModifier M2,
  6406. SourceLocation M1Loc, SourceLocation M2Loc) {
  6407. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  6408. SmallVector<unsigned, 2> Excluded;
  6409. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  6410. Excluded.push_back(M2);
  6411. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  6412. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  6413. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  6414. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  6415. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  6416. << getListOfPossibleValues(OMPC_schedule,
  6417. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  6418. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  6419. Excluded)
  6420. << getOpenMPClauseName(OMPC_schedule);
  6421. return true;
  6422. }
  6423. return false;
  6424. }
  6425. OMPClause *Sema::ActOnOpenMPScheduleClause(
  6426. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  6427. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  6428. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  6429. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  6430. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  6431. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  6432. return nullptr;
  6433. // OpenMP, 2.7.1, Loop Construct, Restrictions
  6434. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  6435. // but not both.
  6436. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  6437. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  6438. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  6439. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  6440. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  6441. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  6442. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  6443. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  6444. return nullptr;
  6445. }
  6446. if (Kind == OMPC_SCHEDULE_unknown) {
  6447. std::string Values;
  6448. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  6449. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  6450. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  6451. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  6452. Exclude);
  6453. } else {
  6454. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  6455. /*Last=*/OMPC_SCHEDULE_unknown);
  6456. }
  6457. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  6458. << Values << getOpenMPClauseName(OMPC_schedule);
  6459. return nullptr;
  6460. }
  6461. // OpenMP, 2.7.1, Loop Construct, Restrictions
  6462. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  6463. // schedule(guided).
  6464. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  6465. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  6466. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  6467. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  6468. diag::err_omp_schedule_nonmonotonic_static);
  6469. return nullptr;
  6470. }
  6471. Expr *ValExpr = ChunkSize;
  6472. Stmt *HelperValStmt = nullptr;
  6473. if (ChunkSize) {
  6474. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  6475. !ChunkSize->isInstantiationDependent() &&
  6476. !ChunkSize->containsUnexpandedParameterPack()) {
  6477. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  6478. ExprResult Val =
  6479. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  6480. if (Val.isInvalid())
  6481. return nullptr;
  6482. ValExpr = Val.get();
  6483. // OpenMP [2.7.1, Restrictions]
  6484. // chunk_size must be a loop invariant integer expression with a positive
  6485. // value.
  6486. llvm::APSInt Result;
  6487. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  6488. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  6489. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  6490. << "schedule" << 1 << ChunkSize->getSourceRange();
  6491. return nullptr;
  6492. }
  6493. } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
  6494. !CurContext->isDependentContext()) {
  6495. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  6496. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  6497. HelperValStmt = buildPreInits(Context, Captures);
  6498. }
  6499. }
  6500. }
  6501. return new (Context)
  6502. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  6503. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  6504. }
  6505. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  6506. SourceLocation StartLoc,
  6507. SourceLocation EndLoc) {
  6508. OMPClause *Res = nullptr;
  6509. switch (Kind) {
  6510. case OMPC_ordered:
  6511. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  6512. break;
  6513. case OMPC_nowait:
  6514. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  6515. break;
  6516. case OMPC_untied:
  6517. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  6518. break;
  6519. case OMPC_mergeable:
  6520. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  6521. break;
  6522. case OMPC_read:
  6523. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  6524. break;
  6525. case OMPC_write:
  6526. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  6527. break;
  6528. case OMPC_update:
  6529. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  6530. break;
  6531. case OMPC_capture:
  6532. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  6533. break;
  6534. case OMPC_seq_cst:
  6535. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  6536. break;
  6537. case OMPC_threads:
  6538. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  6539. break;
  6540. case OMPC_simd:
  6541. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  6542. break;
  6543. case OMPC_nogroup:
  6544. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  6545. break;
  6546. case OMPC_if:
  6547. case OMPC_final:
  6548. case OMPC_num_threads:
  6549. case OMPC_safelen:
  6550. case OMPC_simdlen:
  6551. case OMPC_collapse:
  6552. case OMPC_schedule:
  6553. case OMPC_private:
  6554. case OMPC_firstprivate:
  6555. case OMPC_lastprivate:
  6556. case OMPC_shared:
  6557. case OMPC_reduction:
  6558. case OMPC_linear:
  6559. case OMPC_aligned:
  6560. case OMPC_copyin:
  6561. case OMPC_copyprivate:
  6562. case OMPC_default:
  6563. case OMPC_proc_bind:
  6564. case OMPC_threadprivate:
  6565. case OMPC_flush:
  6566. case OMPC_depend:
  6567. case OMPC_device:
  6568. case OMPC_map:
  6569. case OMPC_num_teams:
  6570. case OMPC_thread_limit:
  6571. case OMPC_priority:
  6572. case OMPC_grainsize:
  6573. case OMPC_num_tasks:
  6574. case OMPC_hint:
  6575. case OMPC_dist_schedule:
  6576. case OMPC_defaultmap:
  6577. case OMPC_unknown:
  6578. case OMPC_uniform:
  6579. case OMPC_to:
  6580. case OMPC_from:
  6581. case OMPC_use_device_ptr:
  6582. case OMPC_is_device_ptr:
  6583. llvm_unreachable("Clause is not allowed.");
  6584. }
  6585. return Res;
  6586. }
  6587. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  6588. SourceLocation EndLoc) {
  6589. DSAStack->setNowaitRegion();
  6590. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  6591. }
  6592. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  6593. SourceLocation EndLoc) {
  6594. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  6595. }
  6596. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  6597. SourceLocation EndLoc) {
  6598. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  6599. }
  6600. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  6601. SourceLocation EndLoc) {
  6602. return new (Context) OMPReadClause(StartLoc, EndLoc);
  6603. }
  6604. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  6605. SourceLocation EndLoc) {
  6606. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  6607. }
  6608. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  6609. SourceLocation EndLoc) {
  6610. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  6611. }
  6612. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  6613. SourceLocation EndLoc) {
  6614. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  6615. }
  6616. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  6617. SourceLocation EndLoc) {
  6618. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  6619. }
  6620. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  6621. SourceLocation EndLoc) {
  6622. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  6623. }
  6624. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  6625. SourceLocation EndLoc) {
  6626. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  6627. }
  6628. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  6629. SourceLocation EndLoc) {
  6630. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  6631. }
  6632. OMPClause *Sema::ActOnOpenMPVarListClause(
  6633. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  6634. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  6635. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  6636. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  6637. OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
  6638. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  6639. SourceLocation DepLinMapLoc) {
  6640. OMPClause *Res = nullptr;
  6641. switch (Kind) {
  6642. case OMPC_private:
  6643. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  6644. break;
  6645. case OMPC_firstprivate:
  6646. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  6647. break;
  6648. case OMPC_lastprivate:
  6649. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  6650. break;
  6651. case OMPC_shared:
  6652. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  6653. break;
  6654. case OMPC_reduction:
  6655. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  6656. EndLoc, ReductionIdScopeSpec, ReductionId);
  6657. break;
  6658. case OMPC_linear:
  6659. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  6660. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  6661. break;
  6662. case OMPC_aligned:
  6663. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  6664. ColonLoc, EndLoc);
  6665. break;
  6666. case OMPC_copyin:
  6667. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  6668. break;
  6669. case OMPC_copyprivate:
  6670. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  6671. break;
  6672. case OMPC_flush:
  6673. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  6674. break;
  6675. case OMPC_depend:
  6676. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  6677. StartLoc, LParenLoc, EndLoc);
  6678. break;
  6679. case OMPC_map:
  6680. Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
  6681. DepLinMapLoc, ColonLoc, VarList, StartLoc,
  6682. LParenLoc, EndLoc);
  6683. break;
  6684. case OMPC_to:
  6685. Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
  6686. break;
  6687. case OMPC_from:
  6688. Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
  6689. break;
  6690. case OMPC_use_device_ptr:
  6691. Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  6692. break;
  6693. case OMPC_is_device_ptr:
  6694. Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  6695. break;
  6696. case OMPC_if:
  6697. case OMPC_final:
  6698. case OMPC_num_threads:
  6699. case OMPC_safelen:
  6700. case OMPC_simdlen:
  6701. case OMPC_collapse:
  6702. case OMPC_default:
  6703. case OMPC_proc_bind:
  6704. case OMPC_schedule:
  6705. case OMPC_ordered:
  6706. case OMPC_nowait:
  6707. case OMPC_untied:
  6708. case OMPC_mergeable:
  6709. case OMPC_threadprivate:
  6710. case OMPC_read:
  6711. case OMPC_write:
  6712. case OMPC_update:
  6713. case OMPC_capture:
  6714. case OMPC_seq_cst:
  6715. case OMPC_device:
  6716. case OMPC_threads:
  6717. case OMPC_simd:
  6718. case OMPC_num_teams:
  6719. case OMPC_thread_limit:
  6720. case OMPC_priority:
  6721. case OMPC_grainsize:
  6722. case OMPC_nogroup:
  6723. case OMPC_num_tasks:
  6724. case OMPC_hint:
  6725. case OMPC_dist_schedule:
  6726. case OMPC_defaultmap:
  6727. case OMPC_unknown:
  6728. case OMPC_uniform:
  6729. llvm_unreachable("Clause is not allowed.");
  6730. }
  6731. return Res;
  6732. }
  6733. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  6734. ExprObjectKind OK, SourceLocation Loc) {
  6735. ExprResult Res = BuildDeclRefExpr(
  6736. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  6737. if (!Res.isUsable())
  6738. return ExprError();
  6739. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  6740. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  6741. if (!Res.isUsable())
  6742. return ExprError();
  6743. }
  6744. if (VK != VK_LValue && Res.get()->isGLValue()) {
  6745. Res = DefaultLvalueConversion(Res.get());
  6746. if (!Res.isUsable())
  6747. return ExprError();
  6748. }
  6749. return Res;
  6750. }
  6751. static std::pair<ValueDecl *, bool>
  6752. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  6753. SourceRange &ERange, bool AllowArraySection = false) {
  6754. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  6755. RefExpr->containsUnexpandedParameterPack())
  6756. return std::make_pair(nullptr, true);
  6757. // OpenMP [3.1, C/C++]
  6758. // A list item is a variable name.
  6759. // OpenMP [2.9.3.3, Restrictions, p.1]
  6760. // A variable that is part of another variable (as an array or
  6761. // structure element) cannot appear in a private clause.
  6762. RefExpr = RefExpr->IgnoreParens();
  6763. enum {
  6764. NoArrayExpr = -1,
  6765. ArraySubscript = 0,
  6766. OMPArraySection = 1
  6767. } IsArrayExpr = NoArrayExpr;
  6768. if (AllowArraySection) {
  6769. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  6770. auto *Base = ASE->getBase()->IgnoreParenImpCasts();
  6771. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  6772. Base = TempASE->getBase()->IgnoreParenImpCasts();
  6773. RefExpr = Base;
  6774. IsArrayExpr = ArraySubscript;
  6775. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  6776. auto *Base = OASE->getBase()->IgnoreParenImpCasts();
  6777. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  6778. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  6779. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  6780. Base = TempASE->getBase()->IgnoreParenImpCasts();
  6781. RefExpr = Base;
  6782. IsArrayExpr = OMPArraySection;
  6783. }
  6784. }
  6785. ELoc = RefExpr->getExprLoc();
  6786. ERange = RefExpr->getSourceRange();
  6787. RefExpr = RefExpr->IgnoreParenImpCasts();
  6788. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  6789. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  6790. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  6791. (S.getCurrentThisType().isNull() || !ME ||
  6792. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  6793. !isa<FieldDecl>(ME->getMemberDecl()))) {
  6794. if (IsArrayExpr != NoArrayExpr)
  6795. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  6796. << ERange;
  6797. else {
  6798. S.Diag(ELoc,
  6799. AllowArraySection
  6800. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  6801. : diag::err_omp_expected_var_name_member_expr)
  6802. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  6803. }
  6804. return std::make_pair(nullptr, false);
  6805. }
  6806. return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
  6807. }
  6808. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  6809. SourceLocation StartLoc,
  6810. SourceLocation LParenLoc,
  6811. SourceLocation EndLoc) {
  6812. SmallVector<Expr *, 8> Vars;
  6813. SmallVector<Expr *, 8> PrivateCopies;
  6814. for (auto &RefExpr : VarList) {
  6815. assert(RefExpr && "NULL expr in OpenMP private clause.");
  6816. SourceLocation ELoc;
  6817. SourceRange ERange;
  6818. Expr *SimpleRefExpr = RefExpr;
  6819. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  6820. if (Res.second) {
  6821. // It will be analyzed later.
  6822. Vars.push_back(RefExpr);
  6823. PrivateCopies.push_back(nullptr);
  6824. }
  6825. ValueDecl *D = Res.first;
  6826. if (!D)
  6827. continue;
  6828. QualType Type = D->getType();
  6829. auto *VD = dyn_cast<VarDecl>(D);
  6830. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  6831. // A variable that appears in a private clause must not have an incomplete
  6832. // type or a reference type.
  6833. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  6834. continue;
  6835. Type = Type.getNonReferenceType();
  6836. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  6837. // in a Construct]
  6838. // Variables with the predetermined data-sharing attributes may not be
  6839. // listed in data-sharing attributes clauses, except for the cases
  6840. // listed below. For these exceptions only, listing a predetermined
  6841. // variable in a data-sharing attribute clause is allowed and overrides
  6842. // the variable's predetermined data-sharing attributes.
  6843. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  6844. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  6845. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  6846. << getOpenMPClauseName(OMPC_private);
  6847. ReportOriginalDSA(*this, DSAStack, D, DVar);
  6848. continue;
  6849. }
  6850. auto CurrDir = DSAStack->getCurrentDirective();
  6851. // Variably modified types are not supported for tasks.
  6852. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  6853. isOpenMPTaskingDirective(CurrDir)) {
  6854. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  6855. << getOpenMPClauseName(OMPC_private) << Type
  6856. << getOpenMPDirectiveName(CurrDir);
  6857. bool IsDecl =
  6858. !VD ||
  6859. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6860. Diag(D->getLocation(),
  6861. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6862. << D;
  6863. continue;
  6864. }
  6865. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  6866. // A list item cannot appear in both a map clause and a data-sharing
  6867. // attribute clause on the same construct
  6868. if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
  6869. CurrDir == OMPD_target_teams ||
  6870. CurrDir == OMPD_target_teams_distribute ||
  6871. CurrDir == OMPD_target_teams_distribute_parallel_for) {
  6872. OpenMPClauseKind ConflictKind;
  6873. if (DSAStack->checkMappableExprComponentListsForDecl(
  6874. VD, /*CurrentRegionOnly=*/true,
  6875. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  6876. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  6877. ConflictKind = WhereFoundClauseKind;
  6878. return true;
  6879. })) {
  6880. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  6881. << getOpenMPClauseName(OMPC_private)
  6882. << getOpenMPClauseName(ConflictKind)
  6883. << getOpenMPDirectiveName(CurrDir);
  6884. ReportOriginalDSA(*this, DSAStack, D, DVar);
  6885. continue;
  6886. }
  6887. }
  6888. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  6889. // A variable of class type (or array thereof) that appears in a private
  6890. // clause requires an accessible, unambiguous default constructor for the
  6891. // class type.
  6892. // Generate helper private variable and initialize it with the default
  6893. // value. The address of the original variable is replaced by the address of
  6894. // the new private variable in CodeGen. This new variable is not added to
  6895. // IdResolver, so the code in the OpenMP region uses original variable for
  6896. // proper diagnostics.
  6897. Type = Type.getUnqualifiedType();
  6898. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  6899. D->hasAttrs() ? &D->getAttrs() : nullptr);
  6900. ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
  6901. if (VDPrivate->isInvalidDecl())
  6902. continue;
  6903. auto VDPrivateRefExpr = buildDeclRefExpr(
  6904. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  6905. DeclRefExpr *Ref = nullptr;
  6906. if (!VD && !CurContext->isDependentContext())
  6907. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  6908. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  6909. Vars.push_back((VD || CurContext->isDependentContext())
  6910. ? RefExpr->IgnoreParens()
  6911. : Ref);
  6912. PrivateCopies.push_back(VDPrivateRefExpr);
  6913. }
  6914. if (Vars.empty())
  6915. return nullptr;
  6916. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  6917. PrivateCopies);
  6918. }
  6919. namespace {
  6920. class DiagsUninitializedSeveretyRAII {
  6921. private:
  6922. DiagnosticsEngine &Diags;
  6923. SourceLocation SavedLoc;
  6924. bool IsIgnored;
  6925. public:
  6926. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  6927. bool IsIgnored)
  6928. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  6929. if (!IsIgnored) {
  6930. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  6931. /*Map*/ diag::Severity::Ignored, Loc);
  6932. }
  6933. }
  6934. ~DiagsUninitializedSeveretyRAII() {
  6935. if (!IsIgnored)
  6936. Diags.popMappings(SavedLoc);
  6937. }
  6938. };
  6939. }
  6940. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  6941. SourceLocation StartLoc,
  6942. SourceLocation LParenLoc,
  6943. SourceLocation EndLoc) {
  6944. SmallVector<Expr *, 8> Vars;
  6945. SmallVector<Expr *, 8> PrivateCopies;
  6946. SmallVector<Expr *, 8> Inits;
  6947. SmallVector<Decl *, 4> ExprCaptures;
  6948. bool IsImplicitClause =
  6949. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  6950. auto ImplicitClauseLoc = DSAStack->getConstructLoc();
  6951. for (auto &RefExpr : VarList) {
  6952. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  6953. SourceLocation ELoc;
  6954. SourceRange ERange;
  6955. Expr *SimpleRefExpr = RefExpr;
  6956. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  6957. if (Res.second) {
  6958. // It will be analyzed later.
  6959. Vars.push_back(RefExpr);
  6960. PrivateCopies.push_back(nullptr);
  6961. Inits.push_back(nullptr);
  6962. }
  6963. ValueDecl *D = Res.first;
  6964. if (!D)
  6965. continue;
  6966. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  6967. QualType Type = D->getType();
  6968. auto *VD = dyn_cast<VarDecl>(D);
  6969. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  6970. // A variable that appears in a private clause must not have an incomplete
  6971. // type or a reference type.
  6972. if (RequireCompleteType(ELoc, Type,
  6973. diag::err_omp_firstprivate_incomplete_type))
  6974. continue;
  6975. Type = Type.getNonReferenceType();
  6976. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  6977. // A variable of class type (or array thereof) that appears in a private
  6978. // clause requires an accessible, unambiguous copy constructor for the
  6979. // class type.
  6980. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  6981. // If an implicit firstprivate variable found it was checked already.
  6982. DSAStackTy::DSAVarData TopDVar;
  6983. if (!IsImplicitClause) {
  6984. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  6985. TopDVar = DVar;
  6986. bool IsConstant = ElemType.isConstant(Context);
  6987. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  6988. // A list item that specifies a given variable may not appear in more
  6989. // than one clause on the same directive, except that a variable may be
  6990. // specified in both firstprivate and lastprivate clauses.
  6991. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  6992. DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
  6993. Diag(ELoc, diag::err_omp_wrong_dsa)
  6994. << getOpenMPClauseName(DVar.CKind)
  6995. << getOpenMPClauseName(OMPC_firstprivate);
  6996. ReportOriginalDSA(*this, DSAStack, D, DVar);
  6997. continue;
  6998. }
  6999. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  7000. // in a Construct]
  7001. // Variables with the predetermined data-sharing attributes may not be
  7002. // listed in data-sharing attributes clauses, except for the cases
  7003. // listed below. For these exceptions only, listing a predetermined
  7004. // variable in a data-sharing attribute clause is allowed and overrides
  7005. // the variable's predetermined data-sharing attributes.
  7006. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  7007. // in a Construct, C/C++, p.2]
  7008. // Variables with const-qualified type having no mutable member may be
  7009. // listed in a firstprivate clause, even if they are static data members.
  7010. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  7011. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  7012. Diag(ELoc, diag::err_omp_wrong_dsa)
  7013. << getOpenMPClauseName(DVar.CKind)
  7014. << getOpenMPClauseName(OMPC_firstprivate);
  7015. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7016. continue;
  7017. }
  7018. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  7019. // OpenMP [2.9.3.4, Restrictions, p.2]
  7020. // A list item that is private within a parallel region must not appear
  7021. // in a firstprivate clause on a worksharing construct if any of the
  7022. // worksharing regions arising from the worksharing construct ever bind
  7023. // to any of the parallel regions arising from the parallel construct.
  7024. if (isOpenMPWorksharingDirective(CurrDir) &&
  7025. !isOpenMPParallelDirective(CurrDir) &&
  7026. !isOpenMPTeamsDirective(CurrDir)) {
  7027. DVar = DSAStack->getImplicitDSA(D, true);
  7028. if (DVar.CKind != OMPC_shared &&
  7029. (isOpenMPParallelDirective(DVar.DKind) ||
  7030. DVar.DKind == OMPD_unknown)) {
  7031. Diag(ELoc, diag::err_omp_required_access)
  7032. << getOpenMPClauseName(OMPC_firstprivate)
  7033. << getOpenMPClauseName(OMPC_shared);
  7034. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7035. continue;
  7036. }
  7037. }
  7038. // OpenMP [2.9.3.4, Restrictions, p.3]
  7039. // A list item that appears in a reduction clause of a parallel construct
  7040. // must not appear in a firstprivate clause on a worksharing or task
  7041. // construct if any of the worksharing or task regions arising from the
  7042. // worksharing or task construct ever bind to any of the parallel regions
  7043. // arising from the parallel construct.
  7044. // OpenMP [2.9.3.4, Restrictions, p.4]
  7045. // A list item that appears in a reduction clause in worksharing
  7046. // construct must not appear in a firstprivate clause in a task construct
  7047. // encountered during execution of any of the worksharing regions arising
  7048. // from the worksharing construct.
  7049. if (isOpenMPTaskingDirective(CurrDir)) {
  7050. DVar = DSAStack->hasInnermostDSA(
  7051. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  7052. [](OpenMPDirectiveKind K) -> bool {
  7053. return isOpenMPParallelDirective(K) ||
  7054. isOpenMPWorksharingDirective(K);
  7055. },
  7056. false);
  7057. if (DVar.CKind == OMPC_reduction &&
  7058. (isOpenMPParallelDirective(DVar.DKind) ||
  7059. isOpenMPWorksharingDirective(DVar.DKind))) {
  7060. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  7061. << getOpenMPDirectiveName(DVar.DKind);
  7062. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7063. continue;
  7064. }
  7065. }
  7066. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  7067. // A list item that is private within a teams region must not appear in a
  7068. // firstprivate clause on a distribute construct if any of the distribute
  7069. // regions arising from the distribute construct ever bind to any of the
  7070. // teams regions arising from the teams construct.
  7071. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  7072. // A list item that appears in a reduction clause of a teams construct
  7073. // must not appear in a firstprivate clause on a distribute construct if
  7074. // any of the distribute regions arising from the distribute construct
  7075. // ever bind to any of the teams regions arising from the teams construct.
  7076. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  7077. // A list item may appear in a firstprivate or lastprivate clause but not
  7078. // both.
  7079. if (CurrDir == OMPD_distribute) {
  7080. DVar = DSAStack->hasInnermostDSA(
  7081. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
  7082. [](OpenMPDirectiveKind K) -> bool {
  7083. return isOpenMPTeamsDirective(K);
  7084. },
  7085. false);
  7086. if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
  7087. Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
  7088. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7089. continue;
  7090. }
  7091. DVar = DSAStack->hasInnermostDSA(
  7092. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  7093. [](OpenMPDirectiveKind K) -> bool {
  7094. return isOpenMPTeamsDirective(K);
  7095. },
  7096. false);
  7097. if (DVar.CKind == OMPC_reduction &&
  7098. isOpenMPTeamsDirective(DVar.DKind)) {
  7099. Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
  7100. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7101. continue;
  7102. }
  7103. DVar = DSAStack->getTopDSA(D, false);
  7104. if (DVar.CKind == OMPC_lastprivate) {
  7105. Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
  7106. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7107. continue;
  7108. }
  7109. }
  7110. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  7111. // A list item cannot appear in both a map clause and a data-sharing
  7112. // attribute clause on the same construct
  7113. if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
  7114. CurrDir == OMPD_target_teams ||
  7115. CurrDir == OMPD_target_teams_distribute ||
  7116. CurrDir == OMPD_target_teams_distribute_parallel_for) {
  7117. OpenMPClauseKind ConflictKind;
  7118. if (DSAStack->checkMappableExprComponentListsForDecl(
  7119. VD, /*CurrentRegionOnly=*/true,
  7120. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  7121. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  7122. ConflictKind = WhereFoundClauseKind;
  7123. return true;
  7124. })) {
  7125. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  7126. << getOpenMPClauseName(OMPC_firstprivate)
  7127. << getOpenMPClauseName(ConflictKind)
  7128. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  7129. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7130. continue;
  7131. }
  7132. }
  7133. }
  7134. // Variably modified types are not supported for tasks.
  7135. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  7136. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  7137. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  7138. << getOpenMPClauseName(OMPC_firstprivate) << Type
  7139. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  7140. bool IsDecl =
  7141. !VD ||
  7142. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  7143. Diag(D->getLocation(),
  7144. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  7145. << D;
  7146. continue;
  7147. }
  7148. Type = Type.getUnqualifiedType();
  7149. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  7150. D->hasAttrs() ? &D->getAttrs() : nullptr);
  7151. // Generate helper private variable and initialize it with the value of the
  7152. // original variable. The address of the original variable is replaced by
  7153. // the address of the new private variable in the CodeGen. This new variable
  7154. // is not added to IdResolver, so the code in the OpenMP region uses
  7155. // original variable for proper diagnostics and variable capturing.
  7156. Expr *VDInitRefExpr = nullptr;
  7157. // For arrays generate initializer for single element and replace it by the
  7158. // original array element in CodeGen.
  7159. if (Type->isArrayType()) {
  7160. auto VDInit =
  7161. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  7162. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  7163. auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
  7164. ElemType = ElemType.getUnqualifiedType();
  7165. auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  7166. ".firstprivate.temp");
  7167. InitializedEntity Entity =
  7168. InitializedEntity::InitializeVariable(VDInitTemp);
  7169. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  7170. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  7171. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  7172. if (Result.isInvalid())
  7173. VDPrivate->setInvalidDecl();
  7174. else
  7175. VDPrivate->setInit(Result.getAs<Expr>());
  7176. // Remove temp variable declaration.
  7177. Context.Deallocate(VDInitTemp);
  7178. } else {
  7179. auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  7180. ".firstprivate.temp");
  7181. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  7182. RefExpr->getExprLoc());
  7183. AddInitializerToDecl(VDPrivate,
  7184. DefaultLvalueConversion(VDInitRefExpr).get(),
  7185. /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
  7186. }
  7187. if (VDPrivate->isInvalidDecl()) {
  7188. if (IsImplicitClause) {
  7189. Diag(RefExpr->getExprLoc(),
  7190. diag::note_omp_task_predetermined_firstprivate_here);
  7191. }
  7192. continue;
  7193. }
  7194. CurContext->addDecl(VDPrivate);
  7195. auto VDPrivateRefExpr = buildDeclRefExpr(
  7196. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  7197. RefExpr->getExprLoc());
  7198. DeclRefExpr *Ref = nullptr;
  7199. if (!VD && !CurContext->isDependentContext()) {
  7200. if (TopDVar.CKind == OMPC_lastprivate)
  7201. Ref = TopDVar.PrivateCopy;
  7202. else {
  7203. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  7204. if (!IsOpenMPCapturedDecl(D))
  7205. ExprCaptures.push_back(Ref->getDecl());
  7206. }
  7207. }
  7208. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  7209. Vars.push_back((VD || CurContext->isDependentContext())
  7210. ? RefExpr->IgnoreParens()
  7211. : Ref);
  7212. PrivateCopies.push_back(VDPrivateRefExpr);
  7213. Inits.push_back(VDInitRefExpr);
  7214. }
  7215. if (Vars.empty())
  7216. return nullptr;
  7217. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  7218. Vars, PrivateCopies, Inits,
  7219. buildPreInits(Context, ExprCaptures));
  7220. }
  7221. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  7222. SourceLocation StartLoc,
  7223. SourceLocation LParenLoc,
  7224. SourceLocation EndLoc) {
  7225. SmallVector<Expr *, 8> Vars;
  7226. SmallVector<Expr *, 8> SrcExprs;
  7227. SmallVector<Expr *, 8> DstExprs;
  7228. SmallVector<Expr *, 8> AssignmentOps;
  7229. SmallVector<Decl *, 4> ExprCaptures;
  7230. SmallVector<Expr *, 4> ExprPostUpdates;
  7231. for (auto &RefExpr : VarList) {
  7232. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  7233. SourceLocation ELoc;
  7234. SourceRange ERange;
  7235. Expr *SimpleRefExpr = RefExpr;
  7236. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  7237. if (Res.second) {
  7238. // It will be analyzed later.
  7239. Vars.push_back(RefExpr);
  7240. SrcExprs.push_back(nullptr);
  7241. DstExprs.push_back(nullptr);
  7242. AssignmentOps.push_back(nullptr);
  7243. }
  7244. ValueDecl *D = Res.first;
  7245. if (!D)
  7246. continue;
  7247. QualType Type = D->getType();
  7248. auto *VD = dyn_cast<VarDecl>(D);
  7249. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  7250. // A variable that appears in a lastprivate clause must not have an
  7251. // incomplete type or a reference type.
  7252. if (RequireCompleteType(ELoc, Type,
  7253. diag::err_omp_lastprivate_incomplete_type))
  7254. continue;
  7255. Type = Type.getNonReferenceType();
  7256. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  7257. // in a Construct]
  7258. // Variables with the predetermined data-sharing attributes may not be
  7259. // listed in data-sharing attributes clauses, except for the cases
  7260. // listed below.
  7261. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  7262. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  7263. DVar.CKind != OMPC_firstprivate &&
  7264. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  7265. Diag(ELoc, diag::err_omp_wrong_dsa)
  7266. << getOpenMPClauseName(DVar.CKind)
  7267. << getOpenMPClauseName(OMPC_lastprivate);
  7268. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7269. continue;
  7270. }
  7271. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  7272. // OpenMP [2.14.3.5, Restrictions, p.2]
  7273. // A list item that is private within a parallel region, or that appears in
  7274. // the reduction clause of a parallel construct, must not appear in a
  7275. // lastprivate clause on a worksharing construct if any of the corresponding
  7276. // worksharing regions ever binds to any of the corresponding parallel
  7277. // regions.
  7278. DSAStackTy::DSAVarData TopDVar = DVar;
  7279. if (isOpenMPWorksharingDirective(CurrDir) &&
  7280. !isOpenMPParallelDirective(CurrDir) &&
  7281. !isOpenMPTeamsDirective(CurrDir)) {
  7282. DVar = DSAStack->getImplicitDSA(D, true);
  7283. if (DVar.CKind != OMPC_shared) {
  7284. Diag(ELoc, diag::err_omp_required_access)
  7285. << getOpenMPClauseName(OMPC_lastprivate)
  7286. << getOpenMPClauseName(OMPC_shared);
  7287. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7288. continue;
  7289. }
  7290. }
  7291. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  7292. // A list item may appear in a firstprivate or lastprivate clause but not
  7293. // both.
  7294. if (CurrDir == OMPD_distribute) {
  7295. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  7296. if (DVar.CKind == OMPC_firstprivate) {
  7297. Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
  7298. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7299. continue;
  7300. }
  7301. }
  7302. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  7303. // A variable of class type (or array thereof) that appears in a
  7304. // lastprivate clause requires an accessible, unambiguous default
  7305. // constructor for the class type, unless the list item is also specified
  7306. // in a firstprivate clause.
  7307. // A variable of class type (or array thereof) that appears in a
  7308. // lastprivate clause requires an accessible, unambiguous copy assignment
  7309. // operator for the class type.
  7310. Type = Context.getBaseElementType(Type).getNonReferenceType();
  7311. auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  7312. Type.getUnqualifiedType(), ".lastprivate.src",
  7313. D->hasAttrs() ? &D->getAttrs() : nullptr);
  7314. auto *PseudoSrcExpr =
  7315. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  7316. auto *DstVD =
  7317. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  7318. D->hasAttrs() ? &D->getAttrs() : nullptr);
  7319. auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  7320. // For arrays generate assignment operation for single element and replace
  7321. // it by the original array element in CodeGen.
  7322. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  7323. PseudoDstExpr, PseudoSrcExpr);
  7324. if (AssignmentOp.isInvalid())
  7325. continue;
  7326. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  7327. /*DiscardedValue=*/true);
  7328. if (AssignmentOp.isInvalid())
  7329. continue;
  7330. DeclRefExpr *Ref = nullptr;
  7331. if (!VD && !CurContext->isDependentContext()) {
  7332. if (TopDVar.CKind == OMPC_firstprivate)
  7333. Ref = TopDVar.PrivateCopy;
  7334. else {
  7335. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  7336. if (!IsOpenMPCapturedDecl(D))
  7337. ExprCaptures.push_back(Ref->getDecl());
  7338. }
  7339. if (TopDVar.CKind == OMPC_firstprivate ||
  7340. (!IsOpenMPCapturedDecl(D) &&
  7341. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  7342. ExprResult RefRes = DefaultLvalueConversion(Ref);
  7343. if (!RefRes.isUsable())
  7344. continue;
  7345. ExprResult PostUpdateRes =
  7346. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  7347. RefRes.get());
  7348. if (!PostUpdateRes.isUsable())
  7349. continue;
  7350. ExprPostUpdates.push_back(
  7351. IgnoredValueConversions(PostUpdateRes.get()).get());
  7352. }
  7353. }
  7354. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  7355. Vars.push_back((VD || CurContext->isDependentContext())
  7356. ? RefExpr->IgnoreParens()
  7357. : Ref);
  7358. SrcExprs.push_back(PseudoSrcExpr);
  7359. DstExprs.push_back(PseudoDstExpr);
  7360. AssignmentOps.push_back(AssignmentOp.get());
  7361. }
  7362. if (Vars.empty())
  7363. return nullptr;
  7364. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  7365. Vars, SrcExprs, DstExprs, AssignmentOps,
  7366. buildPreInits(Context, ExprCaptures),
  7367. buildPostUpdate(*this, ExprPostUpdates));
  7368. }
  7369. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  7370. SourceLocation StartLoc,
  7371. SourceLocation LParenLoc,
  7372. SourceLocation EndLoc) {
  7373. SmallVector<Expr *, 8> Vars;
  7374. for (auto &RefExpr : VarList) {
  7375. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  7376. SourceLocation ELoc;
  7377. SourceRange ERange;
  7378. Expr *SimpleRefExpr = RefExpr;
  7379. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  7380. if (Res.second) {
  7381. // It will be analyzed later.
  7382. Vars.push_back(RefExpr);
  7383. }
  7384. ValueDecl *D = Res.first;
  7385. if (!D)
  7386. continue;
  7387. auto *VD = dyn_cast<VarDecl>(D);
  7388. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  7389. // in a Construct]
  7390. // Variables with the predetermined data-sharing attributes may not be
  7391. // listed in data-sharing attributes clauses, except for the cases
  7392. // listed below. For these exceptions only, listing a predetermined
  7393. // variable in a data-sharing attribute clause is allowed and overrides
  7394. // the variable's predetermined data-sharing attributes.
  7395. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  7396. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  7397. DVar.RefExpr) {
  7398. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  7399. << getOpenMPClauseName(OMPC_shared);
  7400. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7401. continue;
  7402. }
  7403. DeclRefExpr *Ref = nullptr;
  7404. if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  7405. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  7406. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  7407. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  7408. ? RefExpr->IgnoreParens()
  7409. : Ref);
  7410. }
  7411. if (Vars.empty())
  7412. return nullptr;
  7413. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  7414. }
  7415. namespace {
  7416. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  7417. DSAStackTy *Stack;
  7418. public:
  7419. bool VisitDeclRefExpr(DeclRefExpr *E) {
  7420. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
  7421. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
  7422. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  7423. return false;
  7424. if (DVar.CKind != OMPC_unknown)
  7425. return true;
  7426. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  7427. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
  7428. false);
  7429. if (DVarPrivate.CKind != OMPC_unknown)
  7430. return true;
  7431. return false;
  7432. }
  7433. return false;
  7434. }
  7435. bool VisitStmt(Stmt *S) {
  7436. for (auto Child : S->children()) {
  7437. if (Child && Visit(Child))
  7438. return true;
  7439. }
  7440. return false;
  7441. }
  7442. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  7443. };
  7444. } // namespace
  7445. namespace {
  7446. // Transform MemberExpression for specified FieldDecl of current class to
  7447. // DeclRefExpr to specified OMPCapturedExprDecl.
  7448. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  7449. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  7450. ValueDecl *Field;
  7451. DeclRefExpr *CapturedExpr;
  7452. public:
  7453. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  7454. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  7455. ExprResult TransformMemberExpr(MemberExpr *E) {
  7456. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  7457. E->getMemberDecl() == Field) {
  7458. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  7459. return CapturedExpr;
  7460. }
  7461. return BaseTransform::TransformMemberExpr(E);
  7462. }
  7463. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  7464. };
  7465. } // namespace
  7466. template <typename T>
  7467. static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
  7468. const llvm::function_ref<T(ValueDecl *)> &Gen) {
  7469. for (auto &Set : Lookups) {
  7470. for (auto *D : Set) {
  7471. if (auto Res = Gen(cast<ValueDecl>(D)))
  7472. return Res;
  7473. }
  7474. }
  7475. return T();
  7476. }
  7477. static ExprResult
  7478. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  7479. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  7480. const DeclarationNameInfo &ReductionId, QualType Ty,
  7481. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  7482. if (ReductionIdScopeSpec.isInvalid())
  7483. return ExprError();
  7484. SmallVector<UnresolvedSet<8>, 4> Lookups;
  7485. if (S) {
  7486. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  7487. Lookup.suppressDiagnostics();
  7488. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  7489. auto *D = Lookup.getRepresentativeDecl();
  7490. do {
  7491. S = S->getParent();
  7492. } while (S && !S->isDeclScope(D));
  7493. if (S)
  7494. S = S->getParent();
  7495. Lookups.push_back(UnresolvedSet<8>());
  7496. Lookups.back().append(Lookup.begin(), Lookup.end());
  7497. Lookup.clear();
  7498. }
  7499. } else if (auto *ULE =
  7500. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  7501. Lookups.push_back(UnresolvedSet<8>());
  7502. Decl *PrevD = nullptr;
  7503. for (auto *D : ULE->decls()) {
  7504. if (D == PrevD)
  7505. Lookups.push_back(UnresolvedSet<8>());
  7506. else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
  7507. Lookups.back().addDecl(DRD);
  7508. PrevD = D;
  7509. }
  7510. }
  7511. if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
  7512. Ty->containsUnexpandedParameterPack() ||
  7513. filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
  7514. return !D->isInvalidDecl() &&
  7515. (D->getType()->isDependentType() ||
  7516. D->getType()->isInstantiationDependentType() ||
  7517. D->getType()->containsUnexpandedParameterPack());
  7518. })) {
  7519. UnresolvedSet<8> ResSet;
  7520. for (auto &Set : Lookups) {
  7521. ResSet.append(Set.begin(), Set.end());
  7522. // The last item marks the end of all declarations at the specified scope.
  7523. ResSet.addDecl(Set[Set.size() - 1]);
  7524. }
  7525. return UnresolvedLookupExpr::Create(
  7526. SemaRef.Context, /*NamingClass=*/nullptr,
  7527. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  7528. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  7529. }
  7530. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  7531. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  7532. if (!D->isInvalidDecl() &&
  7533. SemaRef.Context.hasSameType(D->getType(), Ty))
  7534. return D;
  7535. return nullptr;
  7536. }))
  7537. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  7538. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  7539. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  7540. if (!D->isInvalidDecl() &&
  7541. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  7542. !Ty.isMoreQualifiedThan(D->getType()))
  7543. return D;
  7544. return nullptr;
  7545. })) {
  7546. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  7547. /*DetectVirtual=*/false);
  7548. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  7549. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  7550. VD->getType().getUnqualifiedType()))) {
  7551. if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
  7552. /*DiagID=*/0) !=
  7553. Sema::AR_inaccessible) {
  7554. SemaRef.BuildBasePathArray(Paths, BasePath);
  7555. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  7556. }
  7557. }
  7558. }
  7559. }
  7560. if (ReductionIdScopeSpec.isSet()) {
  7561. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  7562. return ExprError();
  7563. }
  7564. return ExprEmpty();
  7565. }
  7566. OMPClause *Sema::ActOnOpenMPReductionClause(
  7567. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  7568. SourceLocation ColonLoc, SourceLocation EndLoc,
  7569. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  7570. ArrayRef<Expr *> UnresolvedReductions) {
  7571. auto DN = ReductionId.getName();
  7572. auto OOK = DN.getCXXOverloadedOperator();
  7573. BinaryOperatorKind BOK = BO_Comma;
  7574. // OpenMP [2.14.3.6, reduction clause]
  7575. // C
  7576. // reduction-identifier is either an identifier or one of the following
  7577. // operators: +, -, *, &, |, ^, && and ||
  7578. // C++
  7579. // reduction-identifier is either an id-expression or one of the following
  7580. // operators: +, -, *, &, |, ^, && and ||
  7581. // FIXME: Only 'min' and 'max' identifiers are supported for now.
  7582. switch (OOK) {
  7583. case OO_Plus:
  7584. case OO_Minus:
  7585. BOK = BO_Add;
  7586. break;
  7587. case OO_Star:
  7588. BOK = BO_Mul;
  7589. break;
  7590. case OO_Amp:
  7591. BOK = BO_And;
  7592. break;
  7593. case OO_Pipe:
  7594. BOK = BO_Or;
  7595. break;
  7596. case OO_Caret:
  7597. BOK = BO_Xor;
  7598. break;
  7599. case OO_AmpAmp:
  7600. BOK = BO_LAnd;
  7601. break;
  7602. case OO_PipePipe:
  7603. BOK = BO_LOr;
  7604. break;
  7605. case OO_New:
  7606. case OO_Delete:
  7607. case OO_Array_New:
  7608. case OO_Array_Delete:
  7609. case OO_Slash:
  7610. case OO_Percent:
  7611. case OO_Tilde:
  7612. case OO_Exclaim:
  7613. case OO_Equal:
  7614. case OO_Less:
  7615. case OO_Greater:
  7616. case OO_LessEqual:
  7617. case OO_GreaterEqual:
  7618. case OO_PlusEqual:
  7619. case OO_MinusEqual:
  7620. case OO_StarEqual:
  7621. case OO_SlashEqual:
  7622. case OO_PercentEqual:
  7623. case OO_CaretEqual:
  7624. case OO_AmpEqual:
  7625. case OO_PipeEqual:
  7626. case OO_LessLess:
  7627. case OO_GreaterGreater:
  7628. case OO_LessLessEqual:
  7629. case OO_GreaterGreaterEqual:
  7630. case OO_EqualEqual:
  7631. case OO_ExclaimEqual:
  7632. case OO_PlusPlus:
  7633. case OO_MinusMinus:
  7634. case OO_Comma:
  7635. case OO_ArrowStar:
  7636. case OO_Arrow:
  7637. case OO_Call:
  7638. case OO_Subscript:
  7639. case OO_Conditional:
  7640. case OO_Coawait:
  7641. case NUM_OVERLOADED_OPERATORS:
  7642. llvm_unreachable("Unexpected reduction identifier");
  7643. case OO_None:
  7644. if (auto II = DN.getAsIdentifierInfo()) {
  7645. if (II->isStr("max"))
  7646. BOK = BO_GT;
  7647. else if (II->isStr("min"))
  7648. BOK = BO_LT;
  7649. }
  7650. break;
  7651. }
  7652. SourceRange ReductionIdRange;
  7653. if (ReductionIdScopeSpec.isValid())
  7654. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  7655. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  7656. SmallVector<Expr *, 8> Vars;
  7657. SmallVector<Expr *, 8> Privates;
  7658. SmallVector<Expr *, 8> LHSs;
  7659. SmallVector<Expr *, 8> RHSs;
  7660. SmallVector<Expr *, 8> ReductionOps;
  7661. SmallVector<Decl *, 4> ExprCaptures;
  7662. SmallVector<Expr *, 4> ExprPostUpdates;
  7663. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  7664. bool FirstIter = true;
  7665. for (auto RefExpr : VarList) {
  7666. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  7667. // OpenMP [2.1, C/C++]
  7668. // A list item is a variable or array section, subject to the restrictions
  7669. // specified in Section 2.4 on page 42 and in each of the sections
  7670. // describing clauses and directives for which a list appears.
  7671. // OpenMP [2.14.3.3, Restrictions, p.1]
  7672. // A variable that is part of another variable (as an array or
  7673. // structure element) cannot appear in a private clause.
  7674. if (!FirstIter && IR != ER)
  7675. ++IR;
  7676. FirstIter = false;
  7677. SourceLocation ELoc;
  7678. SourceRange ERange;
  7679. Expr *SimpleRefExpr = RefExpr;
  7680. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  7681. /*AllowArraySection=*/true);
  7682. if (Res.second) {
  7683. // It will be analyzed later.
  7684. Vars.push_back(RefExpr);
  7685. Privates.push_back(nullptr);
  7686. LHSs.push_back(nullptr);
  7687. RHSs.push_back(nullptr);
  7688. // Try to find 'declare reduction' corresponding construct before using
  7689. // builtin/overloaded operators.
  7690. QualType Type = Context.DependentTy;
  7691. CXXCastPath BasePath;
  7692. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  7693. *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
  7694. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  7695. if (CurContext->isDependentContext() &&
  7696. (DeclareReductionRef.isUnset() ||
  7697. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  7698. ReductionOps.push_back(DeclareReductionRef.get());
  7699. else
  7700. ReductionOps.push_back(nullptr);
  7701. }
  7702. ValueDecl *D = Res.first;
  7703. if (!D)
  7704. continue;
  7705. QualType Type;
  7706. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  7707. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  7708. if (ASE)
  7709. Type = ASE->getType().getNonReferenceType();
  7710. else if (OASE) {
  7711. auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  7712. if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
  7713. Type = ATy->getElementType();
  7714. else
  7715. Type = BaseType->getPointeeType();
  7716. Type = Type.getNonReferenceType();
  7717. } else
  7718. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  7719. auto *VD = dyn_cast<VarDecl>(D);
  7720. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  7721. // A variable that appears in a private clause must not have an incomplete
  7722. // type or a reference type.
  7723. if (RequireCompleteType(ELoc, Type,
  7724. diag::err_omp_reduction_incomplete_type))
  7725. continue;
  7726. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  7727. // A list item that appears in a reduction clause must not be
  7728. // const-qualified.
  7729. if (Type.getNonReferenceType().isConstant(Context)) {
  7730. Diag(ELoc, diag::err_omp_const_reduction_list_item)
  7731. << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
  7732. if (!ASE && !OASE) {
  7733. bool IsDecl = !VD ||
  7734. VD->isThisDeclarationADefinition(Context) ==
  7735. VarDecl::DeclarationOnly;
  7736. Diag(D->getLocation(),
  7737. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  7738. << D;
  7739. }
  7740. continue;
  7741. }
  7742. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  7743. // If a list-item is a reference type then it must bind to the same object
  7744. // for all threads of the team.
  7745. if (!ASE && !OASE && VD) {
  7746. VarDecl *VDDef = VD->getDefinition();
  7747. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  7748. DSARefChecker Check(DSAStack);
  7749. if (Check.Visit(VDDef->getInit())) {
  7750. Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
  7751. Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  7752. continue;
  7753. }
  7754. }
  7755. }
  7756. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  7757. // in a Construct]
  7758. // Variables with the predetermined data-sharing attributes may not be
  7759. // listed in data-sharing attributes clauses, except for the cases
  7760. // listed below. For these exceptions only, listing a predetermined
  7761. // variable in a data-sharing attribute clause is allowed and overrides
  7762. // the variable's predetermined data-sharing attributes.
  7763. // OpenMP [2.14.3.6, Restrictions, p.3]
  7764. // Any number of reduction clauses can be specified on the directive,
  7765. // but a list item can appear only once in the reduction clauses for that
  7766. // directive.
  7767. DSAStackTy::DSAVarData DVar;
  7768. DVar = DSAStack->getTopDSA(D, false);
  7769. if (DVar.CKind == OMPC_reduction) {
  7770. Diag(ELoc, diag::err_omp_once_referenced)
  7771. << getOpenMPClauseName(OMPC_reduction);
  7772. if (DVar.RefExpr)
  7773. Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  7774. } else if (DVar.CKind != OMPC_unknown) {
  7775. Diag(ELoc, diag::err_omp_wrong_dsa)
  7776. << getOpenMPClauseName(DVar.CKind)
  7777. << getOpenMPClauseName(OMPC_reduction);
  7778. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7779. continue;
  7780. }
  7781. // OpenMP [2.14.3.6, Restrictions, p.1]
  7782. // A list item that appears in a reduction clause of a worksharing
  7783. // construct must be shared in the parallel regions to which any of the
  7784. // worksharing regions arising from the worksharing construct bind.
  7785. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  7786. if (isOpenMPWorksharingDirective(CurrDir) &&
  7787. !isOpenMPParallelDirective(CurrDir) &&
  7788. !isOpenMPTeamsDirective(CurrDir)) {
  7789. DVar = DSAStack->getImplicitDSA(D, true);
  7790. if (DVar.CKind != OMPC_shared) {
  7791. Diag(ELoc, diag::err_omp_required_access)
  7792. << getOpenMPClauseName(OMPC_reduction)
  7793. << getOpenMPClauseName(OMPC_shared);
  7794. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7795. continue;
  7796. }
  7797. }
  7798. // Try to find 'declare reduction' corresponding construct before using
  7799. // builtin/overloaded operators.
  7800. CXXCastPath BasePath;
  7801. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  7802. *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
  7803. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  7804. if (DeclareReductionRef.isInvalid())
  7805. continue;
  7806. if (CurContext->isDependentContext() &&
  7807. (DeclareReductionRef.isUnset() ||
  7808. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  7809. Vars.push_back(RefExpr);
  7810. Privates.push_back(nullptr);
  7811. LHSs.push_back(nullptr);
  7812. RHSs.push_back(nullptr);
  7813. ReductionOps.push_back(DeclareReductionRef.get());
  7814. continue;
  7815. }
  7816. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  7817. // Not allowed reduction identifier is found.
  7818. Diag(ReductionId.getLocStart(),
  7819. diag::err_omp_unknown_reduction_identifier)
  7820. << Type << ReductionIdRange;
  7821. continue;
  7822. }
  7823. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  7824. // The type of a list item that appears in a reduction clause must be valid
  7825. // for the reduction-identifier. For a max or min reduction in C, the type
  7826. // of the list item must be an allowed arithmetic data type: char, int,
  7827. // float, double, or _Bool, possibly modified with long, short, signed, or
  7828. // unsigned. For a max or min reduction in C++, the type of the list item
  7829. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  7830. // double, or bool, possibly modified with long, short, signed, or unsigned.
  7831. if (DeclareReductionRef.isUnset()) {
  7832. if ((BOK == BO_GT || BOK == BO_LT) &&
  7833. !(Type->isScalarType() ||
  7834. (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  7835. Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  7836. << getLangOpts().CPlusPlus;
  7837. if (!ASE && !OASE) {
  7838. bool IsDecl = !VD ||
  7839. VD->isThisDeclarationADefinition(Context) ==
  7840. VarDecl::DeclarationOnly;
  7841. Diag(D->getLocation(),
  7842. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  7843. << D;
  7844. }
  7845. continue;
  7846. }
  7847. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  7848. !getLangOpts().CPlusPlus && Type->isFloatingType()) {
  7849. Diag(ELoc, diag::err_omp_clause_floating_type_arg);
  7850. if (!ASE && !OASE) {
  7851. bool IsDecl = !VD ||
  7852. VD->isThisDeclarationADefinition(Context) ==
  7853. VarDecl::DeclarationOnly;
  7854. Diag(D->getLocation(),
  7855. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  7856. << D;
  7857. }
  7858. continue;
  7859. }
  7860. }
  7861. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  7862. auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
  7863. D->hasAttrs() ? &D->getAttrs() : nullptr);
  7864. auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
  7865. D->hasAttrs() ? &D->getAttrs() : nullptr);
  7866. auto PrivateTy = Type;
  7867. if (OASE ||
  7868. (!ASE &&
  7869. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  7870. // For arrays/array sections only:
  7871. // Create pseudo array type for private copy. The size for this array will
  7872. // be generated during codegen.
  7873. // For array subscripts or single variables Private Ty is the same as Type
  7874. // (type of the variable or single array element).
  7875. PrivateTy = Context.getVariableArrayType(
  7876. Type, new (Context) OpaqueValueExpr(SourceLocation(),
  7877. Context.getSizeType(), VK_RValue),
  7878. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  7879. } else if (!ASE && !OASE &&
  7880. Context.getAsArrayType(D->getType().getNonReferenceType()))
  7881. PrivateTy = D->getType().getNonReferenceType();
  7882. // Private copy.
  7883. auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
  7884. D->hasAttrs() ? &D->getAttrs() : nullptr);
  7885. // Add initializer for private variable.
  7886. Expr *Init = nullptr;
  7887. auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
  7888. auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
  7889. if (DeclareReductionRef.isUsable()) {
  7890. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  7891. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  7892. if (DRD->getInitializer()) {
  7893. Init = DRDRef;
  7894. RHSVD->setInit(DRDRef);
  7895. RHSVD->setInitStyle(VarDecl::CallInit);
  7896. }
  7897. } else {
  7898. switch (BOK) {
  7899. case BO_Add:
  7900. case BO_Xor:
  7901. case BO_Or:
  7902. case BO_LOr:
  7903. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  7904. if (Type->isScalarType() || Type->isAnyComplexType())
  7905. Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  7906. break;
  7907. case BO_Mul:
  7908. case BO_LAnd:
  7909. if (Type->isScalarType() || Type->isAnyComplexType()) {
  7910. // '*' and '&&' reduction ops - initializer is '1'.
  7911. Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  7912. }
  7913. break;
  7914. case BO_And: {
  7915. // '&' reduction op - initializer is '~0'.
  7916. QualType OrigType = Type;
  7917. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  7918. Type = ComplexTy->getElementType();
  7919. if (Type->isRealFloatingType()) {
  7920. llvm::APFloat InitValue =
  7921. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  7922. /*isIEEE=*/true);
  7923. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  7924. Type, ELoc);
  7925. } else if (Type->isScalarType()) {
  7926. auto Size = Context.getTypeSize(Type);
  7927. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  7928. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  7929. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  7930. }
  7931. if (Init && OrigType->isAnyComplexType()) {
  7932. // Init = 0xFFFF + 0xFFFFi;
  7933. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  7934. Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  7935. }
  7936. Type = OrigType;
  7937. break;
  7938. }
  7939. case BO_LT:
  7940. case BO_GT: {
  7941. // 'min' reduction op - initializer is 'Largest representable number in
  7942. // the reduction list item type'.
  7943. // 'max' reduction op - initializer is 'Least representable number in
  7944. // the reduction list item type'.
  7945. if (Type->isIntegerType() || Type->isPointerType()) {
  7946. bool IsSigned = Type->hasSignedIntegerRepresentation();
  7947. auto Size = Context.getTypeSize(Type);
  7948. QualType IntTy =
  7949. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  7950. llvm::APInt InitValue =
  7951. (BOK != BO_LT)
  7952. ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  7953. : llvm::APInt::getMinValue(Size)
  7954. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  7955. : llvm::APInt::getMaxValue(Size);
  7956. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  7957. if (Type->isPointerType()) {
  7958. // Cast to pointer type.
  7959. auto CastExpr = BuildCStyleCastExpr(
  7960. SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
  7961. SourceLocation(), Init);
  7962. if (CastExpr.isInvalid())
  7963. continue;
  7964. Init = CastExpr.get();
  7965. }
  7966. } else if (Type->isRealFloatingType()) {
  7967. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  7968. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  7969. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  7970. Type, ELoc);
  7971. }
  7972. break;
  7973. }
  7974. case BO_PtrMemD:
  7975. case BO_PtrMemI:
  7976. case BO_MulAssign:
  7977. case BO_Div:
  7978. case BO_Rem:
  7979. case BO_Sub:
  7980. case BO_Shl:
  7981. case BO_Shr:
  7982. case BO_LE:
  7983. case BO_GE:
  7984. case BO_EQ:
  7985. case BO_NE:
  7986. case BO_AndAssign:
  7987. case BO_XorAssign:
  7988. case BO_OrAssign:
  7989. case BO_Assign:
  7990. case BO_AddAssign:
  7991. case BO_SubAssign:
  7992. case BO_DivAssign:
  7993. case BO_RemAssign:
  7994. case BO_ShlAssign:
  7995. case BO_ShrAssign:
  7996. case BO_Comma:
  7997. llvm_unreachable("Unexpected reduction operation");
  7998. }
  7999. }
  8000. if (Init && DeclareReductionRef.isUnset()) {
  8001. AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
  8002. /*TypeMayContainAuto=*/false);
  8003. } else if (!Init)
  8004. ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
  8005. if (RHSVD->isInvalidDecl())
  8006. continue;
  8007. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  8008. Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
  8009. << ReductionIdRange;
  8010. bool IsDecl =
  8011. !VD ||
  8012. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8013. Diag(D->getLocation(),
  8014. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8015. << D;
  8016. continue;
  8017. }
  8018. // Store initializer for single element in private copy. Will be used during
  8019. // codegen.
  8020. PrivateVD->setInit(RHSVD->getInit());
  8021. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  8022. auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
  8023. ExprResult ReductionOp;
  8024. if (DeclareReductionRef.isUsable()) {
  8025. QualType RedTy = DeclareReductionRef.get()->getType();
  8026. QualType PtrRedTy = Context.getPointerType(RedTy);
  8027. ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  8028. ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  8029. if (!BasePath.empty()) {
  8030. LHS = DefaultLvalueConversion(LHS.get());
  8031. RHS = DefaultLvalueConversion(RHS.get());
  8032. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  8033. CK_UncheckedDerivedToBase, LHS.get(),
  8034. &BasePath, LHS.get()->getValueKind());
  8035. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  8036. CK_UncheckedDerivedToBase, RHS.get(),
  8037. &BasePath, RHS.get()->getValueKind());
  8038. }
  8039. FunctionProtoType::ExtProtoInfo EPI;
  8040. QualType Params[] = {PtrRedTy, PtrRedTy};
  8041. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  8042. auto *OVE = new (Context) OpaqueValueExpr(
  8043. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  8044. DefaultLvalueConversion(DeclareReductionRef.get()).get());
  8045. Expr *Args[] = {LHS.get(), RHS.get()};
  8046. ReductionOp = new (Context)
  8047. CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  8048. } else {
  8049. ReductionOp = BuildBinOp(DSAStack->getCurScope(),
  8050. ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
  8051. if (ReductionOp.isUsable()) {
  8052. if (BOK != BO_LT && BOK != BO_GT) {
  8053. ReductionOp =
  8054. BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
  8055. BO_Assign, LHSDRE, ReductionOp.get());
  8056. } else {
  8057. auto *ConditionalOp = new (Context) ConditionalOperator(
  8058. ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
  8059. RHSDRE, Type, VK_LValue, OK_Ordinary);
  8060. ReductionOp =
  8061. BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
  8062. BO_Assign, LHSDRE, ConditionalOp);
  8063. }
  8064. ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
  8065. }
  8066. if (ReductionOp.isInvalid())
  8067. continue;
  8068. }
  8069. DeclRefExpr *Ref = nullptr;
  8070. Expr *VarsExpr = RefExpr->IgnoreParens();
  8071. if (!VD && !CurContext->isDependentContext()) {
  8072. if (ASE || OASE) {
  8073. TransformExprToCaptures RebuildToCapture(*this, D);
  8074. VarsExpr =
  8075. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  8076. Ref = RebuildToCapture.getCapturedExpr();
  8077. } else {
  8078. VarsExpr = Ref =
  8079. buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  8080. }
  8081. if (!IsOpenMPCapturedDecl(D)) {
  8082. ExprCaptures.push_back(Ref->getDecl());
  8083. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  8084. ExprResult RefRes = DefaultLvalueConversion(Ref);
  8085. if (!RefRes.isUsable())
  8086. continue;
  8087. ExprResult PostUpdateRes =
  8088. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  8089. SimpleRefExpr, RefRes.get());
  8090. if (!PostUpdateRes.isUsable())
  8091. continue;
  8092. ExprPostUpdates.push_back(
  8093. IgnoredValueConversions(PostUpdateRes.get()).get());
  8094. }
  8095. }
  8096. }
  8097. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  8098. Vars.push_back(VarsExpr);
  8099. Privates.push_back(PrivateDRE);
  8100. LHSs.push_back(LHSDRE);
  8101. RHSs.push_back(RHSDRE);
  8102. ReductionOps.push_back(ReductionOp.get());
  8103. }
  8104. if (Vars.empty())
  8105. return nullptr;
  8106. return OMPReductionClause::Create(
  8107. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
  8108. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
  8109. LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
  8110. buildPostUpdate(*this, ExprPostUpdates));
  8111. }
  8112. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  8113. SourceLocation LinLoc) {
  8114. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  8115. LinKind == OMPC_LINEAR_unknown) {
  8116. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  8117. return true;
  8118. }
  8119. return false;
  8120. }
  8121. bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
  8122. OpenMPLinearClauseKind LinKind,
  8123. QualType Type) {
  8124. auto *VD = dyn_cast_or_null<VarDecl>(D);
  8125. // A variable must not have an incomplete type or a reference type.
  8126. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  8127. return true;
  8128. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  8129. !Type->isReferenceType()) {
  8130. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  8131. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  8132. return true;
  8133. }
  8134. Type = Type.getNonReferenceType();
  8135. // A list item must not be const-qualified.
  8136. if (Type.isConstant(Context)) {
  8137. Diag(ELoc, diag::err_omp_const_variable)
  8138. << getOpenMPClauseName(OMPC_linear);
  8139. if (D) {
  8140. bool IsDecl =
  8141. !VD ||
  8142. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8143. Diag(D->getLocation(),
  8144. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8145. << D;
  8146. }
  8147. return true;
  8148. }
  8149. // A list item must be of integral or pointer type.
  8150. Type = Type.getUnqualifiedType().getCanonicalType();
  8151. const auto *Ty = Type.getTypePtrOrNull();
  8152. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  8153. !Ty->isPointerType())) {
  8154. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  8155. if (D) {
  8156. bool IsDecl =
  8157. !VD ||
  8158. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8159. Diag(D->getLocation(),
  8160. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8161. << D;
  8162. }
  8163. return true;
  8164. }
  8165. return false;
  8166. }
  8167. OMPClause *Sema::ActOnOpenMPLinearClause(
  8168. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  8169. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  8170. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  8171. SmallVector<Expr *, 8> Vars;
  8172. SmallVector<Expr *, 8> Privates;
  8173. SmallVector<Expr *, 8> Inits;
  8174. SmallVector<Decl *, 4> ExprCaptures;
  8175. SmallVector<Expr *, 4> ExprPostUpdates;
  8176. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  8177. LinKind = OMPC_LINEAR_val;
  8178. for (auto &RefExpr : VarList) {
  8179. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  8180. SourceLocation ELoc;
  8181. SourceRange ERange;
  8182. Expr *SimpleRefExpr = RefExpr;
  8183. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  8184. /*AllowArraySection=*/false);
  8185. if (Res.second) {
  8186. // It will be analyzed later.
  8187. Vars.push_back(RefExpr);
  8188. Privates.push_back(nullptr);
  8189. Inits.push_back(nullptr);
  8190. }
  8191. ValueDecl *D = Res.first;
  8192. if (!D)
  8193. continue;
  8194. QualType Type = D->getType();
  8195. auto *VD = dyn_cast<VarDecl>(D);
  8196. // OpenMP [2.14.3.7, linear clause]
  8197. // A list-item cannot appear in more than one linear clause.
  8198. // A list-item that appears in a linear clause cannot appear in any
  8199. // other data-sharing attribute clause.
  8200. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8201. if (DVar.RefExpr) {
  8202. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  8203. << getOpenMPClauseName(OMPC_linear);
  8204. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8205. continue;
  8206. }
  8207. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  8208. continue;
  8209. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  8210. // Build private copy of original var.
  8211. auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
  8212. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8213. auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  8214. // Build var to save initial value.
  8215. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  8216. Expr *InitExpr;
  8217. DeclRefExpr *Ref = nullptr;
  8218. if (!VD && !CurContext->isDependentContext()) {
  8219. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  8220. if (!IsOpenMPCapturedDecl(D)) {
  8221. ExprCaptures.push_back(Ref->getDecl());
  8222. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  8223. ExprResult RefRes = DefaultLvalueConversion(Ref);
  8224. if (!RefRes.isUsable())
  8225. continue;
  8226. ExprResult PostUpdateRes =
  8227. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  8228. SimpleRefExpr, RefRes.get());
  8229. if (!PostUpdateRes.isUsable())
  8230. continue;
  8231. ExprPostUpdates.push_back(
  8232. IgnoredValueConversions(PostUpdateRes.get()).get());
  8233. }
  8234. }
  8235. }
  8236. if (LinKind == OMPC_LINEAR_uval)
  8237. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  8238. else
  8239. InitExpr = VD ? SimpleRefExpr : Ref;
  8240. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  8241. /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
  8242. auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  8243. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  8244. Vars.push_back((VD || CurContext->isDependentContext())
  8245. ? RefExpr->IgnoreParens()
  8246. : Ref);
  8247. Privates.push_back(PrivateRef);
  8248. Inits.push_back(InitRef);
  8249. }
  8250. if (Vars.empty())
  8251. return nullptr;
  8252. Expr *StepExpr = Step;
  8253. Expr *CalcStepExpr = nullptr;
  8254. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  8255. !Step->isInstantiationDependent() &&
  8256. !Step->containsUnexpandedParameterPack()) {
  8257. SourceLocation StepLoc = Step->getLocStart();
  8258. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  8259. if (Val.isInvalid())
  8260. return nullptr;
  8261. StepExpr = Val.get();
  8262. // Build var to save the step value.
  8263. VarDecl *SaveVar =
  8264. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  8265. ExprResult SaveRef =
  8266. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  8267. ExprResult CalcStep =
  8268. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  8269. CalcStep = ActOnFinishFullExpr(CalcStep.get());
  8270. // Warn about zero linear step (it would be probably better specified as
  8271. // making corresponding variables 'const').
  8272. llvm::APSInt Result;
  8273. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  8274. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  8275. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  8276. << (Vars.size() > 1);
  8277. if (!IsConstant && CalcStep.isUsable()) {
  8278. // Calculate the step beforehand instead of doing this on each iteration.
  8279. // (This is not used if the number of iterations may be kfold-ed).
  8280. CalcStepExpr = CalcStep.get();
  8281. }
  8282. }
  8283. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  8284. ColonLoc, EndLoc, Vars, Privates, Inits,
  8285. StepExpr, CalcStepExpr,
  8286. buildPreInits(Context, ExprCaptures),
  8287. buildPostUpdate(*this, ExprPostUpdates));
  8288. }
  8289. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  8290. Expr *NumIterations, Sema &SemaRef,
  8291. Scope *S, DSAStackTy *Stack) {
  8292. // Walk the vars and build update/final expressions for the CodeGen.
  8293. SmallVector<Expr *, 8> Updates;
  8294. SmallVector<Expr *, 8> Finals;
  8295. Expr *Step = Clause.getStep();
  8296. Expr *CalcStep = Clause.getCalcStep();
  8297. // OpenMP [2.14.3.7, linear clause]
  8298. // If linear-step is not specified it is assumed to be 1.
  8299. if (Step == nullptr)
  8300. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  8301. else if (CalcStep) {
  8302. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  8303. }
  8304. bool HasErrors = false;
  8305. auto CurInit = Clause.inits().begin();
  8306. auto CurPrivate = Clause.privates().begin();
  8307. auto LinKind = Clause.getModifier();
  8308. for (auto &RefExpr : Clause.varlists()) {
  8309. SourceLocation ELoc;
  8310. SourceRange ERange;
  8311. Expr *SimpleRefExpr = RefExpr;
  8312. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
  8313. /*AllowArraySection=*/false);
  8314. ValueDecl *D = Res.first;
  8315. if (Res.second || !D) {
  8316. Updates.push_back(nullptr);
  8317. Finals.push_back(nullptr);
  8318. HasErrors = true;
  8319. continue;
  8320. }
  8321. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
  8322. D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
  8323. ->getMemberDecl();
  8324. }
  8325. auto &&Info = Stack->isLoopControlVariable(D);
  8326. Expr *InitExpr = *CurInit;
  8327. // Build privatized reference to the current linear var.
  8328. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  8329. Expr *CapturedRef;
  8330. if (LinKind == OMPC_LINEAR_uval)
  8331. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  8332. else
  8333. CapturedRef =
  8334. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  8335. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  8336. /*RefersToCapture=*/true);
  8337. // Build update: Var = InitExpr + IV * Step
  8338. ExprResult Update;
  8339. if (!Info.first) {
  8340. Update =
  8341. BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  8342. InitExpr, IV, Step, /* Subtract */ false);
  8343. } else
  8344. Update = *CurPrivate;
  8345. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
  8346. /*DiscardedValue=*/true);
  8347. // Build final: Var = InitExpr + NumIterations * Step
  8348. ExprResult Final;
  8349. if (!Info.first) {
  8350. Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  8351. InitExpr, NumIterations, Step,
  8352. /* Subtract */ false);
  8353. } else
  8354. Final = *CurPrivate;
  8355. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
  8356. /*DiscardedValue=*/true);
  8357. if (!Update.isUsable() || !Final.isUsable()) {
  8358. Updates.push_back(nullptr);
  8359. Finals.push_back(nullptr);
  8360. HasErrors = true;
  8361. } else {
  8362. Updates.push_back(Update.get());
  8363. Finals.push_back(Final.get());
  8364. }
  8365. ++CurInit;
  8366. ++CurPrivate;
  8367. }
  8368. Clause.setUpdates(Updates);
  8369. Clause.setFinals(Finals);
  8370. return HasErrors;
  8371. }
  8372. OMPClause *Sema::ActOnOpenMPAlignedClause(
  8373. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  8374. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  8375. SmallVector<Expr *, 8> Vars;
  8376. for (auto &RefExpr : VarList) {
  8377. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  8378. SourceLocation ELoc;
  8379. SourceRange ERange;
  8380. Expr *SimpleRefExpr = RefExpr;
  8381. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  8382. /*AllowArraySection=*/false);
  8383. if (Res.second) {
  8384. // It will be analyzed later.
  8385. Vars.push_back(RefExpr);
  8386. }
  8387. ValueDecl *D = Res.first;
  8388. if (!D)
  8389. continue;
  8390. QualType QType = D->getType();
  8391. auto *VD = dyn_cast<VarDecl>(D);
  8392. // OpenMP [2.8.1, simd construct, Restrictions]
  8393. // The type of list items appearing in the aligned clause must be
  8394. // array, pointer, reference to array, or reference to pointer.
  8395. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  8396. const Type *Ty = QType.getTypePtrOrNull();
  8397. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  8398. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  8399. << QType << getLangOpts().CPlusPlus << ERange;
  8400. bool IsDecl =
  8401. !VD ||
  8402. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8403. Diag(D->getLocation(),
  8404. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8405. << D;
  8406. continue;
  8407. }
  8408. // OpenMP [2.8.1, simd construct, Restrictions]
  8409. // A list-item cannot appear in more than one aligned clause.
  8410. if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  8411. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  8412. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  8413. << getOpenMPClauseName(OMPC_aligned);
  8414. continue;
  8415. }
  8416. DeclRefExpr *Ref = nullptr;
  8417. if (!VD && IsOpenMPCapturedDecl(D))
  8418. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  8419. Vars.push_back(DefaultFunctionArrayConversion(
  8420. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  8421. .get());
  8422. }
  8423. // OpenMP [2.8.1, simd construct, Description]
  8424. // The parameter of the aligned clause, alignment, must be a constant
  8425. // positive integer expression.
  8426. // If no optional parameter is specified, implementation-defined default
  8427. // alignments for SIMD instructions on the target platforms are assumed.
  8428. if (Alignment != nullptr) {
  8429. ExprResult AlignResult =
  8430. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  8431. if (AlignResult.isInvalid())
  8432. return nullptr;
  8433. Alignment = AlignResult.get();
  8434. }
  8435. if (Vars.empty())
  8436. return nullptr;
  8437. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  8438. EndLoc, Vars, Alignment);
  8439. }
  8440. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  8441. SourceLocation StartLoc,
  8442. SourceLocation LParenLoc,
  8443. SourceLocation EndLoc) {
  8444. SmallVector<Expr *, 8> Vars;
  8445. SmallVector<Expr *, 8> SrcExprs;
  8446. SmallVector<Expr *, 8> DstExprs;
  8447. SmallVector<Expr *, 8> AssignmentOps;
  8448. for (auto &RefExpr : VarList) {
  8449. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  8450. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  8451. // It will be analyzed later.
  8452. Vars.push_back(RefExpr);
  8453. SrcExprs.push_back(nullptr);
  8454. DstExprs.push_back(nullptr);
  8455. AssignmentOps.push_back(nullptr);
  8456. continue;
  8457. }
  8458. SourceLocation ELoc = RefExpr->getExprLoc();
  8459. // OpenMP [2.1, C/C++]
  8460. // A list item is a variable name.
  8461. // OpenMP [2.14.4.1, Restrictions, p.1]
  8462. // A list item that appears in a copyin clause must be threadprivate.
  8463. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  8464. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  8465. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  8466. << 0 << RefExpr->getSourceRange();
  8467. continue;
  8468. }
  8469. Decl *D = DE->getDecl();
  8470. VarDecl *VD = cast<VarDecl>(D);
  8471. QualType Type = VD->getType();
  8472. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  8473. // It will be analyzed later.
  8474. Vars.push_back(DE);
  8475. SrcExprs.push_back(nullptr);
  8476. DstExprs.push_back(nullptr);
  8477. AssignmentOps.push_back(nullptr);
  8478. continue;
  8479. }
  8480. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  8481. // A list item that appears in a copyin clause must be threadprivate.
  8482. if (!DSAStack->isThreadPrivate(VD)) {
  8483. Diag(ELoc, diag::err_omp_required_access)
  8484. << getOpenMPClauseName(OMPC_copyin)
  8485. << getOpenMPDirectiveName(OMPD_threadprivate);
  8486. continue;
  8487. }
  8488. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  8489. // A variable of class type (or array thereof) that appears in a
  8490. // copyin clause requires an accessible, unambiguous copy assignment
  8491. // operator for the class type.
  8492. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  8493. auto *SrcVD =
  8494. buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
  8495. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  8496. auto *PseudoSrcExpr = buildDeclRefExpr(
  8497. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  8498. auto *DstVD =
  8499. buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
  8500. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  8501. auto *PseudoDstExpr =
  8502. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  8503. // For arrays generate assignment operation for single element and replace
  8504. // it by the original array element in CodeGen.
  8505. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  8506. PseudoDstExpr, PseudoSrcExpr);
  8507. if (AssignmentOp.isInvalid())
  8508. continue;
  8509. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  8510. /*DiscardedValue=*/true);
  8511. if (AssignmentOp.isInvalid())
  8512. continue;
  8513. DSAStack->addDSA(VD, DE, OMPC_copyin);
  8514. Vars.push_back(DE);
  8515. SrcExprs.push_back(PseudoSrcExpr);
  8516. DstExprs.push_back(PseudoDstExpr);
  8517. AssignmentOps.push_back(AssignmentOp.get());
  8518. }
  8519. if (Vars.empty())
  8520. return nullptr;
  8521. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  8522. SrcExprs, DstExprs, AssignmentOps);
  8523. }
  8524. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  8525. SourceLocation StartLoc,
  8526. SourceLocation LParenLoc,
  8527. SourceLocation EndLoc) {
  8528. SmallVector<Expr *, 8> Vars;
  8529. SmallVector<Expr *, 8> SrcExprs;
  8530. SmallVector<Expr *, 8> DstExprs;
  8531. SmallVector<Expr *, 8> AssignmentOps;
  8532. for (auto &RefExpr : VarList) {
  8533. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  8534. SourceLocation ELoc;
  8535. SourceRange ERange;
  8536. Expr *SimpleRefExpr = RefExpr;
  8537. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  8538. /*AllowArraySection=*/false);
  8539. if (Res.second) {
  8540. // It will be analyzed later.
  8541. Vars.push_back(RefExpr);
  8542. SrcExprs.push_back(nullptr);
  8543. DstExprs.push_back(nullptr);
  8544. AssignmentOps.push_back(nullptr);
  8545. }
  8546. ValueDecl *D = Res.first;
  8547. if (!D)
  8548. continue;
  8549. QualType Type = D->getType();
  8550. auto *VD = dyn_cast<VarDecl>(D);
  8551. // OpenMP [2.14.4.2, Restrictions, p.2]
  8552. // A list item that appears in a copyprivate clause may not appear in a
  8553. // private or firstprivate clause on the single construct.
  8554. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  8555. auto DVar = DSAStack->getTopDSA(D, false);
  8556. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  8557. DVar.RefExpr) {
  8558. Diag(ELoc, diag::err_omp_wrong_dsa)
  8559. << getOpenMPClauseName(DVar.CKind)
  8560. << getOpenMPClauseName(OMPC_copyprivate);
  8561. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8562. continue;
  8563. }
  8564. // OpenMP [2.11.4.2, Restrictions, p.1]
  8565. // All list items that appear in a copyprivate clause must be either
  8566. // threadprivate or private in the enclosing context.
  8567. if (DVar.CKind == OMPC_unknown) {
  8568. DVar = DSAStack->getImplicitDSA(D, false);
  8569. if (DVar.CKind == OMPC_shared) {
  8570. Diag(ELoc, diag::err_omp_required_access)
  8571. << getOpenMPClauseName(OMPC_copyprivate)
  8572. << "threadprivate or private in the enclosing context";
  8573. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8574. continue;
  8575. }
  8576. }
  8577. }
  8578. // Variably modified types are not supported.
  8579. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  8580. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  8581. << getOpenMPClauseName(OMPC_copyprivate) << Type
  8582. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  8583. bool IsDecl =
  8584. !VD ||
  8585. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8586. Diag(D->getLocation(),
  8587. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8588. << D;
  8589. continue;
  8590. }
  8591. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  8592. // A variable of class type (or array thereof) that appears in a
  8593. // copyin clause requires an accessible, unambiguous copy assignment
  8594. // operator for the class type.
  8595. Type = Context.getBaseElementType(Type.getNonReferenceType())
  8596. .getUnqualifiedType();
  8597. auto *SrcVD =
  8598. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
  8599. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8600. auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  8601. auto *DstVD =
  8602. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
  8603. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8604. auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  8605. auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  8606. PseudoDstExpr, PseudoSrcExpr);
  8607. if (AssignmentOp.isInvalid())
  8608. continue;
  8609. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  8610. /*DiscardedValue=*/true);
  8611. if (AssignmentOp.isInvalid())
  8612. continue;
  8613. // No need to mark vars as copyprivate, they are already threadprivate or
  8614. // implicitly private.
  8615. assert(VD || IsOpenMPCapturedDecl(D));
  8616. Vars.push_back(
  8617. VD ? RefExpr->IgnoreParens()
  8618. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  8619. SrcExprs.push_back(PseudoSrcExpr);
  8620. DstExprs.push_back(PseudoDstExpr);
  8621. AssignmentOps.push_back(AssignmentOp.get());
  8622. }
  8623. if (Vars.empty())
  8624. return nullptr;
  8625. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  8626. Vars, SrcExprs, DstExprs, AssignmentOps);
  8627. }
  8628. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  8629. SourceLocation StartLoc,
  8630. SourceLocation LParenLoc,
  8631. SourceLocation EndLoc) {
  8632. if (VarList.empty())
  8633. return nullptr;
  8634. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  8635. }
  8636. OMPClause *
  8637. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  8638. SourceLocation DepLoc, SourceLocation ColonLoc,
  8639. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  8640. SourceLocation LParenLoc, SourceLocation EndLoc) {
  8641. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  8642. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  8643. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  8644. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  8645. return nullptr;
  8646. }
  8647. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  8648. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  8649. DepKind == OMPC_DEPEND_sink)) {
  8650. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  8651. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  8652. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  8653. /*Last=*/OMPC_DEPEND_unknown, Except)
  8654. << getOpenMPClauseName(OMPC_depend);
  8655. return nullptr;
  8656. }
  8657. SmallVector<Expr *, 8> Vars;
  8658. DSAStackTy::OperatorOffsetTy OpsOffs;
  8659. llvm::APSInt DepCounter(/*BitWidth=*/32);
  8660. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  8661. if (DepKind == OMPC_DEPEND_sink) {
  8662. if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
  8663. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  8664. TotalDepCount.setIsUnsigned(/*Val=*/true);
  8665. }
  8666. }
  8667. if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
  8668. DSAStack->getParentOrderedRegionParam()) {
  8669. for (auto &RefExpr : VarList) {
  8670. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  8671. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  8672. // It will be analyzed later.
  8673. Vars.push_back(RefExpr);
  8674. continue;
  8675. }
  8676. SourceLocation ELoc = RefExpr->getExprLoc();
  8677. auto *SimpleExpr = RefExpr->IgnoreParenCasts();
  8678. if (DepKind == OMPC_DEPEND_sink) {
  8679. if (DepCounter >= TotalDepCount) {
  8680. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  8681. continue;
  8682. }
  8683. ++DepCounter;
  8684. // OpenMP [2.13.9, Summary]
  8685. // depend(dependence-type : vec), where dependence-type is:
  8686. // 'sink' and where vec is the iteration vector, which has the form:
  8687. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  8688. // where n is the value specified by the ordered clause in the loop
  8689. // directive, xi denotes the loop iteration variable of the i-th nested
  8690. // loop associated with the loop directive, and di is a constant
  8691. // non-negative integer.
  8692. if (CurContext->isDependentContext()) {
  8693. // It will be analyzed later.
  8694. Vars.push_back(RefExpr);
  8695. continue;
  8696. }
  8697. SimpleExpr = SimpleExpr->IgnoreImplicit();
  8698. OverloadedOperatorKind OOK = OO_None;
  8699. SourceLocation OOLoc;
  8700. Expr *LHS = SimpleExpr;
  8701. Expr *RHS = nullptr;
  8702. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  8703. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  8704. OOLoc = BO->getOperatorLoc();
  8705. LHS = BO->getLHS()->IgnoreParenImpCasts();
  8706. RHS = BO->getRHS()->IgnoreParenImpCasts();
  8707. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  8708. OOK = OCE->getOperator();
  8709. OOLoc = OCE->getOperatorLoc();
  8710. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  8711. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  8712. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  8713. OOK = MCE->getMethodDecl()
  8714. ->getNameInfo()
  8715. .getName()
  8716. .getCXXOverloadedOperator();
  8717. OOLoc = MCE->getCallee()->getExprLoc();
  8718. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  8719. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  8720. }
  8721. SourceLocation ELoc;
  8722. SourceRange ERange;
  8723. auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
  8724. /*AllowArraySection=*/false);
  8725. if (Res.second) {
  8726. // It will be analyzed later.
  8727. Vars.push_back(RefExpr);
  8728. }
  8729. ValueDecl *D = Res.first;
  8730. if (!D)
  8731. continue;
  8732. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  8733. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  8734. continue;
  8735. }
  8736. if (RHS) {
  8737. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  8738. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  8739. if (RHSRes.isInvalid())
  8740. continue;
  8741. }
  8742. if (!CurContext->isDependentContext() &&
  8743. DSAStack->getParentOrderedRegionParam() &&
  8744. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  8745. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  8746. << DSAStack->getParentLoopControlVariable(
  8747. DepCounter.getZExtValue());
  8748. continue;
  8749. }
  8750. OpsOffs.push_back({RHS, OOK});
  8751. } else {
  8752. // OpenMP [2.11.1.1, Restrictions, p.3]
  8753. // A variable that is part of another variable (such as a field of a
  8754. // structure) but is not an array element or an array section cannot
  8755. // appear in a depend clause.
  8756. auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
  8757. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  8758. auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
  8759. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  8760. (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
  8761. (ASE &&
  8762. !ASE->getBase()
  8763. ->getType()
  8764. .getNonReferenceType()
  8765. ->isPointerType() &&
  8766. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  8767. Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
  8768. << 0 << RefExpr->getSourceRange();
  8769. continue;
  8770. }
  8771. }
  8772. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  8773. }
  8774. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  8775. TotalDepCount > VarList.size() &&
  8776. DSAStack->getParentOrderedRegionParam()) {
  8777. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  8778. << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  8779. }
  8780. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  8781. Vars.empty())
  8782. return nullptr;
  8783. }
  8784. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  8785. DepKind, DepLoc, ColonLoc, Vars);
  8786. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
  8787. DSAStack->addDoacrossDependClause(C, OpsOffs);
  8788. return C;
  8789. }
  8790. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  8791. SourceLocation LParenLoc,
  8792. SourceLocation EndLoc) {
  8793. Expr *ValExpr = Device;
  8794. // OpenMP [2.9.1, Restrictions]
  8795. // The device expression must evaluate to a non-negative integer value.
  8796. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  8797. /*StrictlyPositive=*/false))
  8798. return nullptr;
  8799. return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  8800. }
  8801. static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
  8802. DSAStackTy *Stack, CXXRecordDecl *RD) {
  8803. if (!RD || RD->isInvalidDecl())
  8804. return true;
  8805. auto QTy = SemaRef.Context.getRecordType(RD);
  8806. if (RD->isDynamicClass()) {
  8807. SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
  8808. SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
  8809. return false;
  8810. }
  8811. auto *DC = RD;
  8812. bool IsCorrect = true;
  8813. for (auto *I : DC->decls()) {
  8814. if (I) {
  8815. if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
  8816. if (MD->isStatic()) {
  8817. SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
  8818. SemaRef.Diag(MD->getLocation(),
  8819. diag::note_omp_static_member_in_target);
  8820. IsCorrect = false;
  8821. }
  8822. } else if (auto *VD = dyn_cast<VarDecl>(I)) {
  8823. if (VD->isStaticDataMember()) {
  8824. SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
  8825. SemaRef.Diag(VD->getLocation(),
  8826. diag::note_omp_static_member_in_target);
  8827. IsCorrect = false;
  8828. }
  8829. }
  8830. }
  8831. }
  8832. for (auto &I : RD->bases()) {
  8833. if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
  8834. I.getType()->getAsCXXRecordDecl()))
  8835. IsCorrect = false;
  8836. }
  8837. return IsCorrect;
  8838. }
  8839. static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  8840. DSAStackTy *Stack, QualType QTy) {
  8841. NamedDecl *ND;
  8842. if (QTy->isIncompleteType(&ND)) {
  8843. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  8844. return false;
  8845. } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
  8846. if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
  8847. return false;
  8848. }
  8849. return true;
  8850. }
  8851. /// \brief Return true if it can be proven that the provided array expression
  8852. /// (array section or array subscript) does NOT specify the whole size of the
  8853. /// array whose base type is \a BaseQTy.
  8854. static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  8855. const Expr *E,
  8856. QualType BaseQTy) {
  8857. auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  8858. // If this is an array subscript, it refers to the whole size if the size of
  8859. // the dimension is constant and equals 1. Also, an array section assumes the
  8860. // format of an array subscript if no colon is used.
  8861. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  8862. if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  8863. return ATy->getSize().getSExtValue() != 1;
  8864. // Size can't be evaluated statically.
  8865. return false;
  8866. }
  8867. assert(OASE && "Expecting array section if not an array subscript.");
  8868. auto *LowerBound = OASE->getLowerBound();
  8869. auto *Length = OASE->getLength();
  8870. // If there is a lower bound that does not evaluates to zero, we are not
  8871. // covering the whole dimension.
  8872. if (LowerBound) {
  8873. llvm::APSInt ConstLowerBound;
  8874. if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
  8875. return false; // Can't get the integer value as a constant.
  8876. if (ConstLowerBound.getSExtValue())
  8877. return true;
  8878. }
  8879. // If we don't have a length we covering the whole dimension.
  8880. if (!Length)
  8881. return false;
  8882. // If the base is a pointer, we don't have a way to get the size of the
  8883. // pointee.
  8884. if (BaseQTy->isPointerType())
  8885. return false;
  8886. // We can only check if the length is the same as the size of the dimension
  8887. // if we have a constant array.
  8888. auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  8889. if (!CATy)
  8890. return false;
  8891. llvm::APSInt ConstLength;
  8892. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  8893. return false; // Can't get the integer value as a constant.
  8894. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  8895. }
  8896. // Return true if it can be proven that the provided array expression (array
  8897. // section or array subscript) does NOT specify a single element of the array
  8898. // whose base type is \a BaseQTy.
  8899. static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  8900. const Expr *E,
  8901. QualType BaseQTy) {
  8902. auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  8903. // An array subscript always refer to a single element. Also, an array section
  8904. // assumes the format of an array subscript if no colon is used.
  8905. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  8906. return false;
  8907. assert(OASE && "Expecting array section if not an array subscript.");
  8908. auto *Length = OASE->getLength();
  8909. // If we don't have a length we have to check if the array has unitary size
  8910. // for this dimension. Also, we should always expect a length if the base type
  8911. // is pointer.
  8912. if (!Length) {
  8913. if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  8914. return ATy->getSize().getSExtValue() != 1;
  8915. // We cannot assume anything.
  8916. return false;
  8917. }
  8918. // Check if the length evaluates to 1.
  8919. llvm::APSInt ConstLength;
  8920. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  8921. return false; // Can't get the integer value as a constant.
  8922. return ConstLength.getSExtValue() != 1;
  8923. }
  8924. // Return the expression of the base of the mappable expression or null if it
  8925. // cannot be determined and do all the necessary checks to see if the expression
  8926. // is valid as a standalone mappable expression. In the process, record all the
  8927. // components of the expression.
  8928. static Expr *CheckMapClauseExpressionBase(
  8929. Sema &SemaRef, Expr *E,
  8930. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  8931. OpenMPClauseKind CKind) {
  8932. SourceLocation ELoc = E->getExprLoc();
  8933. SourceRange ERange = E->getSourceRange();
  8934. // The base of elements of list in a map clause have to be either:
  8935. // - a reference to variable or field.
  8936. // - a member expression.
  8937. // - an array expression.
  8938. //
  8939. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  8940. // reference to 'r'.
  8941. //
  8942. // If we have:
  8943. //
  8944. // struct SS {
  8945. // Bla S;
  8946. // foo() {
  8947. // #pragma omp target map (S.Arr[:12]);
  8948. // }
  8949. // }
  8950. //
  8951. // We want to retrieve the member expression 'this->S';
  8952. Expr *RelevantExpr = nullptr;
  8953. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  8954. // If a list item is an array section, it must specify contiguous storage.
  8955. //
  8956. // For this restriction it is sufficient that we make sure only references
  8957. // to variables or fields and array expressions, and that no array sections
  8958. // exist except in the rightmost expression (unless they cover the whole
  8959. // dimension of the array). E.g. these would be invalid:
  8960. //
  8961. // r.ArrS[3:5].Arr[6:7]
  8962. //
  8963. // r.ArrS[3:5].x
  8964. //
  8965. // but these would be valid:
  8966. // r.ArrS[3].Arr[6:7]
  8967. //
  8968. // r.ArrS[3].x
  8969. bool AllowUnitySizeArraySection = true;
  8970. bool AllowWholeSizeArraySection = true;
  8971. while (!RelevantExpr) {
  8972. E = E->IgnoreParenImpCasts();
  8973. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  8974. if (!isa<VarDecl>(CurE->getDecl()))
  8975. break;
  8976. RelevantExpr = CurE;
  8977. // If we got a reference to a declaration, we should not expect any array
  8978. // section before that.
  8979. AllowUnitySizeArraySection = false;
  8980. AllowWholeSizeArraySection = false;
  8981. // Record the component.
  8982. CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
  8983. CurE, CurE->getDecl()));
  8984. continue;
  8985. }
  8986. if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  8987. auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  8988. if (isa<CXXThisExpr>(BaseE))
  8989. // We found a base expression: this->Val.
  8990. RelevantExpr = CurE;
  8991. else
  8992. E = BaseE;
  8993. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  8994. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  8995. << CurE->getSourceRange();
  8996. break;
  8997. }
  8998. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  8999. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  9000. // A bit-field cannot appear in a map clause.
  9001. //
  9002. if (FD->isBitField()) {
  9003. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  9004. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  9005. break;
  9006. }
  9007. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  9008. // If the type of a list item is a reference to a type T then the type
  9009. // will be considered to be T for all purposes of this clause.
  9010. QualType CurType = BaseE->getType().getNonReferenceType();
  9011. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  9012. // A list item cannot be a variable that is a member of a structure with
  9013. // a union type.
  9014. //
  9015. if (auto *RT = CurType->getAs<RecordType>())
  9016. if (RT->isUnionType()) {
  9017. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  9018. << CurE->getSourceRange();
  9019. break;
  9020. }
  9021. // If we got a member expression, we should not expect any array section
  9022. // before that:
  9023. //
  9024. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  9025. // If a list item is an element of a structure, only the rightmost symbol
  9026. // of the variable reference can be an array section.
  9027. //
  9028. AllowUnitySizeArraySection = false;
  9029. AllowWholeSizeArraySection = false;
  9030. // Record the component.
  9031. CurComponents.push_back(
  9032. OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
  9033. continue;
  9034. }
  9035. if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  9036. E = CurE->getBase()->IgnoreParenImpCasts();
  9037. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  9038. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  9039. << 0 << CurE->getSourceRange();
  9040. break;
  9041. }
  9042. // If we got an array subscript that express the whole dimension we
  9043. // can have any array expressions before. If it only expressing part of
  9044. // the dimension, we can only have unitary-size array expressions.
  9045. if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  9046. E->getType()))
  9047. AllowWholeSizeArraySection = false;
  9048. // Record the component - we don't have any declaration associated.
  9049. CurComponents.push_back(
  9050. OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
  9051. continue;
  9052. }
  9053. if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  9054. E = CurE->getBase()->IgnoreParenImpCasts();
  9055. auto CurType =
  9056. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  9057. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  9058. // If the type of a list item is a reference to a type T then the type
  9059. // will be considered to be T for all purposes of this clause.
  9060. if (CurType->isReferenceType())
  9061. CurType = CurType->getPointeeType();
  9062. bool IsPointer = CurType->isAnyPointerType();
  9063. if (!IsPointer && !CurType->isArrayType()) {
  9064. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  9065. << 0 << CurE->getSourceRange();
  9066. break;
  9067. }
  9068. bool NotWhole =
  9069. CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  9070. bool NotUnity =
  9071. CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  9072. if (AllowWholeSizeArraySection) {
  9073. // Any array section is currently allowed. Allowing a whole size array
  9074. // section implies allowing a unity array section as well.
  9075. //
  9076. // If this array section refers to the whole dimension we can still
  9077. // accept other array sections before this one, except if the base is a
  9078. // pointer. Otherwise, only unitary sections are accepted.
  9079. if (NotWhole || IsPointer)
  9080. AllowWholeSizeArraySection = false;
  9081. } else if (AllowUnitySizeArraySection && NotUnity) {
  9082. // A unity or whole array section is not allowed and that is not
  9083. // compatible with the properties of the current array section.
  9084. SemaRef.Diag(
  9085. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  9086. << CurE->getSourceRange();
  9087. break;
  9088. }
  9089. // Record the component - we don't have any declaration associated.
  9090. CurComponents.push_back(
  9091. OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
  9092. continue;
  9093. }
  9094. // If nothing else worked, this is not a valid map clause expression.
  9095. SemaRef.Diag(ELoc,
  9096. diag::err_omp_expected_named_var_member_or_array_expression)
  9097. << ERange;
  9098. break;
  9099. }
  9100. return RelevantExpr;
  9101. }
  9102. // Return true if expression E associated with value VD has conflicts with other
  9103. // map information.
  9104. static bool CheckMapConflicts(
  9105. Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
  9106. bool CurrentRegionOnly,
  9107. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  9108. OpenMPClauseKind CKind) {
  9109. assert(VD && E);
  9110. SourceLocation ELoc = E->getExprLoc();
  9111. SourceRange ERange = E->getSourceRange();
  9112. // In order to easily check the conflicts we need to match each component of
  9113. // the expression under test with the components of the expressions that are
  9114. // already in the stack.
  9115. assert(!CurComponents.empty() && "Map clause expression with no components!");
  9116. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  9117. "Map clause expression with unexpected base!");
  9118. // Variables to help detecting enclosing problems in data environment nests.
  9119. bool IsEnclosedByDataEnvironmentExpr = false;
  9120. const Expr *EnclosingExpr = nullptr;
  9121. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  9122. VD, CurrentRegionOnly,
  9123. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
  9124. StackComponents,
  9125. OpenMPClauseKind) -> bool {
  9126. assert(!StackComponents.empty() &&
  9127. "Map clause expression with no components!");
  9128. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  9129. "Map clause expression with unexpected base!");
  9130. // The whole expression in the stack.
  9131. auto *RE = StackComponents.front().getAssociatedExpression();
  9132. // Expressions must start from the same base. Here we detect at which
  9133. // point both expressions diverge from each other and see if we can
  9134. // detect if the memory referred to both expressions is contiguous and
  9135. // do not overlap.
  9136. auto CI = CurComponents.rbegin();
  9137. auto CE = CurComponents.rend();
  9138. auto SI = StackComponents.rbegin();
  9139. auto SE = StackComponents.rend();
  9140. for (; CI != CE && SI != SE; ++CI, ++SI) {
  9141. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  9142. // At most one list item can be an array item derived from a given
  9143. // variable in map clauses of the same construct.
  9144. if (CurrentRegionOnly &&
  9145. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  9146. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  9147. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  9148. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  9149. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  9150. diag::err_omp_multiple_array_items_in_map_clause)
  9151. << CI->getAssociatedExpression()->getSourceRange();
  9152. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  9153. diag::note_used_here)
  9154. << SI->getAssociatedExpression()->getSourceRange();
  9155. return true;
  9156. }
  9157. // Do both expressions have the same kind?
  9158. if (CI->getAssociatedExpression()->getStmtClass() !=
  9159. SI->getAssociatedExpression()->getStmtClass())
  9160. break;
  9161. // Are we dealing with different variables/fields?
  9162. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  9163. break;
  9164. }
  9165. // Check if the extra components of the expressions in the enclosing
  9166. // data environment are redundant for the current base declaration.
  9167. // If they are, the maps completely overlap, which is legal.
  9168. for (; SI != SE; ++SI) {
  9169. QualType Type;
  9170. if (auto *ASE =
  9171. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  9172. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  9173. } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
  9174. SI->getAssociatedExpression())) {
  9175. auto *E = OASE->getBase()->IgnoreParenImpCasts();
  9176. Type =
  9177. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  9178. }
  9179. if (Type.isNull() || Type->isAnyPointerType() ||
  9180. CheckArrayExpressionDoesNotReferToWholeSize(
  9181. SemaRef, SI->getAssociatedExpression(), Type))
  9182. break;
  9183. }
  9184. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  9185. // List items of map clauses in the same construct must not share
  9186. // original storage.
  9187. //
  9188. // If the expressions are exactly the same or one is a subset of the
  9189. // other, it means they are sharing storage.
  9190. if (CI == CE && SI == SE) {
  9191. if (CurrentRegionOnly) {
  9192. if (CKind == OMPC_map)
  9193. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  9194. else {
  9195. assert(CKind == OMPC_to || CKind == OMPC_from);
  9196. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  9197. << ERange;
  9198. }
  9199. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  9200. << RE->getSourceRange();
  9201. return true;
  9202. } else {
  9203. // If we find the same expression in the enclosing data environment,
  9204. // that is legal.
  9205. IsEnclosedByDataEnvironmentExpr = true;
  9206. return false;
  9207. }
  9208. }
  9209. QualType DerivedType =
  9210. std::prev(CI)->getAssociatedDeclaration()->getType();
  9211. SourceLocation DerivedLoc =
  9212. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  9213. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  9214. // If the type of a list item is a reference to a type T then the type
  9215. // will be considered to be T for all purposes of this clause.
  9216. DerivedType = DerivedType.getNonReferenceType();
  9217. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  9218. // A variable for which the type is pointer and an array section
  9219. // derived from that variable must not appear as list items of map
  9220. // clauses of the same construct.
  9221. //
  9222. // Also, cover one of the cases in:
  9223. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  9224. // If any part of the original storage of a list item has corresponding
  9225. // storage in the device data environment, all of the original storage
  9226. // must have corresponding storage in the device data environment.
  9227. //
  9228. if (DerivedType->isAnyPointerType()) {
  9229. if (CI == CE || SI == SE) {
  9230. SemaRef.Diag(
  9231. DerivedLoc,
  9232. diag::err_omp_pointer_mapped_along_with_derived_section)
  9233. << DerivedLoc;
  9234. } else {
  9235. assert(CI != CE && SI != SE);
  9236. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
  9237. << DerivedLoc;
  9238. }
  9239. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  9240. << RE->getSourceRange();
  9241. return true;
  9242. }
  9243. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  9244. // List items of map clauses in the same construct must not share
  9245. // original storage.
  9246. //
  9247. // An expression is a subset of the other.
  9248. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  9249. if (CKind == OMPC_map)
  9250. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  9251. else {
  9252. assert(CKind == OMPC_to || CKind == OMPC_from);
  9253. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  9254. << ERange;
  9255. }
  9256. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  9257. << RE->getSourceRange();
  9258. return true;
  9259. }
  9260. // The current expression uses the same base as other expression in the
  9261. // data environment but does not contain it completely.
  9262. if (!CurrentRegionOnly && SI != SE)
  9263. EnclosingExpr = RE;
  9264. // The current expression is a subset of the expression in the data
  9265. // environment.
  9266. IsEnclosedByDataEnvironmentExpr |=
  9267. (!CurrentRegionOnly && CI != CE && SI == SE);
  9268. return false;
  9269. });
  9270. if (CurrentRegionOnly)
  9271. return FoundError;
  9272. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  9273. // If any part of the original storage of a list item has corresponding
  9274. // storage in the device data environment, all of the original storage must
  9275. // have corresponding storage in the device data environment.
  9276. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  9277. // If a list item is an element of a structure, and a different element of
  9278. // the structure has a corresponding list item in the device data environment
  9279. // prior to a task encountering the construct associated with the map clause,
  9280. // then the list item must also have a corresponding list item in the device
  9281. // data environment prior to the task encountering the construct.
  9282. //
  9283. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  9284. SemaRef.Diag(ELoc,
  9285. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  9286. << ERange;
  9287. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  9288. << EnclosingExpr->getSourceRange();
  9289. return true;
  9290. }
  9291. return FoundError;
  9292. }
  9293. namespace {
  9294. // Utility struct that gathers all the related lists associated with a mappable
  9295. // expression.
  9296. struct MappableVarListInfo final {
  9297. // The list of expressions.
  9298. ArrayRef<Expr *> VarList;
  9299. // The list of processed expressions.
  9300. SmallVector<Expr *, 16> ProcessedVarList;
  9301. // The mappble components for each expression.
  9302. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  9303. // The base declaration of the variable.
  9304. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  9305. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  9306. // We have a list of components and base declarations for each entry in the
  9307. // variable list.
  9308. VarComponents.reserve(VarList.size());
  9309. VarBaseDeclarations.reserve(VarList.size());
  9310. }
  9311. };
  9312. }
  9313. // Check the validity of the provided variable list for the provided clause kind
  9314. // \a CKind. In the check process the valid expressions, and mappable expression
  9315. // components and variables are extracted and used to fill \a Vars,
  9316. // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
  9317. // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
  9318. static void
  9319. checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
  9320. OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
  9321. SourceLocation StartLoc,
  9322. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  9323. bool IsMapTypeImplicit = false) {
  9324. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  9325. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  9326. "Unexpected clause kind with mappable expressions!");
  9327. // Keep track of the mappable components and base declarations in this clause.
  9328. // Each entry in the list is going to have a list of components associated. We
  9329. // record each set of the components so that we can build the clause later on.
  9330. // In the end we should have the same amount of declarations and component
  9331. // lists.
  9332. for (auto &RE : MVLI.VarList) {
  9333. assert(RE && "Null expr in omp to/from/map clause");
  9334. SourceLocation ELoc = RE->getExprLoc();
  9335. auto *VE = RE->IgnoreParenLValueCasts();
  9336. if (VE->isValueDependent() || VE->isTypeDependent() ||
  9337. VE->isInstantiationDependent() ||
  9338. VE->containsUnexpandedParameterPack()) {
  9339. // We can only analyze this information once the missing information is
  9340. // resolved.
  9341. MVLI.ProcessedVarList.push_back(RE);
  9342. continue;
  9343. }
  9344. auto *SimpleExpr = RE->IgnoreParenCasts();
  9345. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  9346. SemaRef.Diag(ELoc,
  9347. diag::err_omp_expected_named_var_member_or_array_expression)
  9348. << RE->getSourceRange();
  9349. continue;
  9350. }
  9351. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  9352. ValueDecl *CurDeclaration = nullptr;
  9353. // Obtain the array or member expression bases if required. Also, fill the
  9354. // components array with all the components identified in the process.
  9355. auto *BE =
  9356. CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
  9357. if (!BE)
  9358. continue;
  9359. assert(!CurComponents.empty() &&
  9360. "Invalid mappable expression information.");
  9361. // For the following checks, we rely on the base declaration which is
  9362. // expected to be associated with the last component. The declaration is
  9363. // expected to be a variable or a field (if 'this' is being mapped).
  9364. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  9365. assert(CurDeclaration && "Null decl on map clause.");
  9366. assert(
  9367. CurDeclaration->isCanonicalDecl() &&
  9368. "Expecting components to have associated only canonical declarations.");
  9369. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  9370. auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  9371. assert((VD || FD) && "Only variables or fields are expected here!");
  9372. (void)FD;
  9373. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  9374. // threadprivate variables cannot appear in a map clause.
  9375. // OpenMP 4.5 [2.10.5, target update Construct]
  9376. // threadprivate variables cannot appear in a from clause.
  9377. if (VD && DSAS->isThreadPrivate(VD)) {
  9378. auto DVar = DSAS->getTopDSA(VD, false);
  9379. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  9380. << getOpenMPClauseName(CKind);
  9381. ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
  9382. continue;
  9383. }
  9384. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  9385. // A list item cannot appear in both a map clause and a data-sharing
  9386. // attribute clause on the same construct.
  9387. // Check conflicts with other map clause expressions. We check the conflicts
  9388. // with the current construct separately from the enclosing data
  9389. // environment, because the restrictions are different. We only have to
  9390. // check conflicts across regions for the map clauses.
  9391. if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  9392. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  9393. break;
  9394. if (CKind == OMPC_map &&
  9395. CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  9396. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  9397. break;
  9398. // OpenMP 4.5 [2.10.5, target update Construct]
  9399. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  9400. // If the type of a list item is a reference to a type T then the type will
  9401. // be considered to be T for all purposes of this clause.
  9402. QualType Type = CurDeclaration->getType().getNonReferenceType();
  9403. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  9404. // A list item in a to or from clause must have a mappable type.
  9405. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  9406. // A list item must have a mappable type.
  9407. if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  9408. DSAS, Type))
  9409. continue;
  9410. if (CKind == OMPC_map) {
  9411. // target enter data
  9412. // OpenMP [2.10.2, Restrictions, p. 99]
  9413. // A map-type must be specified in all map clauses and must be either
  9414. // to or alloc.
  9415. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  9416. if (DKind == OMPD_target_enter_data &&
  9417. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  9418. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  9419. << (IsMapTypeImplicit ? 1 : 0)
  9420. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  9421. << getOpenMPDirectiveName(DKind);
  9422. continue;
  9423. }
  9424. // target exit_data
  9425. // OpenMP [2.10.3, Restrictions, p. 102]
  9426. // A map-type must be specified in all map clauses and must be either
  9427. // from, release, or delete.
  9428. if (DKind == OMPD_target_exit_data &&
  9429. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  9430. MapType == OMPC_MAP_delete)) {
  9431. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  9432. << (IsMapTypeImplicit ? 1 : 0)
  9433. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  9434. << getOpenMPDirectiveName(DKind);
  9435. continue;
  9436. }
  9437. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  9438. // A list item cannot appear in both a map clause and a data-sharing
  9439. // attribute clause on the same construct
  9440. if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
  9441. DKind == OMPD_target_teams_distribute ||
  9442. DKind == OMPD_target_teams_distribute_parallel_for) && VD) {
  9443. auto DVar = DSAS->getTopDSA(VD, false);
  9444. if (isOpenMPPrivate(DVar.CKind)) {
  9445. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  9446. << getOpenMPClauseName(DVar.CKind)
  9447. << getOpenMPClauseName(OMPC_map)
  9448. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  9449. ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
  9450. continue;
  9451. }
  9452. }
  9453. }
  9454. // Save the current expression.
  9455. MVLI.ProcessedVarList.push_back(RE);
  9456. // Store the components in the stack so that they can be used to check
  9457. // against other clauses later on.
  9458. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  9459. /*WhereFoundClauseKind=*/OMPC_map);
  9460. // Save the components and declaration to create the clause. For purposes of
  9461. // the clause creation, any component list that has has base 'this' uses
  9462. // null as base declaration.
  9463. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  9464. MVLI.VarComponents.back().append(CurComponents.begin(),
  9465. CurComponents.end());
  9466. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  9467. : CurDeclaration);
  9468. }
  9469. }
  9470. OMPClause *
  9471. Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
  9472. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  9473. SourceLocation MapLoc, SourceLocation ColonLoc,
  9474. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  9475. SourceLocation LParenLoc, SourceLocation EndLoc) {
  9476. MappableVarListInfo MVLI(VarList);
  9477. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
  9478. MapType, IsMapTypeImplicit);
  9479. // We need to produce a map clause even if we don't have variables so that
  9480. // other diagnostics related with non-existing map clauses are accurate.
  9481. return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9482. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  9483. MVLI.VarComponents, MapTypeModifier, MapType,
  9484. IsMapTypeImplicit, MapLoc);
  9485. }
  9486. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  9487. TypeResult ParsedType) {
  9488. assert(ParsedType.isUsable());
  9489. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  9490. if (ReductionType.isNull())
  9491. return QualType();
  9492. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  9493. // A type name in a declare reduction directive cannot be a function type, an
  9494. // array type, a reference type, or a type qualified with const, volatile or
  9495. // restrict.
  9496. if (ReductionType.hasQualifiers()) {
  9497. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  9498. return QualType();
  9499. }
  9500. if (ReductionType->isFunctionType()) {
  9501. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  9502. return QualType();
  9503. }
  9504. if (ReductionType->isReferenceType()) {
  9505. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  9506. return QualType();
  9507. }
  9508. if (ReductionType->isArrayType()) {
  9509. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  9510. return QualType();
  9511. }
  9512. return ReductionType;
  9513. }
  9514. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  9515. Scope *S, DeclContext *DC, DeclarationName Name,
  9516. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  9517. AccessSpecifier AS, Decl *PrevDeclInScope) {
  9518. SmallVector<Decl *, 8> Decls;
  9519. Decls.reserve(ReductionTypes.size());
  9520. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  9521. ForRedeclaration);
  9522. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  9523. // A reduction-identifier may not be re-declared in the current scope for the
  9524. // same type or for a type that is compatible according to the base language
  9525. // rules.
  9526. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  9527. OMPDeclareReductionDecl *PrevDRD = nullptr;
  9528. bool InCompoundScope = true;
  9529. if (S != nullptr) {
  9530. // Find previous declaration with the same name not referenced in other
  9531. // declarations.
  9532. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  9533. InCompoundScope =
  9534. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  9535. LookupName(Lookup, S);
  9536. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  9537. /*AllowInlineNamespace=*/false);
  9538. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  9539. auto Filter = Lookup.makeFilter();
  9540. while (Filter.hasNext()) {
  9541. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  9542. if (InCompoundScope) {
  9543. auto I = UsedAsPrevious.find(PrevDecl);
  9544. if (I == UsedAsPrevious.end())
  9545. UsedAsPrevious[PrevDecl] = false;
  9546. if (auto *D = PrevDecl->getPrevDeclInScope())
  9547. UsedAsPrevious[D] = true;
  9548. }
  9549. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  9550. PrevDecl->getLocation();
  9551. }
  9552. Filter.done();
  9553. if (InCompoundScope) {
  9554. for (auto &PrevData : UsedAsPrevious) {
  9555. if (!PrevData.second) {
  9556. PrevDRD = PrevData.first;
  9557. break;
  9558. }
  9559. }
  9560. }
  9561. } else if (PrevDeclInScope != nullptr) {
  9562. auto *PrevDRDInScope = PrevDRD =
  9563. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  9564. do {
  9565. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  9566. PrevDRDInScope->getLocation();
  9567. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  9568. } while (PrevDRDInScope != nullptr);
  9569. }
  9570. for (auto &TyData : ReductionTypes) {
  9571. auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  9572. bool Invalid = false;
  9573. if (I != PreviousRedeclTypes.end()) {
  9574. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  9575. << TyData.first;
  9576. Diag(I->second, diag::note_previous_definition);
  9577. Invalid = true;
  9578. }
  9579. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  9580. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  9581. Name, TyData.first, PrevDRD);
  9582. DC->addDecl(DRD);
  9583. DRD->setAccess(AS);
  9584. Decls.push_back(DRD);
  9585. if (Invalid)
  9586. DRD->setInvalidDecl();
  9587. else
  9588. PrevDRD = DRD;
  9589. }
  9590. return DeclGroupPtrTy::make(
  9591. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  9592. }
  9593. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  9594. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  9595. // Enter new function scope.
  9596. PushFunctionScope();
  9597. getCurFunction()->setHasBranchProtectedScope();
  9598. getCurFunction()->setHasOMPDeclareReductionCombiner();
  9599. if (S != nullptr)
  9600. PushDeclContext(S, DRD);
  9601. else
  9602. CurContext = DRD;
  9603. PushExpressionEvaluationContext(PotentiallyEvaluated);
  9604. QualType ReductionType = DRD->getType();
  9605. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  9606. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  9607. // uses semantics of argument handles by value, but it should be passed by
  9608. // reference. C lang does not support references, so pass all parameters as
  9609. // pointers.
  9610. // Create 'T omp_in;' variable.
  9611. auto *OmpInParm =
  9612. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  9613. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  9614. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  9615. // uses semantics of argument handles by value, but it should be passed by
  9616. // reference. C lang does not support references, so pass all parameters as
  9617. // pointers.
  9618. // Create 'T omp_out;' variable.
  9619. auto *OmpOutParm =
  9620. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  9621. if (S != nullptr) {
  9622. PushOnScopeChains(OmpInParm, S);
  9623. PushOnScopeChains(OmpOutParm, S);
  9624. } else {
  9625. DRD->addDecl(OmpInParm);
  9626. DRD->addDecl(OmpOutParm);
  9627. }
  9628. }
  9629. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  9630. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  9631. DiscardCleanupsInEvaluationContext();
  9632. PopExpressionEvaluationContext();
  9633. PopDeclContext();
  9634. PopFunctionScopeInfo();
  9635. if (Combiner != nullptr)
  9636. DRD->setCombiner(Combiner);
  9637. else
  9638. DRD->setInvalidDecl();
  9639. }
  9640. void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  9641. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  9642. // Enter new function scope.
  9643. PushFunctionScope();
  9644. getCurFunction()->setHasBranchProtectedScope();
  9645. if (S != nullptr)
  9646. PushDeclContext(S, DRD);
  9647. else
  9648. CurContext = DRD;
  9649. PushExpressionEvaluationContext(PotentiallyEvaluated);
  9650. QualType ReductionType = DRD->getType();
  9651. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  9652. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  9653. // uses semantics of argument handles by value, but it should be passed by
  9654. // reference. C lang does not support references, so pass all parameters as
  9655. // pointers.
  9656. // Create 'T omp_priv;' variable.
  9657. auto *OmpPrivParm =
  9658. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  9659. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  9660. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  9661. // uses semantics of argument handles by value, but it should be passed by
  9662. // reference. C lang does not support references, so pass all parameters as
  9663. // pointers.
  9664. // Create 'T omp_orig;' variable.
  9665. auto *OmpOrigParm =
  9666. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  9667. if (S != nullptr) {
  9668. PushOnScopeChains(OmpPrivParm, S);
  9669. PushOnScopeChains(OmpOrigParm, S);
  9670. } else {
  9671. DRD->addDecl(OmpPrivParm);
  9672. DRD->addDecl(OmpOrigParm);
  9673. }
  9674. }
  9675. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
  9676. Expr *Initializer) {
  9677. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  9678. DiscardCleanupsInEvaluationContext();
  9679. PopExpressionEvaluationContext();
  9680. PopDeclContext();
  9681. PopFunctionScopeInfo();
  9682. if (Initializer != nullptr)
  9683. DRD->setInitializer(Initializer);
  9684. else
  9685. DRD->setInvalidDecl();
  9686. }
  9687. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  9688. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  9689. for (auto *D : DeclReductions.get()) {
  9690. if (IsValid) {
  9691. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  9692. if (S != nullptr)
  9693. PushOnScopeChains(DRD, S, /*AddToContext=*/false);
  9694. } else
  9695. D->setInvalidDecl();
  9696. }
  9697. return DeclReductions;
  9698. }
  9699. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  9700. SourceLocation StartLoc,
  9701. SourceLocation LParenLoc,
  9702. SourceLocation EndLoc) {
  9703. Expr *ValExpr = NumTeams;
  9704. // OpenMP [teams Constrcut, Restrictions]
  9705. // The num_teams expression must evaluate to a positive integer value.
  9706. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  9707. /*StrictlyPositive=*/true))
  9708. return nullptr;
  9709. return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  9710. }
  9711. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  9712. SourceLocation StartLoc,
  9713. SourceLocation LParenLoc,
  9714. SourceLocation EndLoc) {
  9715. Expr *ValExpr = ThreadLimit;
  9716. // OpenMP [teams Constrcut, Restrictions]
  9717. // The thread_limit expression must evaluate to a positive integer value.
  9718. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  9719. /*StrictlyPositive=*/true))
  9720. return nullptr;
  9721. return new (Context)
  9722. OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  9723. }
  9724. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  9725. SourceLocation StartLoc,
  9726. SourceLocation LParenLoc,
  9727. SourceLocation EndLoc) {
  9728. Expr *ValExpr = Priority;
  9729. // OpenMP [2.9.1, task Constrcut]
  9730. // The priority-value is a non-negative numerical scalar expression.
  9731. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  9732. /*StrictlyPositive=*/false))
  9733. return nullptr;
  9734. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  9735. }
  9736. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  9737. SourceLocation StartLoc,
  9738. SourceLocation LParenLoc,
  9739. SourceLocation EndLoc) {
  9740. Expr *ValExpr = Grainsize;
  9741. // OpenMP [2.9.2, taskloop Constrcut]
  9742. // The parameter of the grainsize clause must be a positive integer
  9743. // expression.
  9744. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  9745. /*StrictlyPositive=*/true))
  9746. return nullptr;
  9747. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  9748. }
  9749. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  9750. SourceLocation StartLoc,
  9751. SourceLocation LParenLoc,
  9752. SourceLocation EndLoc) {
  9753. Expr *ValExpr = NumTasks;
  9754. // OpenMP [2.9.2, taskloop Constrcut]
  9755. // The parameter of the num_tasks clause must be a positive integer
  9756. // expression.
  9757. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  9758. /*StrictlyPositive=*/true))
  9759. return nullptr;
  9760. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  9761. }
  9762. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  9763. SourceLocation LParenLoc,
  9764. SourceLocation EndLoc) {
  9765. // OpenMP [2.13.2, critical construct, Description]
  9766. // ... where hint-expression is an integer constant expression that evaluates
  9767. // to a valid lock hint.
  9768. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  9769. if (HintExpr.isInvalid())
  9770. return nullptr;
  9771. return new (Context)
  9772. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  9773. }
  9774. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  9775. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  9776. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  9777. SourceLocation EndLoc) {
  9778. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  9779. std::string Values;
  9780. Values += "'";
  9781. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  9782. Values += "'";
  9783. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  9784. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  9785. return nullptr;
  9786. }
  9787. Expr *ValExpr = ChunkSize;
  9788. Stmt *HelperValStmt = nullptr;
  9789. if (ChunkSize) {
  9790. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  9791. !ChunkSize->isInstantiationDependent() &&
  9792. !ChunkSize->containsUnexpandedParameterPack()) {
  9793. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  9794. ExprResult Val =
  9795. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  9796. if (Val.isInvalid())
  9797. return nullptr;
  9798. ValExpr = Val.get();
  9799. // OpenMP [2.7.1, Restrictions]
  9800. // chunk_size must be a loop invariant integer expression with a positive
  9801. // value.
  9802. llvm::APSInt Result;
  9803. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  9804. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  9805. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  9806. << "dist_schedule" << ChunkSize->getSourceRange();
  9807. return nullptr;
  9808. }
  9809. } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
  9810. !CurContext->isDependentContext()) {
  9811. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  9812. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  9813. HelperValStmt = buildPreInits(Context, Captures);
  9814. }
  9815. }
  9816. }
  9817. return new (Context)
  9818. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  9819. Kind, ValExpr, HelperValStmt);
  9820. }
  9821. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  9822. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  9823. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  9824. SourceLocation KindLoc, SourceLocation EndLoc) {
  9825. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  9826. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  9827. std::string Value;
  9828. SourceLocation Loc;
  9829. Value += "'";
  9830. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  9831. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  9832. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  9833. Loc = MLoc;
  9834. } else {
  9835. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  9836. OMPC_DEFAULTMAP_scalar);
  9837. Loc = KindLoc;
  9838. }
  9839. Value += "'";
  9840. Diag(Loc, diag::err_omp_unexpected_clause_value)
  9841. << Value << getOpenMPClauseName(OMPC_defaultmap);
  9842. return nullptr;
  9843. }
  9844. return new (Context)
  9845. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  9846. }
  9847. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  9848. DeclContext *CurLexicalContext = getCurLexicalContext();
  9849. if (!CurLexicalContext->isFileContext() &&
  9850. !CurLexicalContext->isExternCContext() &&
  9851. !CurLexicalContext->isExternCXXContext()) {
  9852. Diag(Loc, diag::err_omp_region_not_file_context);
  9853. return false;
  9854. }
  9855. if (IsInOpenMPDeclareTargetContext) {
  9856. Diag(Loc, diag::err_omp_enclosed_declare_target);
  9857. return false;
  9858. }
  9859. IsInOpenMPDeclareTargetContext = true;
  9860. return true;
  9861. }
  9862. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  9863. assert(IsInOpenMPDeclareTargetContext &&
  9864. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  9865. IsInOpenMPDeclareTargetContext = false;
  9866. }
  9867. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  9868. CXXScopeSpec &ScopeSpec,
  9869. const DeclarationNameInfo &Id,
  9870. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  9871. NamedDeclSetType &SameDirectiveDecls) {
  9872. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  9873. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  9874. if (Lookup.isAmbiguous())
  9875. return;
  9876. Lookup.suppressDiagnostics();
  9877. if (!Lookup.isSingleResult()) {
  9878. if (TypoCorrection Corrected =
  9879. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
  9880. llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
  9881. CTK_ErrorRecovery)) {
  9882. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  9883. << Id.getName());
  9884. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  9885. return;
  9886. }
  9887. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  9888. return;
  9889. }
  9890. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  9891. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
  9892. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  9893. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  9894. if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
  9895. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  9896. ND->addAttr(A);
  9897. if (ASTMutationListener *ML = Context.getASTMutationListener())
  9898. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  9899. checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
  9900. } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
  9901. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  9902. << Id.getName();
  9903. }
  9904. } else
  9905. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  9906. }
  9907. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  9908. Sema &SemaRef, Decl *D) {
  9909. if (!D)
  9910. return;
  9911. Decl *LD = nullptr;
  9912. if (isa<TagDecl>(D)) {
  9913. LD = cast<TagDecl>(D)->getDefinition();
  9914. } else if (isa<VarDecl>(D)) {
  9915. LD = cast<VarDecl>(D)->getDefinition();
  9916. // If this is an implicit variable that is legal and we do not need to do
  9917. // anything.
  9918. if (cast<VarDecl>(D)->isImplicit()) {
  9919. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  9920. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  9921. D->addAttr(A);
  9922. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  9923. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  9924. return;
  9925. }
  9926. } else if (isa<FunctionDecl>(D)) {
  9927. const FunctionDecl *FD = nullptr;
  9928. if (cast<FunctionDecl>(D)->hasBody(FD))
  9929. LD = const_cast<FunctionDecl *>(FD);
  9930. // If the definition is associated with the current declaration in the
  9931. // target region (it can be e.g. a lambda) that is legal and we do not need
  9932. // to do anything else.
  9933. if (LD == D) {
  9934. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  9935. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  9936. D->addAttr(A);
  9937. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  9938. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  9939. return;
  9940. }
  9941. }
  9942. if (!LD)
  9943. LD = D;
  9944. if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
  9945. (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
  9946. // Outlined declaration is not declared target.
  9947. if (LD->isOutOfLine()) {
  9948. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  9949. SemaRef.Diag(SL, diag::note_used_here) << SR;
  9950. } else {
  9951. DeclContext *DC = LD->getDeclContext();
  9952. while (DC) {
  9953. if (isa<FunctionDecl>(DC) &&
  9954. cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
  9955. break;
  9956. DC = DC->getParent();
  9957. }
  9958. if (DC)
  9959. return;
  9960. // Is not declared in target context.
  9961. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  9962. SemaRef.Diag(SL, diag::note_used_here) << SR;
  9963. }
  9964. // Mark decl as declared target to prevent further diagnostic.
  9965. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  9966. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  9967. D->addAttr(A);
  9968. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  9969. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  9970. }
  9971. }
  9972. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  9973. Sema &SemaRef, DSAStackTy *Stack,
  9974. ValueDecl *VD) {
  9975. if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
  9976. return true;
  9977. if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
  9978. return false;
  9979. return true;
  9980. }
  9981. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
  9982. if (!D || D->isInvalidDecl())
  9983. return;
  9984. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  9985. SourceLocation SL = E ? E->getLocStart() : D->getLocation();
  9986. // 2.10.6: threadprivate variable cannot appear in a declare target directive.
  9987. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  9988. if (DSAStack->isThreadPrivate(VD)) {
  9989. Diag(SL, diag::err_omp_threadprivate_in_target);
  9990. ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  9991. return;
  9992. }
  9993. }
  9994. if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
  9995. // Problem if any with var declared with incomplete type will be reported
  9996. // as normal, so no need to check it here.
  9997. if ((E || !VD->getType()->isIncompleteType()) &&
  9998. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
  9999. // Mark decl as declared target to prevent further diagnostic.
  10000. if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
  10001. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  10002. Context, OMPDeclareTargetDeclAttr::MT_To);
  10003. VD->addAttr(A);
  10004. if (ASTMutationListener *ML = Context.getASTMutationListener())
  10005. ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
  10006. }
  10007. return;
  10008. }
  10009. }
  10010. if (!E) {
  10011. // Checking declaration inside declare target region.
  10012. if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
  10013. (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
  10014. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  10015. Context, OMPDeclareTargetDeclAttr::MT_To);
  10016. D->addAttr(A);
  10017. if (ASTMutationListener *ML = Context.getASTMutationListener())
  10018. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  10019. }
  10020. return;
  10021. }
  10022. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  10023. }
  10024. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  10025. SourceLocation StartLoc,
  10026. SourceLocation LParenLoc,
  10027. SourceLocation EndLoc) {
  10028. MappableVarListInfo MVLI(VarList);
  10029. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
  10030. if (MVLI.ProcessedVarList.empty())
  10031. return nullptr;
  10032. return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10033. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  10034. MVLI.VarComponents);
  10035. }
  10036. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  10037. SourceLocation StartLoc,
  10038. SourceLocation LParenLoc,
  10039. SourceLocation EndLoc) {
  10040. MappableVarListInfo MVLI(VarList);
  10041. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
  10042. if (MVLI.ProcessedVarList.empty())
  10043. return nullptr;
  10044. return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10045. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  10046. MVLI.VarComponents);
  10047. }
  10048. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  10049. SourceLocation StartLoc,
  10050. SourceLocation LParenLoc,
  10051. SourceLocation EndLoc) {
  10052. MappableVarListInfo MVLI(VarList);
  10053. SmallVector<Expr *, 8> PrivateCopies;
  10054. SmallVector<Expr *, 8> Inits;
  10055. for (auto &RefExpr : VarList) {
  10056. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  10057. SourceLocation ELoc;
  10058. SourceRange ERange;
  10059. Expr *SimpleRefExpr = RefExpr;
  10060. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10061. if (Res.second) {
  10062. // It will be analyzed later.
  10063. MVLI.ProcessedVarList.push_back(RefExpr);
  10064. PrivateCopies.push_back(nullptr);
  10065. Inits.push_back(nullptr);
  10066. }
  10067. ValueDecl *D = Res.first;
  10068. if (!D)
  10069. continue;
  10070. QualType Type = D->getType();
  10071. Type = Type.getNonReferenceType().getUnqualifiedType();
  10072. auto *VD = dyn_cast<VarDecl>(D);
  10073. // Item should be a pointer or reference to pointer.
  10074. if (!Type->isPointerType()) {
  10075. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  10076. << 0 << RefExpr->getSourceRange();
  10077. continue;
  10078. }
  10079. // Build the private variable and the expression that refers to it.
  10080. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  10081. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10082. if (VDPrivate->isInvalidDecl())
  10083. continue;
  10084. CurContext->addDecl(VDPrivate);
  10085. auto VDPrivateRefExpr = buildDeclRefExpr(
  10086. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  10087. // Add temporary variable to initialize the private copy of the pointer.
  10088. auto *VDInit =
  10089. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  10090. auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  10091. RefExpr->getExprLoc());
  10092. AddInitializerToDecl(VDPrivate,
  10093. DefaultLvalueConversion(VDInitRefExpr).get(),
  10094. /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
  10095. // If required, build a capture to implement the privatization initialized
  10096. // with the current list item value.
  10097. DeclRefExpr *Ref = nullptr;
  10098. if (!VD)
  10099. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  10100. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  10101. PrivateCopies.push_back(VDPrivateRefExpr);
  10102. Inits.push_back(VDInitRefExpr);
  10103. // We need to add a data sharing attribute for this variable to make sure it
  10104. // is correctly captured. A variable that shows up in a use_device_ptr has
  10105. // similar properties of a first private variable.
  10106. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  10107. // Create a mappable component for the list item. List items in this clause
  10108. // only need a component.
  10109. MVLI.VarBaseDeclarations.push_back(D);
  10110. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  10111. MVLI.VarComponents.back().push_back(
  10112. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  10113. }
  10114. if (MVLI.ProcessedVarList.empty())
  10115. return nullptr;
  10116. return OMPUseDevicePtrClause::Create(
  10117. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  10118. PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
  10119. }
  10120. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  10121. SourceLocation StartLoc,
  10122. SourceLocation LParenLoc,
  10123. SourceLocation EndLoc) {
  10124. MappableVarListInfo MVLI(VarList);
  10125. for (auto &RefExpr : VarList) {
  10126. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  10127. SourceLocation ELoc;
  10128. SourceRange ERange;
  10129. Expr *SimpleRefExpr = RefExpr;
  10130. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10131. if (Res.second) {
  10132. // It will be analyzed later.
  10133. MVLI.ProcessedVarList.push_back(RefExpr);
  10134. }
  10135. ValueDecl *D = Res.first;
  10136. if (!D)
  10137. continue;
  10138. QualType Type = D->getType();
  10139. // item should be a pointer or array or reference to pointer or array
  10140. if (!Type.getNonReferenceType()->isPointerType() &&
  10141. !Type.getNonReferenceType()->isArrayType()) {
  10142. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  10143. << 0 << RefExpr->getSourceRange();
  10144. continue;
  10145. }
  10146. // Check if the declaration in the clause does not show up in any data
  10147. // sharing attribute.
  10148. auto DVar = DSAStack->getTopDSA(D, false);
  10149. if (isOpenMPPrivate(DVar.CKind)) {
  10150. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  10151. << getOpenMPClauseName(DVar.CKind)
  10152. << getOpenMPClauseName(OMPC_is_device_ptr)
  10153. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  10154. ReportOriginalDSA(*this, DSAStack, D, DVar);
  10155. continue;
  10156. }
  10157. Expr *ConflictExpr;
  10158. if (DSAStack->checkMappableExprComponentListsForDecl(
  10159. D, /*CurrentRegionOnly=*/true,
  10160. [&ConflictExpr](
  10161. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  10162. OpenMPClauseKind) -> bool {
  10163. ConflictExpr = R.front().getAssociatedExpression();
  10164. return true;
  10165. })) {
  10166. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  10167. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  10168. << ConflictExpr->getSourceRange();
  10169. continue;
  10170. }
  10171. // Store the components in the stack so that they can be used to check
  10172. // against other clauses later on.
  10173. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  10174. DSAStack->addMappableExpressionComponents(
  10175. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  10176. // Record the expression we've just processed.
  10177. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  10178. // Create a mappable component for the list item. List items in this clause
  10179. // only need a component. We use a null declaration to signal fields in
  10180. // 'this'.
  10181. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  10182. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  10183. "Unexpected device pointer expression!");
  10184. MVLI.VarBaseDeclarations.push_back(
  10185. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  10186. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  10187. MVLI.VarComponents.back().push_back(MC);
  10188. }
  10189. if (MVLI.ProcessedVarList.empty())
  10190. return nullptr;
  10191. return OMPIsDevicePtrClause::Create(
  10192. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  10193. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  10194. }