SemaExpr.cpp 664 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128
  1. //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for expressions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TreeTransform.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DeclTemplate.h"
  20. #include "clang/AST/EvaluatedExprVisitor.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/ExprObjC.h"
  24. #include "clang/AST/ExprOpenMP.h"
  25. #include "clang/AST/RecursiveASTVisitor.h"
  26. #include "clang/AST/TypeLoc.h"
  27. #include "clang/Basic/FixedPoint.h"
  28. #include "clang/Basic/PartialDiagnostic.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Lex/LiteralSupport.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "clang/Sema/AnalysisBasedWarnings.h"
  34. #include "clang/Sema/DeclSpec.h"
  35. #include "clang/Sema/DelayedDiagnostic.h"
  36. #include "clang/Sema/Designator.h"
  37. #include "clang/Sema/Initialization.h"
  38. #include "clang/Sema/Lookup.h"
  39. #include "clang/Sema/Overload.h"
  40. #include "clang/Sema/ParsedTemplate.h"
  41. #include "clang/Sema/Scope.h"
  42. #include "clang/Sema/ScopeInfo.h"
  43. #include "clang/Sema/SemaFixItUtils.h"
  44. #include "clang/Sema/SemaInternal.h"
  45. #include "clang/Sema/Template.h"
  46. #include "llvm/Support/ConvertUTF.h"
  47. using namespace clang;
  48. using namespace sema;
  49. /// Determine whether the use of this declaration is valid, without
  50. /// emitting diagnostics.
  51. bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
  52. // See if this is an auto-typed variable whose initializer we are parsing.
  53. if (ParsingInitForAutoVars.count(D))
  54. return false;
  55. // See if this is a deleted function.
  56. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  57. if (FD->isDeleted())
  58. return false;
  59. // If the function has a deduced return type, and we can't deduce it,
  60. // then we can't use it either.
  61. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  62. DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
  63. return false;
  64. // See if this is an aligned allocation/deallocation function that is
  65. // unavailable.
  66. if (TreatUnavailableAsInvalid &&
  67. isUnavailableAlignedAllocationFunction(*FD))
  68. return false;
  69. }
  70. // See if this function is unavailable.
  71. if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
  72. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  73. return false;
  74. return true;
  75. }
  76. static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  77. // Warn if this is used but marked unused.
  78. if (const auto *A = D->getAttr<UnusedAttr>()) {
  79. // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
  80. // should diagnose them.
  81. if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
  82. A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
  83. const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
  84. if (DC && !DC->hasAttr<UnusedAttr>())
  85. S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
  86. }
  87. }
  88. }
  89. /// Emit a note explaining that this function is deleted.
  90. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  91. assert(Decl->isDeleted());
  92. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
  93. if (Method && Method->isDeleted() && Method->isDefaulted()) {
  94. // If the method was explicitly defaulted, point at that declaration.
  95. if (!Method->isImplicit())
  96. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  97. // Try to diagnose why this special member function was implicitly
  98. // deleted. This might fail, if that reason no longer applies.
  99. CXXSpecialMember CSM = getSpecialMember(Method);
  100. if (CSM != CXXInvalid)
  101. ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
  102. return;
  103. }
  104. auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
  105. if (Ctor && Ctor->isInheritingConstructor())
  106. return NoteDeletedInheritingConstructor(Ctor);
  107. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  108. << Decl << 1;
  109. }
  110. /// Determine whether a FunctionDecl was ever declared with an
  111. /// explicit storage class.
  112. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  113. for (auto I : D->redecls()) {
  114. if (I->getStorageClass() != SC_None)
  115. return true;
  116. }
  117. return false;
  118. }
  119. /// Check whether we're in an extern inline function and referring to a
  120. /// variable or function with internal linkage (C11 6.7.4p3).
  121. ///
  122. /// This is only a warning because we used to silently accept this code, but
  123. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  124. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  125. /// and so while there may still be user mistakes, most of the time we can't
  126. /// prove that there are errors.
  127. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  128. const NamedDecl *D,
  129. SourceLocation Loc) {
  130. // This is disabled under C++; there are too many ways for this to fire in
  131. // contexts where the warning is a false positive, or where it is technically
  132. // correct but benign.
  133. if (S.getLangOpts().CPlusPlus)
  134. return;
  135. // Check if this is an inlined function or method.
  136. FunctionDecl *Current = S.getCurFunctionDecl();
  137. if (!Current)
  138. return;
  139. if (!Current->isInlined())
  140. return;
  141. if (!Current->isExternallyVisible())
  142. return;
  143. // Check if the decl has internal linkage.
  144. if (D->getFormalLinkage() != InternalLinkage)
  145. return;
  146. // Downgrade from ExtWarn to Extension if
  147. // (1) the supposedly external inline function is in the main file,
  148. // and probably won't be included anywhere else.
  149. // (2) the thing we're referencing is a pure function.
  150. // (3) the thing we're referencing is another inline function.
  151. // This last can give us false negatives, but it's better than warning on
  152. // wrappers for simple C library functions.
  153. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  154. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  155. if (!DowngradeWarning && UsedFn)
  156. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  157. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  158. : diag::ext_internal_in_extern_inline)
  159. << /*IsVar=*/!UsedFn << D;
  160. S.MaybeSuggestAddingStaticToDecl(Current);
  161. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  162. << D;
  163. }
  164. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  165. const FunctionDecl *First = Cur->getFirstDecl();
  166. // Suggest "static" on the function, if possible.
  167. if (!hasAnyExplicitStorageClass(First)) {
  168. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  169. Diag(DeclBegin, diag::note_convert_inline_to_static)
  170. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  171. }
  172. }
  173. /// Determine whether the use of this declaration is valid, and
  174. /// emit any corresponding diagnostics.
  175. ///
  176. /// This routine diagnoses various problems with referencing
  177. /// declarations that can occur when using a declaration. For example,
  178. /// it might warn if a deprecated or unavailable declaration is being
  179. /// used, or produce an error (and return true) if a C++0x deleted
  180. /// function is being used.
  181. ///
  182. /// \returns true if there was an error (this declaration cannot be
  183. /// referenced), false otherwise.
  184. ///
  185. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
  186. const ObjCInterfaceDecl *UnknownObjCClass,
  187. bool ObjCPropertyAccess,
  188. bool AvoidPartialAvailabilityChecks,
  189. ObjCInterfaceDecl *ClassReceiver) {
  190. SourceLocation Loc = Locs.front();
  191. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  192. // If there were any diagnostics suppressed by template argument deduction,
  193. // emit them now.
  194. auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  195. if (Pos != SuppressedDiagnostics.end()) {
  196. for (const PartialDiagnosticAt &Suppressed : Pos->second)
  197. Diag(Suppressed.first, Suppressed.second);
  198. // Clear out the list of suppressed diagnostics, so that we don't emit
  199. // them again for this specialization. However, we don't obsolete this
  200. // entry from the table, because we want to avoid ever emitting these
  201. // diagnostics again.
  202. Pos->second.clear();
  203. }
  204. // C++ [basic.start.main]p3:
  205. // The function 'main' shall not be used within a program.
  206. if (cast<FunctionDecl>(D)->isMain())
  207. Diag(Loc, diag::ext_main_used);
  208. diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
  209. }
  210. // See if this is an auto-typed variable whose initializer we are parsing.
  211. if (ParsingInitForAutoVars.count(D)) {
  212. if (isa<BindingDecl>(D)) {
  213. Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
  214. << D->getDeclName();
  215. } else {
  216. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  217. << D->getDeclName() << cast<VarDecl>(D)->getType();
  218. }
  219. return true;
  220. }
  221. // See if this is a deleted function.
  222. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  223. if (FD->isDeleted()) {
  224. auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
  225. if (Ctor && Ctor->isInheritingConstructor())
  226. Diag(Loc, diag::err_deleted_inherited_ctor_use)
  227. << Ctor->getParent()
  228. << Ctor->getInheritedConstructor().getConstructor()->getParent();
  229. else
  230. Diag(Loc, diag::err_deleted_function_use);
  231. NoteDeletedFunction(FD);
  232. return true;
  233. }
  234. // If the function has a deduced return type, and we can't deduce it,
  235. // then we can't use it either.
  236. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  237. DeduceReturnType(FD, Loc))
  238. return true;
  239. if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
  240. return true;
  241. }
  242. if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  243. // Lambdas are only default-constructible or assignable in C++2a onwards.
  244. if (MD->getParent()->isLambda() &&
  245. ((isa<CXXConstructorDecl>(MD) &&
  246. cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
  247. MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
  248. Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
  249. << !isa<CXXConstructorDecl>(MD);
  250. }
  251. }
  252. auto getReferencedObjCProp = [](const NamedDecl *D) ->
  253. const ObjCPropertyDecl * {
  254. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  255. return MD->findPropertyDecl();
  256. return nullptr;
  257. };
  258. if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
  259. if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
  260. return true;
  261. } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
  262. return true;
  263. }
  264. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  265. // Only the variables omp_in and omp_out are allowed in the combiner.
  266. // Only the variables omp_priv and omp_orig are allowed in the
  267. // initializer-clause.
  268. auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
  269. if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
  270. isa<VarDecl>(D)) {
  271. Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
  272. << getCurFunction()->HasOMPDeclareReductionCombiner;
  273. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  274. return true;
  275. }
  276. // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
  277. // List-items in map clauses on this construct may only refer to the declared
  278. // variable var and entities that could be referenced by a procedure defined
  279. // at the same location
  280. auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
  281. if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
  282. isa<VarDecl>(D)) {
  283. Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
  284. << DMD->getVarName().getAsString();
  285. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  286. return true;
  287. }
  288. DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
  289. AvoidPartialAvailabilityChecks, ClassReceiver);
  290. DiagnoseUnusedOfDecl(*this, D, Loc);
  291. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  292. return false;
  293. }
  294. /// DiagnoseSentinelCalls - This routine checks whether a call or
  295. /// message-send is to a declaration with the sentinel attribute, and
  296. /// if so, it checks that the requirements of the sentinel are
  297. /// satisfied.
  298. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  299. ArrayRef<Expr *> Args) {
  300. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  301. if (!attr)
  302. return;
  303. // The number of formal parameters of the declaration.
  304. unsigned numFormalParams;
  305. // The kind of declaration. This is also an index into a %select in
  306. // the diagnostic.
  307. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  308. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  309. numFormalParams = MD->param_size();
  310. calleeType = CT_Method;
  311. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  312. numFormalParams = FD->param_size();
  313. calleeType = CT_Function;
  314. } else if (isa<VarDecl>(D)) {
  315. QualType type = cast<ValueDecl>(D)->getType();
  316. const FunctionType *fn = nullptr;
  317. if (const PointerType *ptr = type->getAs<PointerType>()) {
  318. fn = ptr->getPointeeType()->getAs<FunctionType>();
  319. if (!fn) return;
  320. calleeType = CT_Function;
  321. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  322. fn = ptr->getPointeeType()->castAs<FunctionType>();
  323. calleeType = CT_Block;
  324. } else {
  325. return;
  326. }
  327. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  328. numFormalParams = proto->getNumParams();
  329. } else {
  330. numFormalParams = 0;
  331. }
  332. } else {
  333. return;
  334. }
  335. // "nullPos" is the number of formal parameters at the end which
  336. // effectively count as part of the variadic arguments. This is
  337. // useful if you would prefer to not have *any* formal parameters,
  338. // but the language forces you to have at least one.
  339. unsigned nullPos = attr->getNullPos();
  340. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  341. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  342. // The number of arguments which should follow the sentinel.
  343. unsigned numArgsAfterSentinel = attr->getSentinel();
  344. // If there aren't enough arguments for all the formal parameters,
  345. // the sentinel, and the args after the sentinel, complain.
  346. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  347. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  348. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  349. return;
  350. }
  351. // Otherwise, find the sentinel expression.
  352. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  353. if (!sentinelExpr) return;
  354. if (sentinelExpr->isValueDependent()) return;
  355. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  356. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  357. // or 'NULL' if those are actually defined in the context. Only use
  358. // 'nil' for ObjC methods, where it's much more likely that the
  359. // variadic arguments form a list of object pointers.
  360. SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
  361. std::string NullValue;
  362. if (calleeType == CT_Method && PP.isMacroDefined("nil"))
  363. NullValue = "nil";
  364. else if (getLangOpts().CPlusPlus11)
  365. NullValue = "nullptr";
  366. else if (PP.isMacroDefined("NULL"))
  367. NullValue = "NULL";
  368. else
  369. NullValue = "(void*) 0";
  370. if (MissingNilLoc.isInvalid())
  371. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  372. else
  373. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  374. << int(calleeType)
  375. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  376. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  377. }
  378. SourceRange Sema::getExprRange(Expr *E) const {
  379. return E ? E->getSourceRange() : SourceRange();
  380. }
  381. //===----------------------------------------------------------------------===//
  382. // Standard Promotions and Conversions
  383. //===----------------------------------------------------------------------===//
  384. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  385. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
  386. // Handle any placeholder expressions which made it here.
  387. if (E->getType()->isPlaceholderType()) {
  388. ExprResult result = CheckPlaceholderExpr(E);
  389. if (result.isInvalid()) return ExprError();
  390. E = result.get();
  391. }
  392. QualType Ty = E->getType();
  393. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  394. if (Ty->isFunctionType()) {
  395. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
  396. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
  397. if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
  398. return ExprError();
  399. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  400. CK_FunctionToPointerDecay).get();
  401. } else if (Ty->isArrayType()) {
  402. // In C90 mode, arrays only promote to pointers if the array expression is
  403. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  404. // type 'array of type' is converted to an expression that has type 'pointer
  405. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  406. // that has type 'array of type' ...". The relevant change is "an lvalue"
  407. // (C90) to "an expression" (C99).
  408. //
  409. // C++ 4.2p1:
  410. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  411. // T" can be converted to an rvalue of type "pointer to T".
  412. //
  413. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
  414. E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  415. CK_ArrayToPointerDecay).get();
  416. }
  417. return E;
  418. }
  419. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  420. // Check to see if we are dereferencing a null pointer. If so,
  421. // and if not volatile-qualified, this is undefined behavior that the
  422. // optimizer will delete, so warn about it. People sometimes try to use this
  423. // to get a deterministic trap and are surprised by clang's behavior. This
  424. // only handles the pattern "*null", which is a very syntactic check.
  425. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  426. if (UO->getOpcode() == UO_Deref &&
  427. UO->getSubExpr()->IgnoreParenCasts()->
  428. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  429. !UO->getType().isVolatileQualified()) {
  430. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  431. S.PDiag(diag::warn_indirection_through_null)
  432. << UO->getSubExpr()->getSourceRange());
  433. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  434. S.PDiag(diag::note_indirection_through_null));
  435. }
  436. }
  437. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  438. SourceLocation AssignLoc,
  439. const Expr* RHS) {
  440. const ObjCIvarDecl *IV = OIRE->getDecl();
  441. if (!IV)
  442. return;
  443. DeclarationName MemberName = IV->getDeclName();
  444. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  445. if (!Member || !Member->isStr("isa"))
  446. return;
  447. const Expr *Base = OIRE->getBase();
  448. QualType BaseType = Base->getType();
  449. if (OIRE->isArrow())
  450. BaseType = BaseType->getPointeeType();
  451. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  452. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  453. ObjCInterfaceDecl *ClassDeclared = nullptr;
  454. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  455. if (!ClassDeclared->getSuperClass()
  456. && (*ClassDeclared->ivar_begin()) == IV) {
  457. if (RHS) {
  458. NamedDecl *ObjectSetClass =
  459. S.LookupSingleName(S.TUScope,
  460. &S.Context.Idents.get("object_setClass"),
  461. SourceLocation(), S.LookupOrdinaryName);
  462. if (ObjectSetClass) {
  463. SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
  464. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
  465. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  466. "object_setClass(")
  467. << FixItHint::CreateReplacement(
  468. SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
  469. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  470. }
  471. else
  472. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  473. } else {
  474. NamedDecl *ObjectGetClass =
  475. S.LookupSingleName(S.TUScope,
  476. &S.Context.Idents.get("object_getClass"),
  477. SourceLocation(), S.LookupOrdinaryName);
  478. if (ObjectGetClass)
  479. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
  480. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  481. "object_getClass(")
  482. << FixItHint::CreateReplacement(
  483. SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
  484. else
  485. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  486. }
  487. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  488. }
  489. }
  490. }
  491. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  492. // Handle any placeholder expressions which made it here.
  493. if (E->getType()->isPlaceholderType()) {
  494. ExprResult result = CheckPlaceholderExpr(E);
  495. if (result.isInvalid()) return ExprError();
  496. E = result.get();
  497. }
  498. // C++ [conv.lval]p1:
  499. // A glvalue of a non-function, non-array type T can be
  500. // converted to a prvalue.
  501. if (!E->isGLValue()) return E;
  502. QualType T = E->getType();
  503. assert(!T.isNull() && "r-value conversion on typeless expression?");
  504. // We don't want to throw lvalue-to-rvalue casts on top of
  505. // expressions of certain types in C++.
  506. if (getLangOpts().CPlusPlus &&
  507. (E->getType() == Context.OverloadTy ||
  508. T->isDependentType() ||
  509. T->isRecordType()))
  510. return E;
  511. // The C standard is actually really unclear on this point, and
  512. // DR106 tells us what the result should be but not why. It's
  513. // generally best to say that void types just doesn't undergo
  514. // lvalue-to-rvalue at all. Note that expressions of unqualified
  515. // 'void' type are never l-values, but qualified void can be.
  516. if (T->isVoidType())
  517. return E;
  518. // OpenCL usually rejects direct accesses to values of 'half' type.
  519. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  520. T->isHalfType()) {
  521. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  522. << 0 << T;
  523. return ExprError();
  524. }
  525. CheckForNullPointerDereference(*this, E);
  526. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  527. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  528. &Context.Idents.get("object_getClass"),
  529. SourceLocation(), LookupOrdinaryName);
  530. if (ObjectGetClass)
  531. Diag(E->getExprLoc(), diag::warn_objc_isa_use)
  532. << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
  533. << FixItHint::CreateReplacement(
  534. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  535. else
  536. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  537. }
  538. else if (const ObjCIvarRefExpr *OIRE =
  539. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  540. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  541. // C++ [conv.lval]p1:
  542. // [...] If T is a non-class type, the type of the prvalue is the
  543. // cv-unqualified version of T. Otherwise, the type of the
  544. // rvalue is T.
  545. //
  546. // C99 6.3.2.1p2:
  547. // If the lvalue has qualified type, the value has the unqualified
  548. // version of the type of the lvalue; otherwise, the value has the
  549. // type of the lvalue.
  550. if (T.hasQualifiers())
  551. T = T.getUnqualifiedType();
  552. // Under the MS ABI, lock down the inheritance model now.
  553. if (T->isMemberPointerType() &&
  554. Context.getTargetInfo().getCXXABI().isMicrosoft())
  555. (void)isCompleteType(E->getExprLoc(), T);
  556. UpdateMarkingForLValueToRValue(E);
  557. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  558. // balance that.
  559. if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  560. Cleanup.setExprNeedsCleanups(true);
  561. ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
  562. nullptr, VK_RValue);
  563. // C11 6.3.2.1p2:
  564. // ... if the lvalue has atomic type, the value has the non-atomic version
  565. // of the type of the lvalue ...
  566. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  567. T = Atomic->getValueType().getUnqualifiedType();
  568. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  569. nullptr, VK_RValue);
  570. }
  571. return Res;
  572. }
  573. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
  574. ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
  575. if (Res.isInvalid())
  576. return ExprError();
  577. Res = DefaultLvalueConversion(Res.get());
  578. if (Res.isInvalid())
  579. return ExprError();
  580. return Res;
  581. }
  582. /// CallExprUnaryConversions - a special case of an unary conversion
  583. /// performed on a function designator of a call expression.
  584. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  585. QualType Ty = E->getType();
  586. ExprResult Res = E;
  587. // Only do implicit cast for a function type, but not for a pointer
  588. // to function type.
  589. if (Ty->isFunctionType()) {
  590. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  591. CK_FunctionToPointerDecay).get();
  592. if (Res.isInvalid())
  593. return ExprError();
  594. }
  595. Res = DefaultLvalueConversion(Res.get());
  596. if (Res.isInvalid())
  597. return ExprError();
  598. return Res.get();
  599. }
  600. /// UsualUnaryConversions - Performs various conversions that are common to most
  601. /// operators (C99 6.3). The conversions of array and function types are
  602. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  603. /// apply if the array is an argument to the sizeof or address (&) operators.
  604. /// In these instances, this routine should *not* be called.
  605. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  606. // First, convert to an r-value.
  607. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  608. if (Res.isInvalid())
  609. return ExprError();
  610. E = Res.get();
  611. QualType Ty = E->getType();
  612. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  613. // Half FP have to be promoted to float unless it is natively supported
  614. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  615. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  616. // Try to perform integral promotions if the object has a theoretically
  617. // promotable type.
  618. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  619. // C99 6.3.1.1p2:
  620. //
  621. // The following may be used in an expression wherever an int or
  622. // unsigned int may be used:
  623. // - an object or expression with an integer type whose integer
  624. // conversion rank is less than or equal to the rank of int
  625. // and unsigned int.
  626. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  627. //
  628. // If an int can represent all values of the original type, the
  629. // value is converted to an int; otherwise, it is converted to an
  630. // unsigned int. These are called the integer promotions. All
  631. // other types are unchanged by the integer promotions.
  632. QualType PTy = Context.isPromotableBitField(E);
  633. if (!PTy.isNull()) {
  634. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  635. return E;
  636. }
  637. if (Ty->isPromotableIntegerType()) {
  638. QualType PT = Context.getPromotedIntegerType(Ty);
  639. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  640. return E;
  641. }
  642. }
  643. return E;
  644. }
  645. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  646. /// do not have a prototype. Arguments that have type float or __fp16
  647. /// are promoted to double. All other argument types are converted by
  648. /// UsualUnaryConversions().
  649. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  650. QualType Ty = E->getType();
  651. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  652. ExprResult Res = UsualUnaryConversions(E);
  653. if (Res.isInvalid())
  654. return ExprError();
  655. E = Res.get();
  656. // If this is a 'float' or '__fp16' (CVR qualified or typedef)
  657. // promote to double.
  658. // Note that default argument promotion applies only to float (and
  659. // half/fp16); it does not apply to _Float16.
  660. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  661. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  662. BTy->getKind() == BuiltinType::Float)) {
  663. if (getLangOpts().OpenCL &&
  664. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  665. if (BTy->getKind() == BuiltinType::Half) {
  666. E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
  667. }
  668. } else {
  669. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  670. }
  671. }
  672. // C++ performs lvalue-to-rvalue conversion as a default argument
  673. // promotion, even on class types, but note:
  674. // C++11 [conv.lval]p2:
  675. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  676. // operand or a subexpression thereof the value contained in the
  677. // referenced object is not accessed. Otherwise, if the glvalue
  678. // has a class type, the conversion copy-initializes a temporary
  679. // of type T from the glvalue and the result of the conversion
  680. // is a prvalue for the temporary.
  681. // FIXME: add some way to gate this entire thing for correctness in
  682. // potentially potentially evaluated contexts.
  683. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  684. ExprResult Temp = PerformCopyInitialization(
  685. InitializedEntity::InitializeTemporary(E->getType()),
  686. E->getExprLoc(), E);
  687. if (Temp.isInvalid())
  688. return ExprError();
  689. E = Temp.get();
  690. }
  691. return E;
  692. }
  693. /// Determine the degree of POD-ness for an expression.
  694. /// Incomplete types are considered POD, since this check can be performed
  695. /// when we're in an unevaluated context.
  696. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  697. if (Ty->isIncompleteType()) {
  698. // C++11 [expr.call]p7:
  699. // After these conversions, if the argument does not have arithmetic,
  700. // enumeration, pointer, pointer to member, or class type, the program
  701. // is ill-formed.
  702. //
  703. // Since we've already performed array-to-pointer and function-to-pointer
  704. // decay, the only such type in C++ is cv void. This also handles
  705. // initializer lists as variadic arguments.
  706. if (Ty->isVoidType())
  707. return VAK_Invalid;
  708. if (Ty->isObjCObjectType())
  709. return VAK_Invalid;
  710. return VAK_Valid;
  711. }
  712. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  713. return VAK_Invalid;
  714. if (Ty.isCXX98PODType(Context))
  715. return VAK_Valid;
  716. // C++11 [expr.call]p7:
  717. // Passing a potentially-evaluated argument of class type (Clause 9)
  718. // having a non-trivial copy constructor, a non-trivial move constructor,
  719. // or a non-trivial destructor, with no corresponding parameter,
  720. // is conditionally-supported with implementation-defined semantics.
  721. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  722. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  723. if (!Record->hasNonTrivialCopyConstructor() &&
  724. !Record->hasNonTrivialMoveConstructor() &&
  725. !Record->hasNonTrivialDestructor())
  726. return VAK_ValidInCXX11;
  727. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  728. return VAK_Valid;
  729. if (Ty->isObjCObjectType())
  730. return VAK_Invalid;
  731. if (getLangOpts().MSVCCompat)
  732. return VAK_MSVCUndefined;
  733. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  734. // permitted to reject them. We should consider doing so.
  735. return VAK_Undefined;
  736. }
  737. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  738. // Don't allow one to pass an Objective-C interface to a vararg.
  739. const QualType &Ty = E->getType();
  740. VarArgKind VAK = isValidVarArgType(Ty);
  741. // Complain about passing non-POD types through varargs.
  742. switch (VAK) {
  743. case VAK_ValidInCXX11:
  744. DiagRuntimeBehavior(
  745. E->getBeginLoc(), nullptr,
  746. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
  747. LLVM_FALLTHROUGH;
  748. case VAK_Valid:
  749. if (Ty->isRecordType()) {
  750. // This is unlikely to be what the user intended. If the class has a
  751. // 'c_str' member function, the user probably meant to call that.
  752. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  753. PDiag(diag::warn_pass_class_arg_to_vararg)
  754. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  755. }
  756. break;
  757. case VAK_Undefined:
  758. case VAK_MSVCUndefined:
  759. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  760. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  761. << getLangOpts().CPlusPlus11 << Ty << CT);
  762. break;
  763. case VAK_Invalid:
  764. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  765. Diag(E->getBeginLoc(),
  766. diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
  767. << Ty << CT;
  768. else if (Ty->isObjCObjectType())
  769. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  770. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  771. << Ty << CT);
  772. else
  773. Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
  774. << isa<InitListExpr>(E) << Ty << CT;
  775. break;
  776. }
  777. }
  778. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  779. /// will create a trap if the resulting type is not a POD type.
  780. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  781. FunctionDecl *FDecl) {
  782. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  783. // Strip the unbridged-cast placeholder expression off, if applicable.
  784. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  785. (CT == VariadicMethod ||
  786. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  787. E = stripARCUnbridgedCast(E);
  788. // Otherwise, do normal placeholder checking.
  789. } else {
  790. ExprResult ExprRes = CheckPlaceholderExpr(E);
  791. if (ExprRes.isInvalid())
  792. return ExprError();
  793. E = ExprRes.get();
  794. }
  795. }
  796. ExprResult ExprRes = DefaultArgumentPromotion(E);
  797. if (ExprRes.isInvalid())
  798. return ExprError();
  799. E = ExprRes.get();
  800. // Diagnostics regarding non-POD argument types are
  801. // emitted along with format string checking in Sema::CheckFunctionCall().
  802. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  803. // Turn this into a trap.
  804. CXXScopeSpec SS;
  805. SourceLocation TemplateKWLoc;
  806. UnqualifiedId Name;
  807. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  808. E->getBeginLoc());
  809. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
  810. /*HasTrailingLParen=*/true,
  811. /*IsAddressOfOperand=*/false);
  812. if (TrapFn.isInvalid())
  813. return ExprError();
  814. ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
  815. None, E->getEndLoc());
  816. if (Call.isInvalid())
  817. return ExprError();
  818. ExprResult Comma =
  819. ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
  820. if (Comma.isInvalid())
  821. return ExprError();
  822. return Comma.get();
  823. }
  824. if (!getLangOpts().CPlusPlus &&
  825. RequireCompleteType(E->getExprLoc(), E->getType(),
  826. diag::err_call_incomplete_argument))
  827. return ExprError();
  828. return E;
  829. }
  830. /// Converts an integer to complex float type. Helper function of
  831. /// UsualArithmeticConversions()
  832. ///
  833. /// \return false if the integer expression is an integer type and is
  834. /// successfully converted to the complex type.
  835. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  836. ExprResult &ComplexExpr,
  837. QualType IntTy,
  838. QualType ComplexTy,
  839. bool SkipCast) {
  840. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  841. if (SkipCast) return false;
  842. if (IntTy->isIntegerType()) {
  843. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  844. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  845. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  846. CK_FloatingRealToComplex);
  847. } else {
  848. assert(IntTy->isComplexIntegerType());
  849. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  850. CK_IntegralComplexToFloatingComplex);
  851. }
  852. return false;
  853. }
  854. /// Handle arithmetic conversion with complex types. Helper function of
  855. /// UsualArithmeticConversions()
  856. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  857. ExprResult &RHS, QualType LHSType,
  858. QualType RHSType,
  859. bool IsCompAssign) {
  860. // if we have an integer operand, the result is the complex type.
  861. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  862. /*skipCast*/false))
  863. return LHSType;
  864. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  865. /*skipCast*/IsCompAssign))
  866. return RHSType;
  867. // This handles complex/complex, complex/float, or float/complex.
  868. // When both operands are complex, the shorter operand is converted to the
  869. // type of the longer, and that is the type of the result. This corresponds
  870. // to what is done when combining two real floating-point operands.
  871. // The fun begins when size promotion occur across type domains.
  872. // From H&S 6.3.4: When one operand is complex and the other is a real
  873. // floating-point type, the less precise type is converted, within it's
  874. // real or complex domain, to the precision of the other type. For example,
  875. // when combining a "long double" with a "double _Complex", the
  876. // "double _Complex" is promoted to "long double _Complex".
  877. // Compute the rank of the two types, regardless of whether they are complex.
  878. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  879. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  880. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  881. QualType LHSElementType =
  882. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  883. QualType RHSElementType =
  884. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  885. QualType ResultType = S.Context.getComplexType(LHSElementType);
  886. if (Order < 0) {
  887. // Promote the precision of the LHS if not an assignment.
  888. ResultType = S.Context.getComplexType(RHSElementType);
  889. if (!IsCompAssign) {
  890. if (LHSComplexType)
  891. LHS =
  892. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  893. else
  894. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  895. }
  896. } else if (Order > 0) {
  897. // Promote the precision of the RHS.
  898. if (RHSComplexType)
  899. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  900. else
  901. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  902. }
  903. return ResultType;
  904. }
  905. /// Handle arithmetic conversion from integer to float. Helper function
  906. /// of UsualArithmeticConversions()
  907. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  908. ExprResult &IntExpr,
  909. QualType FloatTy, QualType IntTy,
  910. bool ConvertFloat, bool ConvertInt) {
  911. if (IntTy->isIntegerType()) {
  912. if (ConvertInt)
  913. // Convert intExpr to the lhs floating point type.
  914. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  915. CK_IntegralToFloating);
  916. return FloatTy;
  917. }
  918. // Convert both sides to the appropriate complex float.
  919. assert(IntTy->isComplexIntegerType());
  920. QualType result = S.Context.getComplexType(FloatTy);
  921. // _Complex int -> _Complex float
  922. if (ConvertInt)
  923. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  924. CK_IntegralComplexToFloatingComplex);
  925. // float -> _Complex float
  926. if (ConvertFloat)
  927. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  928. CK_FloatingRealToComplex);
  929. return result;
  930. }
  931. /// Handle arithmethic conversion with floating point types. Helper
  932. /// function of UsualArithmeticConversions()
  933. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  934. ExprResult &RHS, QualType LHSType,
  935. QualType RHSType, bool IsCompAssign) {
  936. bool LHSFloat = LHSType->isRealFloatingType();
  937. bool RHSFloat = RHSType->isRealFloatingType();
  938. // If we have two real floating types, convert the smaller operand
  939. // to the bigger result.
  940. if (LHSFloat && RHSFloat) {
  941. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  942. if (order > 0) {
  943. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  944. return LHSType;
  945. }
  946. assert(order < 0 && "illegal float comparison");
  947. if (!IsCompAssign)
  948. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  949. return RHSType;
  950. }
  951. if (LHSFloat) {
  952. // Half FP has to be promoted to float unless it is natively supported
  953. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  954. LHSType = S.Context.FloatTy;
  955. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  956. /*convertFloat=*/!IsCompAssign,
  957. /*convertInt=*/ true);
  958. }
  959. assert(RHSFloat);
  960. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  961. /*convertInt=*/ true,
  962. /*convertFloat=*/!IsCompAssign);
  963. }
  964. /// Diagnose attempts to convert between __float128 and long double if
  965. /// there is no support for such conversion. Helper function of
  966. /// UsualArithmeticConversions().
  967. static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
  968. QualType RHSType) {
  969. /* No issue converting if at least one of the types is not a floating point
  970. type or the two types have the same rank.
  971. */
  972. if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
  973. S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
  974. return false;
  975. assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
  976. "The remaining types must be floating point types.");
  977. auto *LHSComplex = LHSType->getAs<ComplexType>();
  978. auto *RHSComplex = RHSType->getAs<ComplexType>();
  979. QualType LHSElemType = LHSComplex ?
  980. LHSComplex->getElementType() : LHSType;
  981. QualType RHSElemType = RHSComplex ?
  982. RHSComplex->getElementType() : RHSType;
  983. // No issue if the two types have the same representation
  984. if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
  985. &S.Context.getFloatTypeSemantics(RHSElemType))
  986. return false;
  987. bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
  988. RHSElemType == S.Context.LongDoubleTy);
  989. Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
  990. RHSElemType == S.Context.Float128Ty);
  991. // We've handled the situation where __float128 and long double have the same
  992. // representation. We allow all conversions for all possible long double types
  993. // except PPC's double double.
  994. return Float128AndLongDouble &&
  995. (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
  996. &llvm::APFloat::PPCDoubleDouble());
  997. }
  998. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  999. namespace {
  1000. /// These helper callbacks are placed in an anonymous namespace to
  1001. /// permit their use as function template parameters.
  1002. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  1003. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  1004. }
  1005. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  1006. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  1007. CK_IntegralComplexCast);
  1008. }
  1009. }
  1010. /// Handle integer arithmetic conversions. Helper function of
  1011. /// UsualArithmeticConversions()
  1012. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  1013. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  1014. ExprResult &RHS, QualType LHSType,
  1015. QualType RHSType, bool IsCompAssign) {
  1016. // The rules for this case are in C99 6.3.1.8
  1017. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  1018. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  1019. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  1020. if (LHSSigned == RHSSigned) {
  1021. // Same signedness; use the higher-ranked type
  1022. if (order >= 0) {
  1023. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1024. return LHSType;
  1025. } else if (!IsCompAssign)
  1026. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1027. return RHSType;
  1028. } else if (order != (LHSSigned ? 1 : -1)) {
  1029. // The unsigned type has greater than or equal rank to the
  1030. // signed type, so use the unsigned type
  1031. if (RHSSigned) {
  1032. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1033. return LHSType;
  1034. } else if (!IsCompAssign)
  1035. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1036. return RHSType;
  1037. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1038. // The two types are different widths; if we are here, that
  1039. // means the signed type is larger than the unsigned type, so
  1040. // use the signed type.
  1041. if (LHSSigned) {
  1042. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1043. return LHSType;
  1044. } else if (!IsCompAssign)
  1045. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1046. return RHSType;
  1047. } else {
  1048. // The signed type is higher-ranked than the unsigned type,
  1049. // but isn't actually any bigger (like unsigned int and long
  1050. // on most 32-bit systems). Use the unsigned type corresponding
  1051. // to the signed type.
  1052. QualType result =
  1053. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1054. RHS = (*doRHSCast)(S, RHS.get(), result);
  1055. if (!IsCompAssign)
  1056. LHS = (*doLHSCast)(S, LHS.get(), result);
  1057. return result;
  1058. }
  1059. }
  1060. /// Handle conversions with GCC complex int extension. Helper function
  1061. /// of UsualArithmeticConversions()
  1062. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1063. ExprResult &RHS, QualType LHSType,
  1064. QualType RHSType,
  1065. bool IsCompAssign) {
  1066. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1067. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1068. if (LHSComplexInt && RHSComplexInt) {
  1069. QualType LHSEltType = LHSComplexInt->getElementType();
  1070. QualType RHSEltType = RHSComplexInt->getElementType();
  1071. QualType ScalarType =
  1072. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1073. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1074. return S.Context.getComplexType(ScalarType);
  1075. }
  1076. if (LHSComplexInt) {
  1077. QualType LHSEltType = LHSComplexInt->getElementType();
  1078. QualType ScalarType =
  1079. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1080. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1081. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1082. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1083. CK_IntegralRealToComplex);
  1084. return ComplexType;
  1085. }
  1086. assert(RHSComplexInt);
  1087. QualType RHSEltType = RHSComplexInt->getElementType();
  1088. QualType ScalarType =
  1089. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1090. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1091. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1092. if (!IsCompAssign)
  1093. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1094. CK_IntegralRealToComplex);
  1095. return ComplexType;
  1096. }
  1097. /// Return the rank of a given fixed point or integer type. The value itself
  1098. /// doesn't matter, but the values must be increasing with proper increasing
  1099. /// rank as described in N1169 4.1.1.
  1100. static unsigned GetFixedPointRank(QualType Ty) {
  1101. const auto *BTy = Ty->getAs<BuiltinType>();
  1102. assert(BTy && "Expected a builtin type.");
  1103. switch (BTy->getKind()) {
  1104. case BuiltinType::ShortFract:
  1105. case BuiltinType::UShortFract:
  1106. case BuiltinType::SatShortFract:
  1107. case BuiltinType::SatUShortFract:
  1108. return 1;
  1109. case BuiltinType::Fract:
  1110. case BuiltinType::UFract:
  1111. case BuiltinType::SatFract:
  1112. case BuiltinType::SatUFract:
  1113. return 2;
  1114. case BuiltinType::LongFract:
  1115. case BuiltinType::ULongFract:
  1116. case BuiltinType::SatLongFract:
  1117. case BuiltinType::SatULongFract:
  1118. return 3;
  1119. case BuiltinType::ShortAccum:
  1120. case BuiltinType::UShortAccum:
  1121. case BuiltinType::SatShortAccum:
  1122. case BuiltinType::SatUShortAccum:
  1123. return 4;
  1124. case BuiltinType::Accum:
  1125. case BuiltinType::UAccum:
  1126. case BuiltinType::SatAccum:
  1127. case BuiltinType::SatUAccum:
  1128. return 5;
  1129. case BuiltinType::LongAccum:
  1130. case BuiltinType::ULongAccum:
  1131. case BuiltinType::SatLongAccum:
  1132. case BuiltinType::SatULongAccum:
  1133. return 6;
  1134. default:
  1135. if (BTy->isInteger())
  1136. return 0;
  1137. llvm_unreachable("Unexpected fixed point or integer type");
  1138. }
  1139. }
  1140. /// handleFixedPointConversion - Fixed point operations between fixed
  1141. /// point types and integers or other fixed point types do not fall under
  1142. /// usual arithmetic conversion since these conversions could result in loss
  1143. /// of precsision (N1169 4.1.4). These operations should be calculated with
  1144. /// the full precision of their result type (N1169 4.1.6.2.1).
  1145. static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
  1146. QualType RHSTy) {
  1147. assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
  1148. "Expected at least one of the operands to be a fixed point type");
  1149. assert((LHSTy->isFixedPointOrIntegerType() ||
  1150. RHSTy->isFixedPointOrIntegerType()) &&
  1151. "Special fixed point arithmetic operation conversions are only "
  1152. "applied to ints or other fixed point types");
  1153. // If one operand has signed fixed-point type and the other operand has
  1154. // unsigned fixed-point type, then the unsigned fixed-point operand is
  1155. // converted to its corresponding signed fixed-point type and the resulting
  1156. // type is the type of the converted operand.
  1157. if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
  1158. LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
  1159. else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
  1160. RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
  1161. // The result type is the type with the highest rank, whereby a fixed-point
  1162. // conversion rank is always greater than an integer conversion rank; if the
  1163. // type of either of the operands is a saturating fixedpoint type, the result
  1164. // type shall be the saturating fixed-point type corresponding to the type
  1165. // with the highest rank; the resulting value is converted (taking into
  1166. // account rounding and overflow) to the precision of the resulting type.
  1167. // Same ranks between signed and unsigned types are resolved earlier, so both
  1168. // types are either signed or both unsigned at this point.
  1169. unsigned LHSTyRank = GetFixedPointRank(LHSTy);
  1170. unsigned RHSTyRank = GetFixedPointRank(RHSTy);
  1171. QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
  1172. if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
  1173. ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
  1174. return ResultTy;
  1175. }
  1176. /// UsualArithmeticConversions - Performs various conversions that are common to
  1177. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1178. /// routine returns the first non-arithmetic type found. The client is
  1179. /// responsible for emitting appropriate error diagnostics.
  1180. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1181. bool IsCompAssign) {
  1182. if (!IsCompAssign) {
  1183. LHS = UsualUnaryConversions(LHS.get());
  1184. if (LHS.isInvalid())
  1185. return QualType();
  1186. }
  1187. RHS = UsualUnaryConversions(RHS.get());
  1188. if (RHS.isInvalid())
  1189. return QualType();
  1190. // For conversion purposes, we ignore any qualifiers.
  1191. // For example, "const float" and "float" are equivalent.
  1192. QualType LHSType =
  1193. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1194. QualType RHSType =
  1195. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1196. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1197. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1198. LHSType = AtomicLHS->getValueType();
  1199. // If both types are identical, no conversion is needed.
  1200. if (LHSType == RHSType)
  1201. return LHSType;
  1202. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1203. // The caller can deal with this (e.g. pointer + int).
  1204. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1205. return QualType();
  1206. // Apply unary and bitfield promotions to the LHS's type.
  1207. QualType LHSUnpromotedType = LHSType;
  1208. if (LHSType->isPromotableIntegerType())
  1209. LHSType = Context.getPromotedIntegerType(LHSType);
  1210. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1211. if (!LHSBitfieldPromoteTy.isNull())
  1212. LHSType = LHSBitfieldPromoteTy;
  1213. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  1214. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1215. // If both types are identical, no conversion is needed.
  1216. if (LHSType == RHSType)
  1217. return LHSType;
  1218. // At this point, we have two different arithmetic types.
  1219. // Diagnose attempts to convert between __float128 and long double where
  1220. // such conversions currently can't be handled.
  1221. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  1222. return QualType();
  1223. // Handle complex types first (C99 6.3.1.8p1).
  1224. if (LHSType->isComplexType() || RHSType->isComplexType())
  1225. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1226. IsCompAssign);
  1227. // Now handle "real" floating types (i.e. float, double, long double).
  1228. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1229. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1230. IsCompAssign);
  1231. // Handle GCC complex int extension.
  1232. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1233. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1234. IsCompAssign);
  1235. if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
  1236. return handleFixedPointConversion(*this, LHSType, RHSType);
  1237. // Finally, we have two differing integer types.
  1238. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1239. (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
  1240. }
  1241. //===----------------------------------------------------------------------===//
  1242. // Semantic Analysis for various Expression Types
  1243. //===----------------------------------------------------------------------===//
  1244. ExprResult
  1245. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1246. SourceLocation DefaultLoc,
  1247. SourceLocation RParenLoc,
  1248. Expr *ControllingExpr,
  1249. ArrayRef<ParsedType> ArgTypes,
  1250. ArrayRef<Expr *> ArgExprs) {
  1251. unsigned NumAssocs = ArgTypes.size();
  1252. assert(NumAssocs == ArgExprs.size());
  1253. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1254. for (unsigned i = 0; i < NumAssocs; ++i) {
  1255. if (ArgTypes[i])
  1256. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1257. else
  1258. Types[i] = nullptr;
  1259. }
  1260. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1261. ControllingExpr,
  1262. llvm::makeArrayRef(Types, NumAssocs),
  1263. ArgExprs);
  1264. delete [] Types;
  1265. return ER;
  1266. }
  1267. ExprResult
  1268. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1269. SourceLocation DefaultLoc,
  1270. SourceLocation RParenLoc,
  1271. Expr *ControllingExpr,
  1272. ArrayRef<TypeSourceInfo *> Types,
  1273. ArrayRef<Expr *> Exprs) {
  1274. unsigned NumAssocs = Types.size();
  1275. assert(NumAssocs == Exprs.size());
  1276. // Decay and strip qualifiers for the controlling expression type, and handle
  1277. // placeholder type replacement. See committee discussion from WG14 DR423.
  1278. {
  1279. EnterExpressionEvaluationContext Unevaluated(
  1280. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  1281. ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
  1282. if (R.isInvalid())
  1283. return ExprError();
  1284. ControllingExpr = R.get();
  1285. }
  1286. // The controlling expression is an unevaluated operand, so side effects are
  1287. // likely unintended.
  1288. if (!inTemplateInstantiation() &&
  1289. ControllingExpr->HasSideEffects(Context, false))
  1290. Diag(ControllingExpr->getExprLoc(),
  1291. diag::warn_side_effects_unevaluated_context);
  1292. bool TypeErrorFound = false,
  1293. IsResultDependent = ControllingExpr->isTypeDependent(),
  1294. ContainsUnexpandedParameterPack
  1295. = ControllingExpr->containsUnexpandedParameterPack();
  1296. for (unsigned i = 0; i < NumAssocs; ++i) {
  1297. if (Exprs[i]->containsUnexpandedParameterPack())
  1298. ContainsUnexpandedParameterPack = true;
  1299. if (Types[i]) {
  1300. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1301. ContainsUnexpandedParameterPack = true;
  1302. if (Types[i]->getType()->isDependentType()) {
  1303. IsResultDependent = true;
  1304. } else {
  1305. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1306. // complete object type other than a variably modified type."
  1307. unsigned D = 0;
  1308. if (Types[i]->getType()->isIncompleteType())
  1309. D = diag::err_assoc_type_incomplete;
  1310. else if (!Types[i]->getType()->isObjectType())
  1311. D = diag::err_assoc_type_nonobject;
  1312. else if (Types[i]->getType()->isVariablyModifiedType())
  1313. D = diag::err_assoc_type_variably_modified;
  1314. if (D != 0) {
  1315. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1316. << Types[i]->getTypeLoc().getSourceRange()
  1317. << Types[i]->getType();
  1318. TypeErrorFound = true;
  1319. }
  1320. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1321. // selection shall specify compatible types."
  1322. for (unsigned j = i+1; j < NumAssocs; ++j)
  1323. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1324. Context.typesAreCompatible(Types[i]->getType(),
  1325. Types[j]->getType())) {
  1326. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1327. diag::err_assoc_compatible_types)
  1328. << Types[j]->getTypeLoc().getSourceRange()
  1329. << Types[j]->getType()
  1330. << Types[i]->getType();
  1331. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1332. diag::note_compat_assoc)
  1333. << Types[i]->getTypeLoc().getSourceRange()
  1334. << Types[i]->getType();
  1335. TypeErrorFound = true;
  1336. }
  1337. }
  1338. }
  1339. }
  1340. if (TypeErrorFound)
  1341. return ExprError();
  1342. // If we determined that the generic selection is result-dependent, don't
  1343. // try to compute the result expression.
  1344. if (IsResultDependent)
  1345. return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
  1346. Exprs, DefaultLoc, RParenLoc,
  1347. ContainsUnexpandedParameterPack);
  1348. SmallVector<unsigned, 1> CompatIndices;
  1349. unsigned DefaultIndex = -1U;
  1350. for (unsigned i = 0; i < NumAssocs; ++i) {
  1351. if (!Types[i])
  1352. DefaultIndex = i;
  1353. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1354. Types[i]->getType()))
  1355. CompatIndices.push_back(i);
  1356. }
  1357. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1358. // type compatible with at most one of the types named in its generic
  1359. // association list."
  1360. if (CompatIndices.size() > 1) {
  1361. // We strip parens here because the controlling expression is typically
  1362. // parenthesized in macro definitions.
  1363. ControllingExpr = ControllingExpr->IgnoreParens();
  1364. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
  1365. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1366. << (unsigned)CompatIndices.size();
  1367. for (unsigned I : CompatIndices) {
  1368. Diag(Types[I]->getTypeLoc().getBeginLoc(),
  1369. diag::note_compat_assoc)
  1370. << Types[I]->getTypeLoc().getSourceRange()
  1371. << Types[I]->getType();
  1372. }
  1373. return ExprError();
  1374. }
  1375. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1376. // its controlling expression shall have type compatible with exactly one of
  1377. // the types named in its generic association list."
  1378. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1379. // We strip parens here because the controlling expression is typically
  1380. // parenthesized in macro definitions.
  1381. ControllingExpr = ControllingExpr->IgnoreParens();
  1382. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
  1383. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1384. return ExprError();
  1385. }
  1386. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1387. // type name that is compatible with the type of the controlling expression,
  1388. // then the result expression of the generic selection is the expression
  1389. // in that generic association. Otherwise, the result expression of the
  1390. // generic selection is the expression in the default generic association."
  1391. unsigned ResultIndex =
  1392. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1393. return GenericSelectionExpr::Create(
  1394. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1395. ContainsUnexpandedParameterPack, ResultIndex);
  1396. }
  1397. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1398. /// location of the token and the offset of the ud-suffix within it.
  1399. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1400. unsigned Offset) {
  1401. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1402. S.getLangOpts());
  1403. }
  1404. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1405. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1406. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1407. IdentifierInfo *UDSuffix,
  1408. SourceLocation UDSuffixLoc,
  1409. ArrayRef<Expr*> Args,
  1410. SourceLocation LitEndLoc) {
  1411. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1412. QualType ArgTy[2];
  1413. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1414. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1415. if (ArgTy[ArgIdx]->isArrayType())
  1416. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1417. }
  1418. DeclarationName OpName =
  1419. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1420. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1421. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1422. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1423. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1424. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1425. /*AllowStringTemplate*/ false,
  1426. /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
  1427. return ExprError();
  1428. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1429. }
  1430. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1431. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1432. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1433. /// multiple tokens. However, the common case is that StringToks points to one
  1434. /// string.
  1435. ///
  1436. ExprResult
  1437. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1438. assert(!StringToks.empty() && "Must have at least one string!");
  1439. StringLiteralParser Literal(StringToks, PP);
  1440. if (Literal.hadError)
  1441. return ExprError();
  1442. SmallVector<SourceLocation, 4> StringTokLocs;
  1443. for (const Token &Tok : StringToks)
  1444. StringTokLocs.push_back(Tok.getLocation());
  1445. QualType CharTy = Context.CharTy;
  1446. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1447. if (Literal.isWide()) {
  1448. CharTy = Context.getWideCharType();
  1449. Kind = StringLiteral::Wide;
  1450. } else if (Literal.isUTF8()) {
  1451. if (getLangOpts().Char8)
  1452. CharTy = Context.Char8Ty;
  1453. Kind = StringLiteral::UTF8;
  1454. } else if (Literal.isUTF16()) {
  1455. CharTy = Context.Char16Ty;
  1456. Kind = StringLiteral::UTF16;
  1457. } else if (Literal.isUTF32()) {
  1458. CharTy = Context.Char32Ty;
  1459. Kind = StringLiteral::UTF32;
  1460. } else if (Literal.isPascal()) {
  1461. CharTy = Context.UnsignedCharTy;
  1462. }
  1463. // Warn on initializing an array of char from a u8 string literal; this
  1464. // becomes ill-formed in C++2a.
  1465. if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
  1466. !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
  1467. Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
  1468. // Create removals for all 'u8' prefixes in the string literal(s). This
  1469. // ensures C++2a compatibility (but may change the program behavior when
  1470. // built by non-Clang compilers for which the execution character set is
  1471. // not always UTF-8).
  1472. auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
  1473. SourceLocation RemovalDiagLoc;
  1474. for (const Token &Tok : StringToks) {
  1475. if (Tok.getKind() == tok::utf8_string_literal) {
  1476. if (RemovalDiagLoc.isInvalid())
  1477. RemovalDiagLoc = Tok.getLocation();
  1478. RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
  1479. Tok.getLocation(),
  1480. Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
  1481. getSourceManager(), getLangOpts())));
  1482. }
  1483. }
  1484. Diag(RemovalDiagLoc, RemovalDiag);
  1485. }
  1486. QualType StrTy =
  1487. Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
  1488. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1489. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1490. Kind, Literal.Pascal, StrTy,
  1491. &StringTokLocs[0],
  1492. StringTokLocs.size());
  1493. if (Literal.getUDSuffix().empty())
  1494. return Lit;
  1495. // We're building a user-defined literal.
  1496. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1497. SourceLocation UDSuffixLoc =
  1498. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1499. Literal.getUDSuffixOffset());
  1500. // Make sure we're allowed user-defined literals here.
  1501. if (!UDLScope)
  1502. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1503. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1504. // operator "" X (str, len)
  1505. QualType SizeType = Context.getSizeType();
  1506. DeclarationName OpName =
  1507. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1508. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1509. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1510. QualType ArgTy[] = {
  1511. Context.getArrayDecayedType(StrTy), SizeType
  1512. };
  1513. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1514. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1515. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1516. /*AllowStringTemplate*/ true,
  1517. /*DiagnoseMissing*/ true)) {
  1518. case LOLR_Cooked: {
  1519. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1520. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1521. StringTokLocs[0]);
  1522. Expr *Args[] = { Lit, LenArg };
  1523. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1524. }
  1525. case LOLR_StringTemplate: {
  1526. TemplateArgumentListInfo ExplicitArgs;
  1527. unsigned CharBits = Context.getIntWidth(CharTy);
  1528. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1529. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1530. TemplateArgument TypeArg(CharTy);
  1531. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1532. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1533. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1534. Value = Lit->getCodeUnit(I);
  1535. TemplateArgument Arg(Context, Value, CharTy);
  1536. TemplateArgumentLocInfo ArgInfo;
  1537. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1538. }
  1539. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1540. &ExplicitArgs);
  1541. }
  1542. case LOLR_Raw:
  1543. case LOLR_Template:
  1544. case LOLR_ErrorNoDiagnostic:
  1545. llvm_unreachable("unexpected literal operator lookup result");
  1546. case LOLR_Error:
  1547. return ExprError();
  1548. }
  1549. llvm_unreachable("unexpected literal operator lookup result");
  1550. }
  1551. ExprResult
  1552. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1553. SourceLocation Loc,
  1554. const CXXScopeSpec *SS) {
  1555. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1556. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1557. }
  1558. /// BuildDeclRefExpr - Build an expression that references a
  1559. /// declaration that does not require a closure capture.
  1560. ExprResult
  1561. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1562. const DeclarationNameInfo &NameInfo,
  1563. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1564. const TemplateArgumentListInfo *TemplateArgs) {
  1565. bool RefersToCapturedVariable =
  1566. isa<VarDecl>(D) &&
  1567. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1568. DeclRefExpr *E;
  1569. if (isa<VarTemplateSpecializationDecl>(D)) {
  1570. VarTemplateSpecializationDecl *VarSpec =
  1571. cast<VarTemplateSpecializationDecl>(D);
  1572. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1573. : NestedNameSpecifierLoc(),
  1574. VarSpec->getTemplateKeywordLoc(), D,
  1575. RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
  1576. FoundD, TemplateArgs);
  1577. } else {
  1578. assert(!TemplateArgs && "No template arguments for non-variable"
  1579. " template specialization references");
  1580. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1581. : NestedNameSpecifierLoc(),
  1582. SourceLocation(), D, RefersToCapturedVariable,
  1583. NameInfo, Ty, VK, FoundD);
  1584. }
  1585. MarkDeclRefReferenced(E);
  1586. if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
  1587. Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
  1588. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
  1589. getCurFunction()->recordUseOfWeak(E);
  1590. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1591. if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
  1592. FD = IFD->getAnonField();
  1593. if (FD) {
  1594. UnusedPrivateFields.remove(FD);
  1595. // Just in case we're building an illegal pointer-to-member.
  1596. if (FD->isBitField())
  1597. E->setObjectKind(OK_BitField);
  1598. }
  1599. // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
  1600. // designates a bit-field.
  1601. if (auto *BD = dyn_cast<BindingDecl>(D))
  1602. if (auto *BE = BD->getBinding())
  1603. E->setObjectKind(BE->getObjectKind());
  1604. return E;
  1605. }
  1606. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1607. /// possibly a list of template arguments.
  1608. ///
  1609. /// If this produces template arguments, it is permitted to call
  1610. /// DecomposeTemplateName.
  1611. ///
  1612. /// This actually loses a lot of source location information for
  1613. /// non-standard name kinds; we should consider preserving that in
  1614. /// some way.
  1615. void
  1616. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1617. TemplateArgumentListInfo &Buffer,
  1618. DeclarationNameInfo &NameInfo,
  1619. const TemplateArgumentListInfo *&TemplateArgs) {
  1620. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
  1621. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1622. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1623. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1624. Id.TemplateId->NumArgs);
  1625. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1626. TemplateName TName = Id.TemplateId->Template.get();
  1627. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1628. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1629. TemplateArgs = &Buffer;
  1630. } else {
  1631. NameInfo = GetNameFromUnqualifiedId(Id);
  1632. TemplateArgs = nullptr;
  1633. }
  1634. }
  1635. static void emitEmptyLookupTypoDiagnostic(
  1636. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1637. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1638. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1639. DeclContext *Ctx =
  1640. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1641. if (!TC) {
  1642. // Emit a special diagnostic for failed member lookups.
  1643. // FIXME: computing the declaration context might fail here (?)
  1644. if (Ctx)
  1645. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1646. << SS.getRange();
  1647. else
  1648. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1649. return;
  1650. }
  1651. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1652. bool DroppedSpecifier =
  1653. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1654. unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
  1655. ? diag::note_implicit_param_decl
  1656. : diag::note_previous_decl;
  1657. if (!Ctx)
  1658. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1659. SemaRef.PDiag(NoteID));
  1660. else
  1661. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1662. << Typo << Ctx << DroppedSpecifier
  1663. << SS.getRange(),
  1664. SemaRef.PDiag(NoteID));
  1665. }
  1666. /// Diagnose an empty lookup.
  1667. ///
  1668. /// \return false if new lookup candidates were found
  1669. bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1670. CorrectionCandidateCallback &CCC,
  1671. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1672. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1673. DeclarationName Name = R.getLookupName();
  1674. unsigned diagnostic = diag::err_undeclared_var_use;
  1675. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1676. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1677. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1678. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1679. diagnostic = diag::err_undeclared_use;
  1680. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1681. }
  1682. // If the original lookup was an unqualified lookup, fake an
  1683. // unqualified lookup. This is useful when (for example) the
  1684. // original lookup would not have found something because it was a
  1685. // dependent name.
  1686. DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
  1687. while (DC) {
  1688. if (isa<CXXRecordDecl>(DC)) {
  1689. LookupQualifiedName(R, DC);
  1690. if (!R.empty()) {
  1691. // Don't give errors about ambiguities in this lookup.
  1692. R.suppressDiagnostics();
  1693. // During a default argument instantiation the CurContext points
  1694. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1695. // function parameter list, hence add an explicit check.
  1696. bool isDefaultArgument =
  1697. !CodeSynthesisContexts.empty() &&
  1698. CodeSynthesisContexts.back().Kind ==
  1699. CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
  1700. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1701. bool isInstance = CurMethod &&
  1702. CurMethod->isInstance() &&
  1703. DC == CurMethod->getParent() && !isDefaultArgument;
  1704. // Give a code modification hint to insert 'this->'.
  1705. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1706. // Actually quite difficult!
  1707. if (getLangOpts().MSVCCompat)
  1708. diagnostic = diag::ext_found_via_dependent_bases_lookup;
  1709. if (isInstance) {
  1710. Diag(R.getNameLoc(), diagnostic) << Name
  1711. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1712. CheckCXXThisCapture(R.getNameLoc());
  1713. } else {
  1714. Diag(R.getNameLoc(), diagnostic) << Name;
  1715. }
  1716. // Do we really want to note all of these?
  1717. for (NamedDecl *D : R)
  1718. Diag(D->getLocation(), diag::note_dependent_var_use);
  1719. // Return true if we are inside a default argument instantiation
  1720. // and the found name refers to an instance member function, otherwise
  1721. // the function calling DiagnoseEmptyLookup will try to create an
  1722. // implicit member call and this is wrong for default argument.
  1723. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1724. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1725. return true;
  1726. }
  1727. // Tell the callee to try to recover.
  1728. return false;
  1729. }
  1730. R.clear();
  1731. }
  1732. // In Microsoft mode, if we are performing lookup from within a friend
  1733. // function definition declared at class scope then we must set
  1734. // DC to the lexical parent to be able to search into the parent
  1735. // class.
  1736. if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
  1737. cast<FunctionDecl>(DC)->getFriendObjectKind() &&
  1738. DC->getLexicalParent()->isRecord())
  1739. DC = DC->getLexicalParent();
  1740. else
  1741. DC = DC->getParent();
  1742. }
  1743. // We didn't find anything, so try to correct for a typo.
  1744. TypoCorrection Corrected;
  1745. if (S && Out) {
  1746. SourceLocation TypoLoc = R.getNameLoc();
  1747. assert(!ExplicitTemplateArgs &&
  1748. "Diagnosing an empty lookup with explicit template args!");
  1749. *Out = CorrectTypoDelayed(
  1750. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
  1751. [=](const TypoCorrection &TC) {
  1752. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1753. diagnostic, diagnostic_suggest);
  1754. },
  1755. nullptr, CTK_ErrorRecovery);
  1756. if (*Out)
  1757. return true;
  1758. } else if (S &&
  1759. (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
  1760. S, &SS, CCC, CTK_ErrorRecovery))) {
  1761. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1762. bool DroppedSpecifier =
  1763. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1764. R.setLookupName(Corrected.getCorrection());
  1765. bool AcceptableWithRecovery = false;
  1766. bool AcceptableWithoutRecovery = false;
  1767. NamedDecl *ND = Corrected.getFoundDecl();
  1768. if (ND) {
  1769. if (Corrected.isOverloaded()) {
  1770. OverloadCandidateSet OCS(R.getNameLoc(),
  1771. OverloadCandidateSet::CSK_Normal);
  1772. OverloadCandidateSet::iterator Best;
  1773. for (NamedDecl *CD : Corrected) {
  1774. if (FunctionTemplateDecl *FTD =
  1775. dyn_cast<FunctionTemplateDecl>(CD))
  1776. AddTemplateOverloadCandidate(
  1777. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1778. Args, OCS);
  1779. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  1780. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1781. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1782. Args, OCS);
  1783. }
  1784. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1785. case OR_Success:
  1786. ND = Best->FoundDecl;
  1787. Corrected.setCorrectionDecl(ND);
  1788. break;
  1789. default:
  1790. // FIXME: Arbitrarily pick the first declaration for the note.
  1791. Corrected.setCorrectionDecl(ND);
  1792. break;
  1793. }
  1794. }
  1795. R.addDecl(ND);
  1796. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1797. CXXRecordDecl *Record = nullptr;
  1798. if (Corrected.getCorrectionSpecifier()) {
  1799. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1800. Record = Ty->getAsCXXRecordDecl();
  1801. }
  1802. if (!Record)
  1803. Record = cast<CXXRecordDecl>(
  1804. ND->getDeclContext()->getRedeclContext());
  1805. R.setNamingClass(Record);
  1806. }
  1807. auto *UnderlyingND = ND->getUnderlyingDecl();
  1808. AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
  1809. isa<FunctionTemplateDecl>(UnderlyingND);
  1810. // FIXME: If we ended up with a typo for a type name or
  1811. // Objective-C class name, we're in trouble because the parser
  1812. // is in the wrong place to recover. Suggest the typo
  1813. // correction, but don't make it a fix-it since we're not going
  1814. // to recover well anyway.
  1815. AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
  1816. getAsTypeTemplateDecl(UnderlyingND) ||
  1817. isa<ObjCInterfaceDecl>(UnderlyingND);
  1818. } else {
  1819. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1820. // because we aren't able to recover.
  1821. AcceptableWithoutRecovery = true;
  1822. }
  1823. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1824. unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
  1825. ? diag::note_implicit_param_decl
  1826. : diag::note_previous_decl;
  1827. if (SS.isEmpty())
  1828. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1829. PDiag(NoteID), AcceptableWithRecovery);
  1830. else
  1831. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1832. << Name << computeDeclContext(SS, false)
  1833. << DroppedSpecifier << SS.getRange(),
  1834. PDiag(NoteID), AcceptableWithRecovery);
  1835. // Tell the callee whether to try to recover.
  1836. return !AcceptableWithRecovery;
  1837. }
  1838. }
  1839. R.clear();
  1840. // Emit a special diagnostic for failed member lookups.
  1841. // FIXME: computing the declaration context might fail here (?)
  1842. if (!SS.isEmpty()) {
  1843. Diag(R.getNameLoc(), diag::err_no_member)
  1844. << Name << computeDeclContext(SS, false)
  1845. << SS.getRange();
  1846. return true;
  1847. }
  1848. // Give up, we can't recover.
  1849. Diag(R.getNameLoc(), diagnostic) << Name;
  1850. return true;
  1851. }
  1852. /// In Microsoft mode, if we are inside a template class whose parent class has
  1853. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1854. /// assume the identifier is a member of a dependent base class. We can only
  1855. /// recover successfully in static methods, instance methods, and other contexts
  1856. /// where 'this' is available. This doesn't precisely match MSVC's
  1857. /// instantiation model, but it's close enough.
  1858. static Expr *
  1859. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1860. DeclarationNameInfo &NameInfo,
  1861. SourceLocation TemplateKWLoc,
  1862. const TemplateArgumentListInfo *TemplateArgs) {
  1863. // Only try to recover from lookup into dependent bases in static methods or
  1864. // contexts where 'this' is available.
  1865. QualType ThisType = S.getCurrentThisType();
  1866. const CXXRecordDecl *RD = nullptr;
  1867. if (!ThisType.isNull())
  1868. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1869. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1870. RD = MD->getParent();
  1871. if (!RD || !RD->hasAnyDependentBases())
  1872. return nullptr;
  1873. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1874. // is available, suggest inserting 'this->' as a fixit.
  1875. SourceLocation Loc = NameInfo.getLoc();
  1876. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1877. DB << NameInfo.getName() << RD;
  1878. if (!ThisType.isNull()) {
  1879. DB << FixItHint::CreateInsertion(Loc, "this->");
  1880. return CXXDependentScopeMemberExpr::Create(
  1881. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1882. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1883. /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
  1884. }
  1885. // Synthesize a fake NNS that points to the derived class. This will
  1886. // perform name lookup during template instantiation.
  1887. CXXScopeSpec SS;
  1888. auto *NNS =
  1889. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1890. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1891. return DependentScopeDeclRefExpr::Create(
  1892. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1893. TemplateArgs);
  1894. }
  1895. ExprResult
  1896. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1897. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1898. bool HasTrailingLParen, bool IsAddressOfOperand,
  1899. CorrectionCandidateCallback *CCC,
  1900. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1901. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1902. "cannot be direct & operand and have a trailing lparen");
  1903. if (SS.isInvalid())
  1904. return ExprError();
  1905. TemplateArgumentListInfo TemplateArgsBuffer;
  1906. // Decompose the UnqualifiedId into the following data.
  1907. DeclarationNameInfo NameInfo;
  1908. const TemplateArgumentListInfo *TemplateArgs;
  1909. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1910. DeclarationName Name = NameInfo.getName();
  1911. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1912. SourceLocation NameLoc = NameInfo.getLoc();
  1913. if (II && II->isEditorPlaceholder()) {
  1914. // FIXME: When typed placeholders are supported we can create a typed
  1915. // placeholder expression node.
  1916. return ExprError();
  1917. }
  1918. // C++ [temp.dep.expr]p3:
  1919. // An id-expression is type-dependent if it contains:
  1920. // -- an identifier that was declared with a dependent type,
  1921. // (note: handled after lookup)
  1922. // -- a template-id that is dependent,
  1923. // (note: handled in BuildTemplateIdExpr)
  1924. // -- a conversion-function-id that specifies a dependent type,
  1925. // -- a nested-name-specifier that contains a class-name that
  1926. // names a dependent type.
  1927. // Determine whether this is a member of an unknown specialization;
  1928. // we need to handle these differently.
  1929. bool DependentID = false;
  1930. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1931. Name.getCXXNameType()->isDependentType()) {
  1932. DependentID = true;
  1933. } else if (SS.isSet()) {
  1934. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1935. if (RequireCompleteDeclContext(SS, DC))
  1936. return ExprError();
  1937. } else {
  1938. DependentID = true;
  1939. }
  1940. }
  1941. if (DependentID)
  1942. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1943. IsAddressOfOperand, TemplateArgs);
  1944. // Perform the required lookup.
  1945. LookupResult R(*this, NameInfo,
  1946. (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
  1947. ? LookupObjCImplicitSelfParam
  1948. : LookupOrdinaryName);
  1949. if (TemplateKWLoc.isValid() || TemplateArgs) {
  1950. // Lookup the template name again to correctly establish the context in
  1951. // which it was found. This is really unfortunate as we already did the
  1952. // lookup to determine that it was a template name in the first place. If
  1953. // this becomes a performance hit, we can work harder to preserve those
  1954. // results until we get here but it's likely not worth it.
  1955. bool MemberOfUnknownSpecialization;
  1956. AssumedTemplateKind AssumedTemplate;
  1957. if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1958. MemberOfUnknownSpecialization, TemplateKWLoc,
  1959. &AssumedTemplate))
  1960. return ExprError();
  1961. if (MemberOfUnknownSpecialization ||
  1962. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1963. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1964. IsAddressOfOperand, TemplateArgs);
  1965. } else {
  1966. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1967. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1968. // If the result might be in a dependent base class, this is a dependent
  1969. // id-expression.
  1970. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1971. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1972. IsAddressOfOperand, TemplateArgs);
  1973. // If this reference is in an Objective-C method, then we need to do
  1974. // some special Objective-C lookup, too.
  1975. if (IvarLookupFollowUp) {
  1976. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1977. if (E.isInvalid())
  1978. return ExprError();
  1979. if (Expr *Ex = E.getAs<Expr>())
  1980. return Ex;
  1981. }
  1982. }
  1983. if (R.isAmbiguous())
  1984. return ExprError();
  1985. // This could be an implicitly declared function reference (legal in C90,
  1986. // extension in C99, forbidden in C++).
  1987. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  1988. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  1989. if (D) R.addDecl(D);
  1990. }
  1991. // Determine whether this name might be a candidate for
  1992. // argument-dependent lookup.
  1993. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  1994. if (R.empty() && !ADL) {
  1995. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  1996. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  1997. TemplateKWLoc, TemplateArgs))
  1998. return E;
  1999. }
  2000. // Don't diagnose an empty lookup for inline assembly.
  2001. if (IsInlineAsmIdentifier)
  2002. return ExprError();
  2003. // If this name wasn't predeclared and if this is not a function
  2004. // call, diagnose the problem.
  2005. TypoExpr *TE = nullptr;
  2006. DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
  2007. : nullptr);
  2008. DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
  2009. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  2010. "Typo correction callback misconfigured");
  2011. if (CCC) {
  2012. // Make sure the callback knows what the typo being diagnosed is.
  2013. CCC->setTypoName(II);
  2014. if (SS.isValid())
  2015. CCC->setTypoNNS(SS.getScopeRep());
  2016. }
  2017. // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
  2018. // a template name, but we happen to have always already looked up the name
  2019. // before we get here if it must be a template name.
  2020. if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
  2021. None, &TE)) {
  2022. if (TE && KeywordReplacement) {
  2023. auto &State = getTypoExprState(TE);
  2024. auto BestTC = State.Consumer->getNextCorrection();
  2025. if (BestTC.isKeyword()) {
  2026. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  2027. if (State.DiagHandler)
  2028. State.DiagHandler(BestTC);
  2029. KeywordReplacement->startToken();
  2030. KeywordReplacement->setKind(II->getTokenID());
  2031. KeywordReplacement->setIdentifierInfo(II);
  2032. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  2033. // Clean up the state associated with the TypoExpr, since it has
  2034. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  2035. clearDelayedTypo(TE);
  2036. // Signal that a correction to a keyword was performed by returning a
  2037. // valid-but-null ExprResult.
  2038. return (Expr*)nullptr;
  2039. }
  2040. State.Consumer->resetCorrectionStream();
  2041. }
  2042. return TE ? TE : ExprError();
  2043. }
  2044. assert(!R.empty() &&
  2045. "DiagnoseEmptyLookup returned false but added no results");
  2046. // If we found an Objective-C instance variable, let
  2047. // LookupInObjCMethod build the appropriate expression to
  2048. // reference the ivar.
  2049. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  2050. R.clear();
  2051. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  2052. // In a hopelessly buggy code, Objective-C instance variable
  2053. // lookup fails and no expression will be built to reference it.
  2054. if (!E.isInvalid() && !E.get())
  2055. return ExprError();
  2056. return E;
  2057. }
  2058. }
  2059. // This is guaranteed from this point on.
  2060. assert(!R.empty() || ADL);
  2061. // Check whether this might be a C++ implicit instance member access.
  2062. // C++ [class.mfct.non-static]p3:
  2063. // When an id-expression that is not part of a class member access
  2064. // syntax and not used to form a pointer to member is used in the
  2065. // body of a non-static member function of class X, if name lookup
  2066. // resolves the name in the id-expression to a non-static non-type
  2067. // member of some class C, the id-expression is transformed into a
  2068. // class member access expression using (*this) as the
  2069. // postfix-expression to the left of the . operator.
  2070. //
  2071. // But we don't actually need to do this for '&' operands if R
  2072. // resolved to a function or overloaded function set, because the
  2073. // expression is ill-formed if it actually works out to be a
  2074. // non-static member function:
  2075. //
  2076. // C++ [expr.ref]p4:
  2077. // Otherwise, if E1.E2 refers to a non-static member function. . .
  2078. // [t]he expression can be used only as the left-hand operand of a
  2079. // member function call.
  2080. //
  2081. // There are other safeguards against such uses, but it's important
  2082. // to get this right here so that we don't end up making a
  2083. // spuriously dependent expression if we're inside a dependent
  2084. // instance method.
  2085. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  2086. bool MightBeImplicitMember;
  2087. if (!IsAddressOfOperand)
  2088. MightBeImplicitMember = true;
  2089. else if (!SS.isEmpty())
  2090. MightBeImplicitMember = false;
  2091. else if (R.isOverloadedResult())
  2092. MightBeImplicitMember = false;
  2093. else if (R.isUnresolvableResult())
  2094. MightBeImplicitMember = true;
  2095. else
  2096. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  2097. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  2098. isa<MSPropertyDecl>(R.getFoundDecl());
  2099. if (MightBeImplicitMember)
  2100. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  2101. R, TemplateArgs, S);
  2102. }
  2103. if (TemplateArgs || TemplateKWLoc.isValid()) {
  2104. // In C++1y, if this is a variable template id, then check it
  2105. // in BuildTemplateIdExpr().
  2106. // The single lookup result must be a variable template declaration.
  2107. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
  2108. Id.TemplateId->Kind == TNK_Var_template) {
  2109. assert(R.getAsSingle<VarTemplateDecl>() &&
  2110. "There should only be one declaration found.");
  2111. }
  2112. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  2113. }
  2114. return BuildDeclarationNameExpr(SS, R, ADL);
  2115. }
  2116. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2117. /// declaration name, generally during template instantiation.
  2118. /// There's a large number of things which don't need to be done along
  2119. /// this path.
  2120. ExprResult Sema::BuildQualifiedDeclarationNameExpr(
  2121. CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
  2122. bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
  2123. DeclContext *DC = computeDeclContext(SS, false);
  2124. if (!DC)
  2125. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2126. NameInfo, /*TemplateArgs=*/nullptr);
  2127. if (RequireCompleteDeclContext(SS, DC))
  2128. return ExprError();
  2129. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2130. LookupQualifiedName(R, DC);
  2131. if (R.isAmbiguous())
  2132. return ExprError();
  2133. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2134. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2135. NameInfo, /*TemplateArgs=*/nullptr);
  2136. if (R.empty()) {
  2137. Diag(NameInfo.getLoc(), diag::err_no_member)
  2138. << NameInfo.getName() << DC << SS.getRange();
  2139. return ExprError();
  2140. }
  2141. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2142. // Diagnose a missing typename if this resolved unambiguously to a type in
  2143. // a dependent context. If we can recover with a type, downgrade this to
  2144. // a warning in Microsoft compatibility mode.
  2145. unsigned DiagID = diag::err_typename_missing;
  2146. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2147. DiagID = diag::ext_typename_missing;
  2148. SourceLocation Loc = SS.getBeginLoc();
  2149. auto D = Diag(Loc, DiagID);
  2150. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2151. << SourceRange(Loc, NameInfo.getEndLoc());
  2152. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2153. // context.
  2154. if (!RecoveryTSI)
  2155. return ExprError();
  2156. // Only issue the fixit if we're prepared to recover.
  2157. D << FixItHint::CreateInsertion(Loc, "typename ");
  2158. // Recover by pretending this was an elaborated type.
  2159. QualType Ty = Context.getTypeDeclType(TD);
  2160. TypeLocBuilder TLB;
  2161. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2162. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2163. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2164. QTL.setElaboratedKeywordLoc(SourceLocation());
  2165. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2166. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2167. return ExprEmpty();
  2168. }
  2169. // Defend against this resolving to an implicit member access. We usually
  2170. // won't get here if this might be a legitimate a class member (we end up in
  2171. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2172. // a pointer-to-member or in an unevaluated context in C++11.
  2173. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2174. return BuildPossibleImplicitMemberExpr(SS,
  2175. /*TemplateKWLoc=*/SourceLocation(),
  2176. R, /*TemplateArgs=*/nullptr, S);
  2177. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2178. }
  2179. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  2180. /// detected that we're currently inside an ObjC method. Perform some
  2181. /// additional lookup.
  2182. ///
  2183. /// Ideally, most of this would be done by lookup, but there's
  2184. /// actually quite a lot of extra work involved.
  2185. ///
  2186. /// Returns a null sentinel to indicate trivial success.
  2187. ExprResult
  2188. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2189. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2190. SourceLocation Loc = Lookup.getNameLoc();
  2191. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2192. // Check for error condition which is already reported.
  2193. if (!CurMethod)
  2194. return ExprError();
  2195. // There are two cases to handle here. 1) scoped lookup could have failed,
  2196. // in which case we should look for an ivar. 2) scoped lookup could have
  2197. // found a decl, but that decl is outside the current instance method (i.e.
  2198. // a global variable). In these two cases, we do a lookup for an ivar with
  2199. // this name, if the lookup sucedes, we replace it our current decl.
  2200. // If we're in a class method, we don't normally want to look for
  2201. // ivars. But if we don't find anything else, and there's an
  2202. // ivar, that's an error.
  2203. bool IsClassMethod = CurMethod->isClassMethod();
  2204. bool LookForIvars;
  2205. if (Lookup.empty())
  2206. LookForIvars = true;
  2207. else if (IsClassMethod)
  2208. LookForIvars = false;
  2209. else
  2210. LookForIvars = (Lookup.isSingleResult() &&
  2211. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2212. ObjCInterfaceDecl *IFace = nullptr;
  2213. if (LookForIvars) {
  2214. IFace = CurMethod->getClassInterface();
  2215. ObjCInterfaceDecl *ClassDeclared;
  2216. ObjCIvarDecl *IV = nullptr;
  2217. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2218. // Diagnose using an ivar in a class method.
  2219. if (IsClassMethod)
  2220. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2221. << IV->getDeclName());
  2222. // If we're referencing an invalid decl, just return this as a silent
  2223. // error node. The error diagnostic was already emitted on the decl.
  2224. if (IV->isInvalidDecl())
  2225. return ExprError();
  2226. // Check if referencing a field with __attribute__((deprecated)).
  2227. if (DiagnoseUseOfDecl(IV, Loc))
  2228. return ExprError();
  2229. // Diagnose the use of an ivar outside of the declaring class.
  2230. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2231. !declaresSameEntity(ClassDeclared, IFace) &&
  2232. !getLangOpts().DebuggerSupport)
  2233. Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
  2234. // FIXME: This should use a new expr for a direct reference, don't
  2235. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2236. IdentifierInfo &II = Context.Idents.get("self");
  2237. UnqualifiedId SelfName;
  2238. SelfName.setIdentifier(&II, SourceLocation());
  2239. SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
  2240. CXXScopeSpec SelfScopeSpec;
  2241. SourceLocation TemplateKWLoc;
  2242. ExprResult SelfExpr =
  2243. ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
  2244. /*HasTrailingLParen=*/false,
  2245. /*IsAddressOfOperand=*/false);
  2246. if (SelfExpr.isInvalid())
  2247. return ExprError();
  2248. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2249. if (SelfExpr.isInvalid())
  2250. return ExprError();
  2251. MarkAnyDeclReferenced(Loc, IV, true);
  2252. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2253. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2254. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2255. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2256. ObjCIvarRefExpr *Result = new (Context)
  2257. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2258. IV->getLocation(), SelfExpr.get(), true, true);
  2259. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2260. if (!isUnevaluatedContext() &&
  2261. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2262. getCurFunction()->recordUseOfWeak(Result);
  2263. }
  2264. if (getLangOpts().ObjCAutoRefCount)
  2265. if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
  2266. ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
  2267. return Result;
  2268. }
  2269. } else if (CurMethod->isInstanceMethod()) {
  2270. // We should warn if a local variable hides an ivar.
  2271. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2272. ObjCInterfaceDecl *ClassDeclared;
  2273. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2274. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2275. declaresSameEntity(IFace, ClassDeclared))
  2276. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2277. }
  2278. }
  2279. } else if (Lookup.isSingleResult() &&
  2280. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2281. // If accessing a stand-alone ivar in a class method, this is an error.
  2282. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  2283. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2284. << IV->getDeclName());
  2285. }
  2286. if (Lookup.empty() && II && AllowBuiltinCreation) {
  2287. // FIXME. Consolidate this with similar code in LookupName.
  2288. if (unsigned BuiltinID = II->getBuiltinID()) {
  2289. if (!(getLangOpts().CPlusPlus &&
  2290. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  2291. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  2292. S, Lookup.isForRedeclaration(),
  2293. Lookup.getNameLoc());
  2294. if (D) Lookup.addDecl(D);
  2295. }
  2296. }
  2297. }
  2298. // Sentinel value saying that we didn't do anything special.
  2299. return ExprResult((Expr *)nullptr);
  2300. }
  2301. /// Cast a base object to a member's actual type.
  2302. ///
  2303. /// Logically this happens in three phases:
  2304. ///
  2305. /// * First we cast from the base type to the naming class.
  2306. /// The naming class is the class into which we were looking
  2307. /// when we found the member; it's the qualifier type if a
  2308. /// qualifier was provided, and otherwise it's the base type.
  2309. ///
  2310. /// * Next we cast from the naming class to the declaring class.
  2311. /// If the member we found was brought into a class's scope by
  2312. /// a using declaration, this is that class; otherwise it's
  2313. /// the class declaring the member.
  2314. ///
  2315. /// * Finally we cast from the declaring class to the "true"
  2316. /// declaring class of the member. This conversion does not
  2317. /// obey access control.
  2318. ExprResult
  2319. Sema::PerformObjectMemberConversion(Expr *From,
  2320. NestedNameSpecifier *Qualifier,
  2321. NamedDecl *FoundDecl,
  2322. NamedDecl *Member) {
  2323. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2324. if (!RD)
  2325. return From;
  2326. QualType DestRecordType;
  2327. QualType DestType;
  2328. QualType FromRecordType;
  2329. QualType FromType = From->getType();
  2330. bool PointerConversions = false;
  2331. if (isa<FieldDecl>(Member)) {
  2332. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2333. auto FromPtrType = FromType->getAs<PointerType>();
  2334. DestRecordType = Context.getAddrSpaceQualType(
  2335. DestRecordType, FromPtrType
  2336. ? FromType->getPointeeType().getAddressSpace()
  2337. : FromType.getAddressSpace());
  2338. if (FromPtrType) {
  2339. DestType = Context.getPointerType(DestRecordType);
  2340. FromRecordType = FromPtrType->getPointeeType();
  2341. PointerConversions = true;
  2342. } else {
  2343. DestType = DestRecordType;
  2344. FromRecordType = FromType;
  2345. }
  2346. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2347. if (Method->isStatic())
  2348. return From;
  2349. DestType = Method->getThisType();
  2350. DestRecordType = DestType->getPointeeType();
  2351. if (FromType->getAs<PointerType>()) {
  2352. FromRecordType = FromType->getPointeeType();
  2353. PointerConversions = true;
  2354. } else {
  2355. FromRecordType = FromType;
  2356. DestType = DestRecordType;
  2357. }
  2358. } else {
  2359. // No conversion necessary.
  2360. return From;
  2361. }
  2362. if (DestType->isDependentType() || FromType->isDependentType())
  2363. return From;
  2364. // If the unqualified types are the same, no conversion is necessary.
  2365. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2366. return From;
  2367. SourceRange FromRange = From->getSourceRange();
  2368. SourceLocation FromLoc = FromRange.getBegin();
  2369. ExprValueKind VK = From->getValueKind();
  2370. // C++ [class.member.lookup]p8:
  2371. // [...] Ambiguities can often be resolved by qualifying a name with its
  2372. // class name.
  2373. //
  2374. // If the member was a qualified name and the qualified referred to a
  2375. // specific base subobject type, we'll cast to that intermediate type
  2376. // first and then to the object in which the member is declared. That allows
  2377. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2378. //
  2379. // class Base { public: int x; };
  2380. // class Derived1 : public Base { };
  2381. // class Derived2 : public Base { };
  2382. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2383. //
  2384. // void VeryDerived::f() {
  2385. // x = 17; // error: ambiguous base subobjects
  2386. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2387. // }
  2388. if (Qualifier && Qualifier->getAsType()) {
  2389. QualType QType = QualType(Qualifier->getAsType(), 0);
  2390. assert(QType->isRecordType() && "lookup done with non-record type");
  2391. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2392. // In C++98, the qualifier type doesn't actually have to be a base
  2393. // type of the object type, in which case we just ignore it.
  2394. // Otherwise build the appropriate casts.
  2395. if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
  2396. CXXCastPath BasePath;
  2397. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2398. FromLoc, FromRange, &BasePath))
  2399. return ExprError();
  2400. if (PointerConversions)
  2401. QType = Context.getPointerType(QType);
  2402. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2403. VK, &BasePath).get();
  2404. FromType = QType;
  2405. FromRecordType = QRecordType;
  2406. // If the qualifier type was the same as the destination type,
  2407. // we're done.
  2408. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2409. return From;
  2410. }
  2411. }
  2412. bool IgnoreAccess = false;
  2413. // If we actually found the member through a using declaration, cast
  2414. // down to the using declaration's type.
  2415. //
  2416. // Pointer equality is fine here because only one declaration of a
  2417. // class ever has member declarations.
  2418. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2419. assert(isa<UsingShadowDecl>(FoundDecl));
  2420. QualType URecordType = Context.getTypeDeclType(
  2421. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2422. // We only need to do this if the naming-class to declaring-class
  2423. // conversion is non-trivial.
  2424. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2425. assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
  2426. CXXCastPath BasePath;
  2427. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2428. FromLoc, FromRange, &BasePath))
  2429. return ExprError();
  2430. QualType UType = URecordType;
  2431. if (PointerConversions)
  2432. UType = Context.getPointerType(UType);
  2433. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2434. VK, &BasePath).get();
  2435. FromType = UType;
  2436. FromRecordType = URecordType;
  2437. }
  2438. // We don't do access control for the conversion from the
  2439. // declaring class to the true declaring class.
  2440. IgnoreAccess = true;
  2441. }
  2442. CXXCastPath BasePath;
  2443. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2444. FromLoc, FromRange, &BasePath,
  2445. IgnoreAccess))
  2446. return ExprError();
  2447. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2448. VK, &BasePath);
  2449. }
  2450. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2451. const LookupResult &R,
  2452. bool HasTrailingLParen) {
  2453. // Only when used directly as the postfix-expression of a call.
  2454. if (!HasTrailingLParen)
  2455. return false;
  2456. // Never if a scope specifier was provided.
  2457. if (SS.isSet())
  2458. return false;
  2459. // Only in C++ or ObjC++.
  2460. if (!getLangOpts().CPlusPlus)
  2461. return false;
  2462. // Turn off ADL when we find certain kinds of declarations during
  2463. // normal lookup:
  2464. for (NamedDecl *D : R) {
  2465. // C++0x [basic.lookup.argdep]p3:
  2466. // -- a declaration of a class member
  2467. // Since using decls preserve this property, we check this on the
  2468. // original decl.
  2469. if (D->isCXXClassMember())
  2470. return false;
  2471. // C++0x [basic.lookup.argdep]p3:
  2472. // -- a block-scope function declaration that is not a
  2473. // using-declaration
  2474. // NOTE: we also trigger this for function templates (in fact, we
  2475. // don't check the decl type at all, since all other decl types
  2476. // turn off ADL anyway).
  2477. if (isa<UsingShadowDecl>(D))
  2478. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2479. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2480. return false;
  2481. // C++0x [basic.lookup.argdep]p3:
  2482. // -- a declaration that is neither a function or a function
  2483. // template
  2484. // And also for builtin functions.
  2485. if (isa<FunctionDecl>(D)) {
  2486. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2487. // But also builtin functions.
  2488. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2489. return false;
  2490. } else if (!isa<FunctionTemplateDecl>(D))
  2491. return false;
  2492. }
  2493. return true;
  2494. }
  2495. /// Diagnoses obvious problems with the use of the given declaration
  2496. /// as an expression. This is only actually called for lookups that
  2497. /// were not overloaded, and it doesn't promise that the declaration
  2498. /// will in fact be used.
  2499. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2500. if (D->isInvalidDecl())
  2501. return true;
  2502. if (isa<TypedefNameDecl>(D)) {
  2503. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2504. return true;
  2505. }
  2506. if (isa<ObjCInterfaceDecl>(D)) {
  2507. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2508. return true;
  2509. }
  2510. if (isa<NamespaceDecl>(D)) {
  2511. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2512. return true;
  2513. }
  2514. return false;
  2515. }
  2516. // Certain multiversion types should be treated as overloaded even when there is
  2517. // only one result.
  2518. static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
  2519. assert(R.isSingleResult() && "Expected only a single result");
  2520. const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  2521. return FD &&
  2522. (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
  2523. }
  2524. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2525. LookupResult &R, bool NeedsADL,
  2526. bool AcceptInvalidDecl) {
  2527. // If this is a single, fully-resolved result and we don't need ADL,
  2528. // just build an ordinary singleton decl ref.
  2529. if (!NeedsADL && R.isSingleResult() &&
  2530. !R.getAsSingle<FunctionTemplateDecl>() &&
  2531. !ShouldLookupResultBeMultiVersionOverload(R))
  2532. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2533. R.getRepresentativeDecl(), nullptr,
  2534. AcceptInvalidDecl);
  2535. // We only need to check the declaration if there's exactly one
  2536. // result, because in the overloaded case the results can only be
  2537. // functions and function templates.
  2538. if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
  2539. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2540. return ExprError();
  2541. // Otherwise, just build an unresolved lookup expression. Suppress
  2542. // any lookup-related diagnostics; we'll hash these out later, when
  2543. // we've picked a target.
  2544. R.suppressDiagnostics();
  2545. UnresolvedLookupExpr *ULE
  2546. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2547. SS.getWithLocInContext(Context),
  2548. R.getLookupNameInfo(),
  2549. NeedsADL, R.isOverloadedResult(),
  2550. R.begin(), R.end());
  2551. return ULE;
  2552. }
  2553. static void
  2554. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  2555. ValueDecl *var, DeclContext *DC);
  2556. /// Complete semantic analysis for a reference to the given declaration.
  2557. ExprResult Sema::BuildDeclarationNameExpr(
  2558. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2559. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2560. bool AcceptInvalidDecl) {
  2561. assert(D && "Cannot refer to a NULL declaration");
  2562. assert(!isa<FunctionTemplateDecl>(D) &&
  2563. "Cannot refer unambiguously to a function template");
  2564. SourceLocation Loc = NameInfo.getLoc();
  2565. if (CheckDeclInExpr(*this, Loc, D))
  2566. return ExprError();
  2567. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2568. // Specifically diagnose references to class templates that are missing
  2569. // a template argument list.
  2570. diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
  2571. return ExprError();
  2572. }
  2573. // Make sure that we're referring to a value.
  2574. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2575. if (!VD) {
  2576. Diag(Loc, diag::err_ref_non_value)
  2577. << D << SS.getRange();
  2578. Diag(D->getLocation(), diag::note_declared_at);
  2579. return ExprError();
  2580. }
  2581. // Check whether this declaration can be used. Note that we suppress
  2582. // this check when we're going to perform argument-dependent lookup
  2583. // on this function name, because this might not be the function
  2584. // that overload resolution actually selects.
  2585. if (DiagnoseUseOfDecl(VD, Loc))
  2586. return ExprError();
  2587. // Only create DeclRefExpr's for valid Decl's.
  2588. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2589. return ExprError();
  2590. // Handle members of anonymous structs and unions. If we got here,
  2591. // and the reference is to a class member indirect field, then this
  2592. // must be the subject of a pointer-to-member expression.
  2593. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2594. if (!indirectField->isCXXClassMember())
  2595. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2596. indirectField);
  2597. {
  2598. QualType type = VD->getType();
  2599. if (type.isNull())
  2600. return ExprError();
  2601. if (auto *FPT = type->getAs<FunctionProtoType>()) {
  2602. // C++ [except.spec]p17:
  2603. // An exception-specification is considered to be needed when:
  2604. // - in an expression, the function is the unique lookup result or
  2605. // the selected member of a set of overloaded functions.
  2606. ResolveExceptionSpec(Loc, FPT);
  2607. type = VD->getType();
  2608. }
  2609. ExprValueKind valueKind = VK_RValue;
  2610. switch (D->getKind()) {
  2611. // Ignore all the non-ValueDecl kinds.
  2612. #define ABSTRACT_DECL(kind)
  2613. #define VALUE(type, base)
  2614. #define DECL(type, base) \
  2615. case Decl::type:
  2616. #include "clang/AST/DeclNodes.inc"
  2617. llvm_unreachable("invalid value decl kind");
  2618. // These shouldn't make it here.
  2619. case Decl::ObjCAtDefsField:
  2620. llvm_unreachable("forming non-member reference to ivar?");
  2621. // Enum constants are always r-values and never references.
  2622. // Unresolved using declarations are dependent.
  2623. case Decl::EnumConstant:
  2624. case Decl::UnresolvedUsingValue:
  2625. case Decl::OMPDeclareReduction:
  2626. case Decl::OMPDeclareMapper:
  2627. valueKind = VK_RValue;
  2628. break;
  2629. // Fields and indirect fields that got here must be for
  2630. // pointer-to-member expressions; we just call them l-values for
  2631. // internal consistency, because this subexpression doesn't really
  2632. // exist in the high-level semantics.
  2633. case Decl::Field:
  2634. case Decl::IndirectField:
  2635. case Decl::ObjCIvar:
  2636. assert(getLangOpts().CPlusPlus &&
  2637. "building reference to field in C?");
  2638. // These can't have reference type in well-formed programs, but
  2639. // for internal consistency we do this anyway.
  2640. type = type.getNonReferenceType();
  2641. valueKind = VK_LValue;
  2642. break;
  2643. // Non-type template parameters are either l-values or r-values
  2644. // depending on the type.
  2645. case Decl::NonTypeTemplateParm: {
  2646. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2647. type = reftype->getPointeeType();
  2648. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2649. break;
  2650. }
  2651. // For non-references, we need to strip qualifiers just in case
  2652. // the template parameter was declared as 'const int' or whatever.
  2653. valueKind = VK_RValue;
  2654. type = type.getUnqualifiedType();
  2655. break;
  2656. }
  2657. case Decl::Var:
  2658. case Decl::VarTemplateSpecialization:
  2659. case Decl::VarTemplatePartialSpecialization:
  2660. case Decl::Decomposition:
  2661. case Decl::OMPCapturedExpr:
  2662. // In C, "extern void blah;" is valid and is an r-value.
  2663. if (!getLangOpts().CPlusPlus &&
  2664. !type.hasQualifiers() &&
  2665. type->isVoidType()) {
  2666. valueKind = VK_RValue;
  2667. break;
  2668. }
  2669. LLVM_FALLTHROUGH;
  2670. case Decl::ImplicitParam:
  2671. case Decl::ParmVar: {
  2672. // These are always l-values.
  2673. valueKind = VK_LValue;
  2674. type = type.getNonReferenceType();
  2675. // FIXME: Does the addition of const really only apply in
  2676. // potentially-evaluated contexts? Since the variable isn't actually
  2677. // captured in an unevaluated context, it seems that the answer is no.
  2678. if (!isUnevaluatedContext()) {
  2679. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2680. if (!CapturedType.isNull())
  2681. type = CapturedType;
  2682. }
  2683. break;
  2684. }
  2685. case Decl::Binding: {
  2686. // These are always lvalues.
  2687. valueKind = VK_LValue;
  2688. type = type.getNonReferenceType();
  2689. // FIXME: Support lambda-capture of BindingDecls, once CWG actually
  2690. // decides how that's supposed to work.
  2691. auto *BD = cast<BindingDecl>(VD);
  2692. if (BD->getDeclContext() != CurContext) {
  2693. auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
  2694. if (DD && DD->hasLocalStorage())
  2695. diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
  2696. }
  2697. break;
  2698. }
  2699. case Decl::Function: {
  2700. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2701. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2702. type = Context.BuiltinFnTy;
  2703. valueKind = VK_RValue;
  2704. break;
  2705. }
  2706. }
  2707. const FunctionType *fty = type->castAs<FunctionType>();
  2708. // If we're referring to a function with an __unknown_anytype
  2709. // result type, make the entire expression __unknown_anytype.
  2710. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2711. type = Context.UnknownAnyTy;
  2712. valueKind = VK_RValue;
  2713. break;
  2714. }
  2715. // Functions are l-values in C++.
  2716. if (getLangOpts().CPlusPlus) {
  2717. valueKind = VK_LValue;
  2718. break;
  2719. }
  2720. // C99 DR 316 says that, if a function type comes from a
  2721. // function definition (without a prototype), that type is only
  2722. // used for checking compatibility. Therefore, when referencing
  2723. // the function, we pretend that we don't have the full function
  2724. // type.
  2725. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2726. isa<FunctionProtoType>(fty))
  2727. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2728. fty->getExtInfo());
  2729. // Functions are r-values in C.
  2730. valueKind = VK_RValue;
  2731. break;
  2732. }
  2733. case Decl::CXXDeductionGuide:
  2734. llvm_unreachable("building reference to deduction guide");
  2735. case Decl::MSProperty:
  2736. valueKind = VK_LValue;
  2737. break;
  2738. case Decl::CXXMethod:
  2739. // If we're referring to a method with an __unknown_anytype
  2740. // result type, make the entire expression __unknown_anytype.
  2741. // This should only be possible with a type written directly.
  2742. if (const FunctionProtoType *proto
  2743. = dyn_cast<FunctionProtoType>(VD->getType()))
  2744. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2745. type = Context.UnknownAnyTy;
  2746. valueKind = VK_RValue;
  2747. break;
  2748. }
  2749. // C++ methods are l-values if static, r-values if non-static.
  2750. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2751. valueKind = VK_LValue;
  2752. break;
  2753. }
  2754. LLVM_FALLTHROUGH;
  2755. case Decl::CXXConversion:
  2756. case Decl::CXXDestructor:
  2757. case Decl::CXXConstructor:
  2758. valueKind = VK_RValue;
  2759. break;
  2760. }
  2761. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2762. TemplateArgs);
  2763. }
  2764. }
  2765. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2766. SmallString<32> &Target) {
  2767. Target.resize(CharByteWidth * (Source.size() + 1));
  2768. char *ResultPtr = &Target[0];
  2769. const llvm::UTF8 *ErrorPtr;
  2770. bool success =
  2771. llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2772. (void)success;
  2773. assert(success);
  2774. Target.resize(ResultPtr - &Target[0]);
  2775. }
  2776. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2777. PredefinedExpr::IdentKind IK) {
  2778. // Pick the current block, lambda, captured statement or function.
  2779. Decl *currentDecl = nullptr;
  2780. if (const BlockScopeInfo *BSI = getCurBlock())
  2781. currentDecl = BSI->TheDecl;
  2782. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2783. currentDecl = LSI->CallOperator;
  2784. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2785. currentDecl = CSI->TheCapturedDecl;
  2786. else
  2787. currentDecl = getCurFunctionOrMethodDecl();
  2788. if (!currentDecl) {
  2789. Diag(Loc, diag::ext_predef_outside_function);
  2790. currentDecl = Context.getTranslationUnitDecl();
  2791. }
  2792. QualType ResTy;
  2793. StringLiteral *SL = nullptr;
  2794. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2795. ResTy = Context.DependentTy;
  2796. else {
  2797. // Pre-defined identifiers are of type char[x], where x is the length of
  2798. // the string.
  2799. auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
  2800. unsigned Length = Str.length();
  2801. llvm::APInt LengthI(32, Length + 1);
  2802. if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
  2803. ResTy =
  2804. Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
  2805. SmallString<32> RawChars;
  2806. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2807. Str, RawChars);
  2808. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2809. /*IndexTypeQuals*/ 0);
  2810. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2811. /*Pascal*/ false, ResTy, Loc);
  2812. } else {
  2813. ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
  2814. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2815. /*IndexTypeQuals*/ 0);
  2816. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2817. /*Pascal*/ false, ResTy, Loc);
  2818. }
  2819. }
  2820. return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
  2821. }
  2822. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2823. PredefinedExpr::IdentKind IK;
  2824. switch (Kind) {
  2825. default: llvm_unreachable("Unknown simple primary expr!");
  2826. case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2827. case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
  2828. case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
  2829. case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
  2830. case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
  2831. case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
  2832. case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
  2833. }
  2834. return BuildPredefinedExpr(Loc, IK);
  2835. }
  2836. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2837. SmallString<16> CharBuffer;
  2838. bool Invalid = false;
  2839. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2840. if (Invalid)
  2841. return ExprError();
  2842. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2843. PP, Tok.getKind());
  2844. if (Literal.hadError())
  2845. return ExprError();
  2846. QualType Ty;
  2847. if (Literal.isWide())
  2848. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2849. else if (Literal.isUTF8() && getLangOpts().Char8)
  2850. Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
  2851. else if (Literal.isUTF16())
  2852. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2853. else if (Literal.isUTF32())
  2854. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2855. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2856. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2857. else
  2858. Ty = Context.CharTy; // 'x' -> char in C++
  2859. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2860. if (Literal.isWide())
  2861. Kind = CharacterLiteral::Wide;
  2862. else if (Literal.isUTF16())
  2863. Kind = CharacterLiteral::UTF16;
  2864. else if (Literal.isUTF32())
  2865. Kind = CharacterLiteral::UTF32;
  2866. else if (Literal.isUTF8())
  2867. Kind = CharacterLiteral::UTF8;
  2868. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2869. Tok.getLocation());
  2870. if (Literal.getUDSuffix().empty())
  2871. return Lit;
  2872. // We're building a user-defined literal.
  2873. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2874. SourceLocation UDSuffixLoc =
  2875. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2876. // Make sure we're allowed user-defined literals here.
  2877. if (!UDLScope)
  2878. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2879. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2880. // operator "" X (ch)
  2881. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2882. Lit, Tok.getLocation());
  2883. }
  2884. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2885. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2886. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2887. Context.IntTy, Loc);
  2888. }
  2889. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2890. QualType Ty, SourceLocation Loc) {
  2891. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2892. using llvm::APFloat;
  2893. APFloat Val(Format);
  2894. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2895. // Overflow is always an error, but underflow is only an error if
  2896. // we underflowed to zero (APFloat reports denormals as underflow).
  2897. if ((result & APFloat::opOverflow) ||
  2898. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2899. unsigned diagnostic;
  2900. SmallString<20> buffer;
  2901. if (result & APFloat::opOverflow) {
  2902. diagnostic = diag::warn_float_overflow;
  2903. APFloat::getLargest(Format).toString(buffer);
  2904. } else {
  2905. diagnostic = diag::warn_float_underflow;
  2906. APFloat::getSmallest(Format).toString(buffer);
  2907. }
  2908. S.Diag(Loc, diagnostic)
  2909. << Ty
  2910. << StringRef(buffer.data(), buffer.size());
  2911. }
  2912. bool isExact = (result == APFloat::opOK);
  2913. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2914. }
  2915. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2916. assert(E && "Invalid expression");
  2917. if (E->isValueDependent())
  2918. return false;
  2919. QualType QT = E->getType();
  2920. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2921. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2922. return true;
  2923. }
  2924. llvm::APSInt ValueAPS;
  2925. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2926. if (R.isInvalid())
  2927. return true;
  2928. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2929. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2930. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2931. << ValueAPS.toString(10) << ValueIsPositive;
  2932. return true;
  2933. }
  2934. return false;
  2935. }
  2936. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2937. // Fast path for a single digit (which is quite common). A single digit
  2938. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2939. if (Tok.getLength() == 1) {
  2940. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2941. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2942. }
  2943. SmallString<128> SpellingBuffer;
  2944. // NumericLiteralParser wants to overread by one character. Add padding to
  2945. // the buffer in case the token is copied to the buffer. If getSpelling()
  2946. // returns a StringRef to the memory buffer, it should have a null char at
  2947. // the EOF, so it is also safe.
  2948. SpellingBuffer.resize(Tok.getLength() + 1);
  2949. // Get the spelling of the token, which eliminates trigraphs, etc.
  2950. bool Invalid = false;
  2951. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2952. if (Invalid)
  2953. return ExprError();
  2954. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2955. if (Literal.hadError)
  2956. return ExprError();
  2957. if (Literal.hasUDSuffix()) {
  2958. // We're building a user-defined literal.
  2959. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2960. SourceLocation UDSuffixLoc =
  2961. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2962. // Make sure we're allowed user-defined literals here.
  2963. if (!UDLScope)
  2964. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2965. QualType CookedTy;
  2966. if (Literal.isFloatingLiteral()) {
  2967. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2968. // long double, the literal is treated as a call of the form
  2969. // operator "" X (f L)
  2970. CookedTy = Context.LongDoubleTy;
  2971. } else {
  2972. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2973. // unsigned long long, the literal is treated as a call of the form
  2974. // operator "" X (n ULL)
  2975. CookedTy = Context.UnsignedLongLongTy;
  2976. }
  2977. DeclarationName OpName =
  2978. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  2979. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  2980. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  2981. SourceLocation TokLoc = Tok.getLocation();
  2982. // Perform literal operator lookup to determine if we're building a raw
  2983. // literal or a cooked one.
  2984. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  2985. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  2986. /*AllowRaw*/ true, /*AllowTemplate*/ true,
  2987. /*AllowStringTemplate*/ false,
  2988. /*DiagnoseMissing*/ !Literal.isImaginary)) {
  2989. case LOLR_ErrorNoDiagnostic:
  2990. // Lookup failure for imaginary constants isn't fatal, there's still the
  2991. // GNU extension producing _Complex types.
  2992. break;
  2993. case LOLR_Error:
  2994. return ExprError();
  2995. case LOLR_Cooked: {
  2996. Expr *Lit;
  2997. if (Literal.isFloatingLiteral()) {
  2998. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  2999. } else {
  3000. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  3001. if (Literal.GetIntegerValue(ResultVal))
  3002. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3003. << /* Unsigned */ 1;
  3004. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  3005. Tok.getLocation());
  3006. }
  3007. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3008. }
  3009. case LOLR_Raw: {
  3010. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  3011. // literal is treated as a call of the form
  3012. // operator "" X ("n")
  3013. unsigned Length = Literal.getUDSuffixOffset();
  3014. QualType StrTy = Context.getConstantArrayType(
  3015. Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
  3016. llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
  3017. Expr *Lit = StringLiteral::Create(
  3018. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  3019. /*Pascal*/false, StrTy, &TokLoc, 1);
  3020. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3021. }
  3022. case LOLR_Template: {
  3023. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  3024. // template), L is treated as a call fo the form
  3025. // operator "" X <'c1', 'c2', ... 'ck'>()
  3026. // where n is the source character sequence c1 c2 ... ck.
  3027. TemplateArgumentListInfo ExplicitArgs;
  3028. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  3029. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  3030. llvm::APSInt Value(CharBits, CharIsUnsigned);
  3031. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  3032. Value = TokSpelling[I];
  3033. TemplateArgument Arg(Context, Value, Context.CharTy);
  3034. TemplateArgumentLocInfo ArgInfo;
  3035. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  3036. }
  3037. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  3038. &ExplicitArgs);
  3039. }
  3040. case LOLR_StringTemplate:
  3041. llvm_unreachable("unexpected literal operator lookup result");
  3042. }
  3043. }
  3044. Expr *Res;
  3045. if (Literal.isFixedPointLiteral()) {
  3046. QualType Ty;
  3047. if (Literal.isAccum) {
  3048. if (Literal.isHalf) {
  3049. Ty = Context.ShortAccumTy;
  3050. } else if (Literal.isLong) {
  3051. Ty = Context.LongAccumTy;
  3052. } else {
  3053. Ty = Context.AccumTy;
  3054. }
  3055. } else if (Literal.isFract) {
  3056. if (Literal.isHalf) {
  3057. Ty = Context.ShortFractTy;
  3058. } else if (Literal.isLong) {
  3059. Ty = Context.LongFractTy;
  3060. } else {
  3061. Ty = Context.FractTy;
  3062. }
  3063. }
  3064. if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
  3065. bool isSigned = !Literal.isUnsigned;
  3066. unsigned scale = Context.getFixedPointScale(Ty);
  3067. unsigned bit_width = Context.getTypeInfo(Ty).Width;
  3068. llvm::APInt Val(bit_width, 0, isSigned);
  3069. bool Overflowed = Literal.GetFixedPointValue(Val, scale);
  3070. bool ValIsZero = Val.isNullValue() && !Overflowed;
  3071. auto MaxVal = Context.getFixedPointMax(Ty).getValue();
  3072. if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
  3073. // Clause 6.4.4 - The value of a constant shall be in the range of
  3074. // representable values for its type, with exception for constants of a
  3075. // fract type with a value of exactly 1; such a constant shall denote
  3076. // the maximal value for the type.
  3077. --Val;
  3078. else if (Val.ugt(MaxVal) || Overflowed)
  3079. Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
  3080. Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
  3081. Tok.getLocation(), scale);
  3082. } else if (Literal.isFloatingLiteral()) {
  3083. QualType Ty;
  3084. if (Literal.isHalf){
  3085. if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
  3086. Ty = Context.HalfTy;
  3087. else {
  3088. Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
  3089. return ExprError();
  3090. }
  3091. } else if (Literal.isFloat)
  3092. Ty = Context.FloatTy;
  3093. else if (Literal.isLong)
  3094. Ty = Context.LongDoubleTy;
  3095. else if (Literal.isFloat16)
  3096. Ty = Context.Float16Ty;
  3097. else if (Literal.isFloat128)
  3098. Ty = Context.Float128Ty;
  3099. else
  3100. Ty = Context.DoubleTy;
  3101. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  3102. if (Ty == Context.DoubleTy) {
  3103. if (getLangOpts().SinglePrecisionConstants) {
  3104. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  3105. if (BTy->getKind() != BuiltinType::Float) {
  3106. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3107. }
  3108. } else if (getLangOpts().OpenCL &&
  3109. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  3110. // Impose single-precision float type when cl_khr_fp64 is not enabled.
  3111. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  3112. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3113. }
  3114. }
  3115. } else if (!Literal.isIntegerLiteral()) {
  3116. return ExprError();
  3117. } else {
  3118. QualType Ty;
  3119. // 'long long' is a C99 or C++11 feature.
  3120. if (!getLangOpts().C99 && Literal.isLongLong) {
  3121. if (getLangOpts().CPlusPlus)
  3122. Diag(Tok.getLocation(),
  3123. getLangOpts().CPlusPlus11 ?
  3124. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  3125. else
  3126. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  3127. }
  3128. // Get the value in the widest-possible width.
  3129. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  3130. llvm::APInt ResultVal(MaxWidth, 0);
  3131. if (Literal.GetIntegerValue(ResultVal)) {
  3132. // If this value didn't fit into uintmax_t, error and force to ull.
  3133. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3134. << /* Unsigned */ 1;
  3135. Ty = Context.UnsignedLongLongTy;
  3136. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  3137. "long long is not intmax_t?");
  3138. } else {
  3139. // If this value fits into a ULL, try to figure out what else it fits into
  3140. // according to the rules of C99 6.4.4.1p5.
  3141. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  3142. // be an unsigned int.
  3143. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  3144. // Check from smallest to largest, picking the smallest type we can.
  3145. unsigned Width = 0;
  3146. // Microsoft specific integer suffixes are explicitly sized.
  3147. if (Literal.MicrosoftInteger) {
  3148. if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  3149. Width = 8;
  3150. Ty = Context.CharTy;
  3151. } else {
  3152. Width = Literal.MicrosoftInteger;
  3153. Ty = Context.getIntTypeForBitwidth(Width,
  3154. /*Signed=*/!Literal.isUnsigned);
  3155. }
  3156. }
  3157. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  3158. // Are int/unsigned possibilities?
  3159. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3160. // Does it fit in a unsigned int?
  3161. if (ResultVal.isIntN(IntSize)) {
  3162. // Does it fit in a signed int?
  3163. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  3164. Ty = Context.IntTy;
  3165. else if (AllowUnsigned)
  3166. Ty = Context.UnsignedIntTy;
  3167. Width = IntSize;
  3168. }
  3169. }
  3170. // Are long/unsigned long possibilities?
  3171. if (Ty.isNull() && !Literal.isLongLong) {
  3172. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  3173. // Does it fit in a unsigned long?
  3174. if (ResultVal.isIntN(LongSize)) {
  3175. // Does it fit in a signed long?
  3176. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  3177. Ty = Context.LongTy;
  3178. else if (AllowUnsigned)
  3179. Ty = Context.UnsignedLongTy;
  3180. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  3181. // is compatible.
  3182. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3183. const unsigned LongLongSize =
  3184. Context.getTargetInfo().getLongLongWidth();
  3185. Diag(Tok.getLocation(),
  3186. getLangOpts().CPlusPlus
  3187. ? Literal.isLong
  3188. ? diag::warn_old_implicitly_unsigned_long_cxx
  3189. : /*C++98 UB*/ diag::
  3190. ext_old_implicitly_unsigned_long_cxx
  3191. : diag::warn_old_implicitly_unsigned_long)
  3192. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3193. : /*will be ill-formed*/ 1);
  3194. Ty = Context.UnsignedLongTy;
  3195. }
  3196. Width = LongSize;
  3197. }
  3198. }
  3199. // Check long long if needed.
  3200. if (Ty.isNull()) {
  3201. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3202. // Does it fit in a unsigned long long?
  3203. if (ResultVal.isIntN(LongLongSize)) {
  3204. // Does it fit in a signed long long?
  3205. // To be compatible with MSVC, hex integer literals ending with the
  3206. // LL or i64 suffix are always signed in Microsoft mode.
  3207. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3208. (getLangOpts().MSVCCompat && Literal.isLongLong)))
  3209. Ty = Context.LongLongTy;
  3210. else if (AllowUnsigned)
  3211. Ty = Context.UnsignedLongLongTy;
  3212. Width = LongLongSize;
  3213. }
  3214. }
  3215. // If we still couldn't decide a type, we probably have something that
  3216. // does not fit in a signed long long, but has no U suffix.
  3217. if (Ty.isNull()) {
  3218. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3219. Ty = Context.UnsignedLongLongTy;
  3220. Width = Context.getTargetInfo().getLongLongWidth();
  3221. }
  3222. if (ResultVal.getBitWidth() != Width)
  3223. ResultVal = ResultVal.trunc(Width);
  3224. }
  3225. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3226. }
  3227. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3228. if (Literal.isImaginary) {
  3229. Res = new (Context) ImaginaryLiteral(Res,
  3230. Context.getComplexType(Res->getType()));
  3231. Diag(Tok.getLocation(), diag::ext_imaginary_constant);
  3232. }
  3233. return Res;
  3234. }
  3235. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3236. assert(E && "ActOnParenExpr() missing expr");
  3237. return new (Context) ParenExpr(L, R, E);
  3238. }
  3239. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3240. SourceLocation Loc,
  3241. SourceRange ArgRange) {
  3242. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3243. // scalar or vector data type argument..."
  3244. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3245. // type (C99 6.2.5p18) or void.
  3246. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3247. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3248. << T << ArgRange;
  3249. return true;
  3250. }
  3251. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3252. "Scalar types should always be complete");
  3253. return false;
  3254. }
  3255. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3256. SourceLocation Loc,
  3257. SourceRange ArgRange,
  3258. UnaryExprOrTypeTrait TraitKind) {
  3259. // Invalid types must be hard errors for SFINAE in C++.
  3260. if (S.LangOpts.CPlusPlus)
  3261. return true;
  3262. // C99 6.5.3.4p1:
  3263. if (T->isFunctionType() &&
  3264. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
  3265. TraitKind == UETT_PreferredAlignOf)) {
  3266. // sizeof(function)/alignof(function) is allowed as an extension.
  3267. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3268. << TraitKind << ArgRange;
  3269. return false;
  3270. }
  3271. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3272. // this is an error (OpenCL v1.1 s6.3.k)
  3273. if (T->isVoidType()) {
  3274. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3275. : diag::ext_sizeof_alignof_void_type;
  3276. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3277. return false;
  3278. }
  3279. return true;
  3280. }
  3281. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3282. SourceLocation Loc,
  3283. SourceRange ArgRange,
  3284. UnaryExprOrTypeTrait TraitKind) {
  3285. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3286. // runtime doesn't allow it.
  3287. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3288. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3289. << T << (TraitKind == UETT_SizeOf)
  3290. << ArgRange;
  3291. return true;
  3292. }
  3293. return false;
  3294. }
  3295. /// Check whether E is a pointer from a decayed array type (the decayed
  3296. /// pointer type is equal to T) and emit a warning if it is.
  3297. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3298. Expr *E) {
  3299. // Don't warn if the operation changed the type.
  3300. if (T != E->getType())
  3301. return;
  3302. // Now look for array decays.
  3303. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3304. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3305. return;
  3306. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3307. << ICE->getType()
  3308. << ICE->getSubExpr()->getType();
  3309. }
  3310. /// Check the constraints on expression operands to unary type expression
  3311. /// and type traits.
  3312. ///
  3313. /// Completes any types necessary and validates the constraints on the operand
  3314. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3315. /// the expression as it completes the type for that expression through template
  3316. /// instantiation, etc.
  3317. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3318. UnaryExprOrTypeTrait ExprKind) {
  3319. QualType ExprTy = E->getType();
  3320. assert(!ExprTy->isReferenceType());
  3321. if (ExprKind == UETT_VecStep)
  3322. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3323. E->getSourceRange());
  3324. // Whitelist some types as extensions
  3325. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3326. E->getSourceRange(), ExprKind))
  3327. return false;
  3328. // 'alignof' applied to an expression only requires the base element type of
  3329. // the expression to be complete. 'sizeof' requires the expression's type to
  3330. // be complete (and will attempt to complete it if it's an array of unknown
  3331. // bound).
  3332. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3333. if (RequireCompleteType(E->getExprLoc(),
  3334. Context.getBaseElementType(E->getType()),
  3335. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3336. E->getSourceRange()))
  3337. return true;
  3338. } else {
  3339. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3340. ExprKind, E->getSourceRange()))
  3341. return true;
  3342. }
  3343. // Completing the expression's type may have changed it.
  3344. ExprTy = E->getType();
  3345. assert(!ExprTy->isReferenceType());
  3346. if (ExprTy->isFunctionType()) {
  3347. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3348. << ExprKind << E->getSourceRange();
  3349. return true;
  3350. }
  3351. // The operand for sizeof and alignof is in an unevaluated expression context,
  3352. // so side effects could result in unintended consequences.
  3353. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
  3354. ExprKind == UETT_PreferredAlignOf) &&
  3355. !inTemplateInstantiation() && E->HasSideEffects(Context, false))
  3356. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3357. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3358. E->getSourceRange(), ExprKind))
  3359. return true;
  3360. if (ExprKind == UETT_SizeOf) {
  3361. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3362. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3363. QualType OType = PVD->getOriginalType();
  3364. QualType Type = PVD->getType();
  3365. if (Type->isPointerType() && OType->isArrayType()) {
  3366. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3367. << Type << OType;
  3368. Diag(PVD->getLocation(), diag::note_declared_at);
  3369. }
  3370. }
  3371. }
  3372. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3373. // decays into a pointer and returns an unintended result. This is most
  3374. // likely a typo for "sizeof(array) op x".
  3375. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3376. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3377. BO->getLHS());
  3378. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3379. BO->getRHS());
  3380. }
  3381. }
  3382. return false;
  3383. }
  3384. /// Check the constraints on operands to unary expression and type
  3385. /// traits.
  3386. ///
  3387. /// This will complete any types necessary, and validate the various constraints
  3388. /// on those operands.
  3389. ///
  3390. /// The UsualUnaryConversions() function is *not* called by this routine.
  3391. /// C99 6.3.2.1p[2-4] all state:
  3392. /// Except when it is the operand of the sizeof operator ...
  3393. ///
  3394. /// C++ [expr.sizeof]p4
  3395. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3396. /// standard conversions are not applied to the operand of sizeof.
  3397. ///
  3398. /// This policy is followed for all of the unary trait expressions.
  3399. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3400. SourceLocation OpLoc,
  3401. SourceRange ExprRange,
  3402. UnaryExprOrTypeTrait ExprKind) {
  3403. if (ExprType->isDependentType())
  3404. return false;
  3405. // C++ [expr.sizeof]p2:
  3406. // When applied to a reference or a reference type, the result
  3407. // is the size of the referenced type.
  3408. // C++11 [expr.alignof]p3:
  3409. // When alignof is applied to a reference type, the result
  3410. // shall be the alignment of the referenced type.
  3411. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3412. ExprType = Ref->getPointeeType();
  3413. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3414. // When alignof or _Alignof is applied to an array type, the result
  3415. // is the alignment of the element type.
  3416. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
  3417. ExprKind == UETT_OpenMPRequiredSimdAlign)
  3418. ExprType = Context.getBaseElementType(ExprType);
  3419. if (ExprKind == UETT_VecStep)
  3420. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3421. // Whitelist some types as extensions
  3422. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3423. ExprKind))
  3424. return false;
  3425. if (RequireCompleteType(OpLoc, ExprType,
  3426. diag::err_sizeof_alignof_incomplete_type,
  3427. ExprKind, ExprRange))
  3428. return true;
  3429. if (ExprType->isFunctionType()) {
  3430. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3431. << ExprKind << ExprRange;
  3432. return true;
  3433. }
  3434. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3435. ExprKind))
  3436. return true;
  3437. return false;
  3438. }
  3439. static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
  3440. E = E->IgnoreParens();
  3441. // Cannot know anything else if the expression is dependent.
  3442. if (E->isTypeDependent())
  3443. return false;
  3444. if (E->getObjectKind() == OK_BitField) {
  3445. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
  3446. << 1 << E->getSourceRange();
  3447. return true;
  3448. }
  3449. ValueDecl *D = nullptr;
  3450. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3451. D = DRE->getDecl();
  3452. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3453. D = ME->getMemberDecl();
  3454. }
  3455. // If it's a field, require the containing struct to have a
  3456. // complete definition so that we can compute the layout.
  3457. //
  3458. // This can happen in C++11 onwards, either by naming the member
  3459. // in a way that is not transformed into a member access expression
  3460. // (in an unevaluated operand, for instance), or by naming the member
  3461. // in a trailing-return-type.
  3462. //
  3463. // For the record, since __alignof__ on expressions is a GCC
  3464. // extension, GCC seems to permit this but always gives the
  3465. // nonsensical answer 0.
  3466. //
  3467. // We don't really need the layout here --- we could instead just
  3468. // directly check for all the appropriate alignment-lowing
  3469. // attributes --- but that would require duplicating a lot of
  3470. // logic that just isn't worth duplicating for such a marginal
  3471. // use-case.
  3472. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3473. // Fast path this check, since we at least know the record has a
  3474. // definition if we can find a member of it.
  3475. if (!FD->getParent()->isCompleteDefinition()) {
  3476. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3477. << E->getSourceRange();
  3478. return true;
  3479. }
  3480. // Otherwise, if it's a field, and the field doesn't have
  3481. // reference type, then it must have a complete type (or be a
  3482. // flexible array member, which we explicitly want to
  3483. // white-list anyway), which makes the following checks trivial.
  3484. if (!FD->getType()->isReferenceType())
  3485. return false;
  3486. }
  3487. return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
  3488. }
  3489. bool Sema::CheckVecStepExpr(Expr *E) {
  3490. E = E->IgnoreParens();
  3491. // Cannot know anything else if the expression is dependent.
  3492. if (E->isTypeDependent())
  3493. return false;
  3494. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3495. }
  3496. static void captureVariablyModifiedType(ASTContext &Context, QualType T,
  3497. CapturingScopeInfo *CSI) {
  3498. assert(T->isVariablyModifiedType());
  3499. assert(CSI != nullptr);
  3500. // We're going to walk down into the type and look for VLA expressions.
  3501. do {
  3502. const Type *Ty = T.getTypePtr();
  3503. switch (Ty->getTypeClass()) {
  3504. #define TYPE(Class, Base)
  3505. #define ABSTRACT_TYPE(Class, Base)
  3506. #define NON_CANONICAL_TYPE(Class, Base)
  3507. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  3508. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  3509. #include "clang/AST/TypeNodes.def"
  3510. T = QualType();
  3511. break;
  3512. // These types are never variably-modified.
  3513. case Type::Builtin:
  3514. case Type::Complex:
  3515. case Type::Vector:
  3516. case Type::ExtVector:
  3517. case Type::Record:
  3518. case Type::Enum:
  3519. case Type::Elaborated:
  3520. case Type::TemplateSpecialization:
  3521. case Type::ObjCObject:
  3522. case Type::ObjCInterface:
  3523. case Type::ObjCObjectPointer:
  3524. case Type::ObjCTypeParam:
  3525. case Type::Pipe:
  3526. llvm_unreachable("type class is never variably-modified!");
  3527. case Type::Adjusted:
  3528. T = cast<AdjustedType>(Ty)->getOriginalType();
  3529. break;
  3530. case Type::Decayed:
  3531. T = cast<DecayedType>(Ty)->getPointeeType();
  3532. break;
  3533. case Type::Pointer:
  3534. T = cast<PointerType>(Ty)->getPointeeType();
  3535. break;
  3536. case Type::BlockPointer:
  3537. T = cast<BlockPointerType>(Ty)->getPointeeType();
  3538. break;
  3539. case Type::LValueReference:
  3540. case Type::RValueReference:
  3541. T = cast<ReferenceType>(Ty)->getPointeeType();
  3542. break;
  3543. case Type::MemberPointer:
  3544. T = cast<MemberPointerType>(Ty)->getPointeeType();
  3545. break;
  3546. case Type::ConstantArray:
  3547. case Type::IncompleteArray:
  3548. // Losing element qualification here is fine.
  3549. T = cast<ArrayType>(Ty)->getElementType();
  3550. break;
  3551. case Type::VariableArray: {
  3552. // Losing element qualification here is fine.
  3553. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  3554. // Unknown size indication requires no size computation.
  3555. // Otherwise, evaluate and record it.
  3556. auto Size = VAT->getSizeExpr();
  3557. if (Size && !CSI->isVLATypeCaptured(VAT) &&
  3558. (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
  3559. CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
  3560. T = VAT->getElementType();
  3561. break;
  3562. }
  3563. case Type::FunctionProto:
  3564. case Type::FunctionNoProto:
  3565. T = cast<FunctionType>(Ty)->getReturnType();
  3566. break;
  3567. case Type::Paren:
  3568. case Type::TypeOf:
  3569. case Type::UnaryTransform:
  3570. case Type::Attributed:
  3571. case Type::SubstTemplateTypeParm:
  3572. case Type::PackExpansion:
  3573. case Type::MacroQualified:
  3574. // Keep walking after single level desugaring.
  3575. T = T.getSingleStepDesugaredType(Context);
  3576. break;
  3577. case Type::Typedef:
  3578. T = cast<TypedefType>(Ty)->desugar();
  3579. break;
  3580. case Type::Decltype:
  3581. T = cast<DecltypeType>(Ty)->desugar();
  3582. break;
  3583. case Type::Auto:
  3584. case Type::DeducedTemplateSpecialization:
  3585. T = cast<DeducedType>(Ty)->getDeducedType();
  3586. break;
  3587. case Type::TypeOfExpr:
  3588. T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  3589. break;
  3590. case Type::Atomic:
  3591. T = cast<AtomicType>(Ty)->getValueType();
  3592. break;
  3593. }
  3594. } while (!T.isNull() && T->isVariablyModifiedType());
  3595. }
  3596. /// Build a sizeof or alignof expression given a type operand.
  3597. ExprResult
  3598. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3599. SourceLocation OpLoc,
  3600. UnaryExprOrTypeTrait ExprKind,
  3601. SourceRange R) {
  3602. if (!TInfo)
  3603. return ExprError();
  3604. QualType T = TInfo->getType();
  3605. if (!T->isDependentType() &&
  3606. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3607. return ExprError();
  3608. if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
  3609. if (auto *TT = T->getAs<TypedefType>()) {
  3610. for (auto I = FunctionScopes.rbegin(),
  3611. E = std::prev(FunctionScopes.rend());
  3612. I != E; ++I) {
  3613. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  3614. if (CSI == nullptr)
  3615. break;
  3616. DeclContext *DC = nullptr;
  3617. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  3618. DC = LSI->CallOperator;
  3619. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  3620. DC = CRSI->TheCapturedDecl;
  3621. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  3622. DC = BSI->TheDecl;
  3623. if (DC) {
  3624. if (DC->containsDecl(TT->getDecl()))
  3625. break;
  3626. captureVariablyModifiedType(Context, T, CSI);
  3627. }
  3628. }
  3629. }
  3630. }
  3631. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3632. return new (Context) UnaryExprOrTypeTraitExpr(
  3633. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3634. }
  3635. /// Build a sizeof or alignof expression given an expression
  3636. /// operand.
  3637. ExprResult
  3638. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3639. UnaryExprOrTypeTrait ExprKind) {
  3640. ExprResult PE = CheckPlaceholderExpr(E);
  3641. if (PE.isInvalid())
  3642. return ExprError();
  3643. E = PE.get();
  3644. // Verify that the operand is valid.
  3645. bool isInvalid = false;
  3646. if (E->isTypeDependent()) {
  3647. // Delay type-checking for type-dependent expressions.
  3648. } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3649. isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
  3650. } else if (ExprKind == UETT_VecStep) {
  3651. isInvalid = CheckVecStepExpr(E);
  3652. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3653. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3654. isInvalid = true;
  3655. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3656. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
  3657. isInvalid = true;
  3658. } else {
  3659. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3660. }
  3661. if (isInvalid)
  3662. return ExprError();
  3663. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3664. PE = TransformToPotentiallyEvaluated(E);
  3665. if (PE.isInvalid()) return ExprError();
  3666. E = PE.get();
  3667. }
  3668. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3669. return new (Context) UnaryExprOrTypeTraitExpr(
  3670. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3671. }
  3672. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3673. /// expr and the same for @c alignof and @c __alignof
  3674. /// Note that the ArgRange is invalid if isType is false.
  3675. ExprResult
  3676. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3677. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3678. void *TyOrEx, SourceRange ArgRange) {
  3679. // If error parsing type, ignore.
  3680. if (!TyOrEx) return ExprError();
  3681. if (IsType) {
  3682. TypeSourceInfo *TInfo;
  3683. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3684. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3685. }
  3686. Expr *ArgEx = (Expr *)TyOrEx;
  3687. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3688. return Result;
  3689. }
  3690. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3691. bool IsReal) {
  3692. if (V.get()->isTypeDependent())
  3693. return S.Context.DependentTy;
  3694. // _Real and _Imag are only l-values for normal l-values.
  3695. if (V.get()->getObjectKind() != OK_Ordinary) {
  3696. V = S.DefaultLvalueConversion(V.get());
  3697. if (V.isInvalid())
  3698. return QualType();
  3699. }
  3700. // These operators return the element type of a complex type.
  3701. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3702. return CT->getElementType();
  3703. // Otherwise they pass through real integer and floating point types here.
  3704. if (V.get()->getType()->isArithmeticType())
  3705. return V.get()->getType();
  3706. // Test for placeholders.
  3707. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3708. if (PR.isInvalid()) return QualType();
  3709. if (PR.get() != V.get()) {
  3710. V = PR;
  3711. return CheckRealImagOperand(S, V, Loc, IsReal);
  3712. }
  3713. // Reject anything else.
  3714. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3715. << (IsReal ? "__real" : "__imag");
  3716. return QualType();
  3717. }
  3718. ExprResult
  3719. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3720. tok::TokenKind Kind, Expr *Input) {
  3721. UnaryOperatorKind Opc;
  3722. switch (Kind) {
  3723. default: llvm_unreachable("Unknown unary op!");
  3724. case tok::plusplus: Opc = UO_PostInc; break;
  3725. case tok::minusminus: Opc = UO_PostDec; break;
  3726. }
  3727. // Since this might is a postfix expression, get rid of ParenListExprs.
  3728. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3729. if (Result.isInvalid()) return ExprError();
  3730. Input = Result.get();
  3731. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3732. }
  3733. /// Diagnose if arithmetic on the given ObjC pointer is illegal.
  3734. ///
  3735. /// \return true on error
  3736. static bool checkArithmeticOnObjCPointer(Sema &S,
  3737. SourceLocation opLoc,
  3738. Expr *op) {
  3739. assert(op->getType()->isObjCObjectPointerType());
  3740. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3741. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3742. return false;
  3743. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3744. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3745. << op->getSourceRange();
  3746. return true;
  3747. }
  3748. static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
  3749. auto *BaseNoParens = Base->IgnoreParens();
  3750. if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
  3751. return MSProp->getPropertyDecl()->getType()->isArrayType();
  3752. return isa<MSPropertySubscriptExpr>(BaseNoParens);
  3753. }
  3754. ExprResult
  3755. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3756. Expr *idx, SourceLocation rbLoc) {
  3757. if (base && !base->getType().isNull() &&
  3758. base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
  3759. return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
  3760. /*Length=*/nullptr, rbLoc);
  3761. // Since this might be a postfix expression, get rid of ParenListExprs.
  3762. if (isa<ParenListExpr>(base)) {
  3763. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3764. if (result.isInvalid()) return ExprError();
  3765. base = result.get();
  3766. }
  3767. // Handle any non-overload placeholder types in the base and index
  3768. // expressions. We can't handle overloads here because the other
  3769. // operand might be an overloadable type, in which case the overload
  3770. // resolution for the operator overload should get the first crack
  3771. // at the overload.
  3772. bool IsMSPropertySubscript = false;
  3773. if (base->getType()->isNonOverloadPlaceholderType()) {
  3774. IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
  3775. if (!IsMSPropertySubscript) {
  3776. ExprResult result = CheckPlaceholderExpr(base);
  3777. if (result.isInvalid())
  3778. return ExprError();
  3779. base = result.get();
  3780. }
  3781. }
  3782. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3783. ExprResult result = CheckPlaceholderExpr(idx);
  3784. if (result.isInvalid()) return ExprError();
  3785. idx = result.get();
  3786. }
  3787. // Build an unanalyzed expression if either operand is type-dependent.
  3788. if (getLangOpts().CPlusPlus &&
  3789. (base->isTypeDependent() || idx->isTypeDependent())) {
  3790. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3791. VK_LValue, OK_Ordinary, rbLoc);
  3792. }
  3793. // MSDN, property (C++)
  3794. // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
  3795. // This attribute can also be used in the declaration of an empty array in a
  3796. // class or structure definition. For example:
  3797. // __declspec(property(get=GetX, put=PutX)) int x[];
  3798. // The above statement indicates that x[] can be used with one or more array
  3799. // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
  3800. // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
  3801. if (IsMSPropertySubscript) {
  3802. // Build MS property subscript expression if base is MS property reference
  3803. // or MS property subscript.
  3804. return new (Context) MSPropertySubscriptExpr(
  3805. base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
  3806. }
  3807. // Use C++ overloaded-operator rules if either operand has record
  3808. // type. The spec says to do this if either type is *overloadable*,
  3809. // but enum types can't declare subscript operators or conversion
  3810. // operators, so there's nothing interesting for overload resolution
  3811. // to do if there aren't any record types involved.
  3812. //
  3813. // ObjC pointers have their own subscripting logic that is not tied
  3814. // to overload resolution and so should not take this path.
  3815. if (getLangOpts().CPlusPlus &&
  3816. (base->getType()->isRecordType() ||
  3817. (!base->getType()->isObjCObjectPointerType() &&
  3818. idx->getType()->isRecordType()))) {
  3819. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3820. }
  3821. ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3822. if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
  3823. CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
  3824. return Res;
  3825. }
  3826. void Sema::CheckAddressOfNoDeref(const Expr *E) {
  3827. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  3828. const Expr *StrippedExpr = E->IgnoreParenImpCasts();
  3829. // For expressions like `&(*s).b`, the base is recorded and what should be
  3830. // checked.
  3831. const MemberExpr *Member = nullptr;
  3832. while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
  3833. StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
  3834. LastRecord.PossibleDerefs.erase(StrippedExpr);
  3835. }
  3836. void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
  3837. QualType ResultTy = E->getType();
  3838. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  3839. // Bail if the element is an array since it is not memory access.
  3840. if (isa<ArrayType>(ResultTy))
  3841. return;
  3842. if (ResultTy->hasAttr(attr::NoDeref)) {
  3843. LastRecord.PossibleDerefs.insert(E);
  3844. return;
  3845. }
  3846. // Check if the base type is a pointer to a member access of a struct
  3847. // marked with noderef.
  3848. const Expr *Base = E->getBase();
  3849. QualType BaseTy = Base->getType();
  3850. if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
  3851. // Not a pointer access
  3852. return;
  3853. const MemberExpr *Member = nullptr;
  3854. while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
  3855. Member->isArrow())
  3856. Base = Member->getBase();
  3857. if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
  3858. if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
  3859. LastRecord.PossibleDerefs.insert(E);
  3860. }
  3861. }
  3862. ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
  3863. Expr *LowerBound,
  3864. SourceLocation ColonLoc, Expr *Length,
  3865. SourceLocation RBLoc) {
  3866. if (Base->getType()->isPlaceholderType() &&
  3867. !Base->getType()->isSpecificPlaceholderType(
  3868. BuiltinType::OMPArraySection)) {
  3869. ExprResult Result = CheckPlaceholderExpr(Base);
  3870. if (Result.isInvalid())
  3871. return ExprError();
  3872. Base = Result.get();
  3873. }
  3874. if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
  3875. ExprResult Result = CheckPlaceholderExpr(LowerBound);
  3876. if (Result.isInvalid())
  3877. return ExprError();
  3878. Result = DefaultLvalueConversion(Result.get());
  3879. if (Result.isInvalid())
  3880. return ExprError();
  3881. LowerBound = Result.get();
  3882. }
  3883. if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
  3884. ExprResult Result = CheckPlaceholderExpr(Length);
  3885. if (Result.isInvalid())
  3886. return ExprError();
  3887. Result = DefaultLvalueConversion(Result.get());
  3888. if (Result.isInvalid())
  3889. return ExprError();
  3890. Length = Result.get();
  3891. }
  3892. // Build an unanalyzed expression if either operand is type-dependent.
  3893. if (Base->isTypeDependent() ||
  3894. (LowerBound &&
  3895. (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
  3896. (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
  3897. return new (Context)
  3898. OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
  3899. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3900. }
  3901. // Perform default conversions.
  3902. QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
  3903. QualType ResultTy;
  3904. if (OriginalTy->isAnyPointerType()) {
  3905. ResultTy = OriginalTy->getPointeeType();
  3906. } else if (OriginalTy->isArrayType()) {
  3907. ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
  3908. } else {
  3909. return ExprError(
  3910. Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
  3911. << Base->getSourceRange());
  3912. }
  3913. // C99 6.5.2.1p1
  3914. if (LowerBound) {
  3915. auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
  3916. LowerBound);
  3917. if (Res.isInvalid())
  3918. return ExprError(Diag(LowerBound->getExprLoc(),
  3919. diag::err_omp_typecheck_section_not_integer)
  3920. << 0 << LowerBound->getSourceRange());
  3921. LowerBound = Res.get();
  3922. if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3923. LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3924. Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
  3925. << 0 << LowerBound->getSourceRange();
  3926. }
  3927. if (Length) {
  3928. auto Res =
  3929. PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
  3930. if (Res.isInvalid())
  3931. return ExprError(Diag(Length->getExprLoc(),
  3932. diag::err_omp_typecheck_section_not_integer)
  3933. << 1 << Length->getSourceRange());
  3934. Length = Res.get();
  3935. if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3936. Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3937. Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
  3938. << 1 << Length->getSourceRange();
  3939. }
  3940. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3941. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3942. // type. Note that functions are not objects, and that (in C99 parlance)
  3943. // incomplete types are not object types.
  3944. if (ResultTy->isFunctionType()) {
  3945. Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
  3946. << ResultTy << Base->getSourceRange();
  3947. return ExprError();
  3948. }
  3949. if (RequireCompleteType(Base->getExprLoc(), ResultTy,
  3950. diag::err_omp_section_incomplete_type, Base))
  3951. return ExprError();
  3952. if (LowerBound && !OriginalTy->isAnyPointerType()) {
  3953. Expr::EvalResult Result;
  3954. if (LowerBound->EvaluateAsInt(Result, Context)) {
  3955. // OpenMP 4.5, [2.4 Array Sections]
  3956. // The array section must be a subset of the original array.
  3957. llvm::APSInt LowerBoundValue = Result.Val.getInt();
  3958. if (LowerBoundValue.isNegative()) {
  3959. Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
  3960. << LowerBound->getSourceRange();
  3961. return ExprError();
  3962. }
  3963. }
  3964. }
  3965. if (Length) {
  3966. Expr::EvalResult Result;
  3967. if (Length->EvaluateAsInt(Result, Context)) {
  3968. // OpenMP 4.5, [2.4 Array Sections]
  3969. // The length must evaluate to non-negative integers.
  3970. llvm::APSInt LengthValue = Result.Val.getInt();
  3971. if (LengthValue.isNegative()) {
  3972. Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
  3973. << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
  3974. << Length->getSourceRange();
  3975. return ExprError();
  3976. }
  3977. }
  3978. } else if (ColonLoc.isValid() &&
  3979. (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
  3980. !OriginalTy->isVariableArrayType()))) {
  3981. // OpenMP 4.5, [2.4 Array Sections]
  3982. // When the size of the array dimension is not known, the length must be
  3983. // specified explicitly.
  3984. Diag(ColonLoc, diag::err_omp_section_length_undefined)
  3985. << (!OriginalTy.isNull() && OriginalTy->isArrayType());
  3986. return ExprError();
  3987. }
  3988. if (!Base->getType()->isSpecificPlaceholderType(
  3989. BuiltinType::OMPArraySection)) {
  3990. ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
  3991. if (Result.isInvalid())
  3992. return ExprError();
  3993. Base = Result.get();
  3994. }
  3995. return new (Context)
  3996. OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
  3997. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3998. }
  3999. ExprResult
  4000. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  4001. Expr *Idx, SourceLocation RLoc) {
  4002. Expr *LHSExp = Base;
  4003. Expr *RHSExp = Idx;
  4004. ExprValueKind VK = VK_LValue;
  4005. ExprObjectKind OK = OK_Ordinary;
  4006. // Per C++ core issue 1213, the result is an xvalue if either operand is
  4007. // a non-lvalue array, and an lvalue otherwise.
  4008. if (getLangOpts().CPlusPlus11) {
  4009. for (auto *Op : {LHSExp, RHSExp}) {
  4010. Op = Op->IgnoreImplicit();
  4011. if (Op->getType()->isArrayType() && !Op->isLValue())
  4012. VK = VK_XValue;
  4013. }
  4014. }
  4015. // Perform default conversions.
  4016. if (!LHSExp->getType()->getAs<VectorType>()) {
  4017. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  4018. if (Result.isInvalid())
  4019. return ExprError();
  4020. LHSExp = Result.get();
  4021. }
  4022. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  4023. if (Result.isInvalid())
  4024. return ExprError();
  4025. RHSExp = Result.get();
  4026. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  4027. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  4028. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  4029. // in the subscript position. As a result, we need to derive the array base
  4030. // and index from the expression types.
  4031. Expr *BaseExpr, *IndexExpr;
  4032. QualType ResultType;
  4033. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  4034. BaseExpr = LHSExp;
  4035. IndexExpr = RHSExp;
  4036. ResultType = Context.DependentTy;
  4037. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  4038. BaseExpr = LHSExp;
  4039. IndexExpr = RHSExp;
  4040. ResultType = PTy->getPointeeType();
  4041. } else if (const ObjCObjectPointerType *PTy =
  4042. LHSTy->getAs<ObjCObjectPointerType>()) {
  4043. BaseExpr = LHSExp;
  4044. IndexExpr = RHSExp;
  4045. // Use custom logic if this should be the pseudo-object subscript
  4046. // expression.
  4047. if (!LangOpts.isSubscriptPointerArithmetic())
  4048. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  4049. nullptr);
  4050. ResultType = PTy->getPointeeType();
  4051. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  4052. // Handle the uncommon case of "123[Ptr]".
  4053. BaseExpr = RHSExp;
  4054. IndexExpr = LHSExp;
  4055. ResultType = PTy->getPointeeType();
  4056. } else if (const ObjCObjectPointerType *PTy =
  4057. RHSTy->getAs<ObjCObjectPointerType>()) {
  4058. // Handle the uncommon case of "123[Ptr]".
  4059. BaseExpr = RHSExp;
  4060. IndexExpr = LHSExp;
  4061. ResultType = PTy->getPointeeType();
  4062. if (!LangOpts.isSubscriptPointerArithmetic()) {
  4063. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  4064. << ResultType << BaseExpr->getSourceRange();
  4065. return ExprError();
  4066. }
  4067. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  4068. BaseExpr = LHSExp; // vectors: V[123]
  4069. IndexExpr = RHSExp;
  4070. // We apply C++ DR1213 to vector subscripting too.
  4071. if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
  4072. ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
  4073. if (Materialized.isInvalid())
  4074. return ExprError();
  4075. LHSExp = Materialized.get();
  4076. }
  4077. VK = LHSExp->getValueKind();
  4078. if (VK != VK_RValue)
  4079. OK = OK_VectorComponent;
  4080. ResultType = VTy->getElementType();
  4081. QualType BaseType = BaseExpr->getType();
  4082. Qualifiers BaseQuals = BaseType.getQualifiers();
  4083. Qualifiers MemberQuals = ResultType.getQualifiers();
  4084. Qualifiers Combined = BaseQuals + MemberQuals;
  4085. if (Combined != MemberQuals)
  4086. ResultType = Context.getQualifiedType(ResultType, Combined);
  4087. } else if (LHSTy->isArrayType()) {
  4088. // If we see an array that wasn't promoted by
  4089. // DefaultFunctionArrayLvalueConversion, it must be an array that
  4090. // wasn't promoted because of the C90 rule that doesn't
  4091. // allow promoting non-lvalue arrays. Warn, then
  4092. // force the promotion here.
  4093. Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  4094. << LHSExp->getSourceRange();
  4095. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  4096. CK_ArrayToPointerDecay).get();
  4097. LHSTy = LHSExp->getType();
  4098. BaseExpr = LHSExp;
  4099. IndexExpr = RHSExp;
  4100. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  4101. } else if (RHSTy->isArrayType()) {
  4102. // Same as previous, except for 123[f().a] case
  4103. Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  4104. << RHSExp->getSourceRange();
  4105. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  4106. CK_ArrayToPointerDecay).get();
  4107. RHSTy = RHSExp->getType();
  4108. BaseExpr = RHSExp;
  4109. IndexExpr = LHSExp;
  4110. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  4111. } else {
  4112. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  4113. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  4114. }
  4115. // C99 6.5.2.1p1
  4116. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  4117. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  4118. << IndexExpr->getSourceRange());
  4119. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  4120. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  4121. && !IndexExpr->isTypeDependent())
  4122. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  4123. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  4124. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  4125. // type. Note that Functions are not objects, and that (in C99 parlance)
  4126. // incomplete types are not object types.
  4127. if (ResultType->isFunctionType()) {
  4128. Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
  4129. << ResultType << BaseExpr->getSourceRange();
  4130. return ExprError();
  4131. }
  4132. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  4133. // GNU extension: subscripting on pointer to void
  4134. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  4135. << BaseExpr->getSourceRange();
  4136. // C forbids expressions of unqualified void type from being l-values.
  4137. // See IsCForbiddenLValueType.
  4138. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  4139. } else if (!ResultType->isDependentType() &&
  4140. RequireCompleteType(LLoc, ResultType,
  4141. diag::err_subscript_incomplete_type, BaseExpr))
  4142. return ExprError();
  4143. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  4144. !ResultType.isCForbiddenLValueType());
  4145. return new (Context)
  4146. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  4147. }
  4148. bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
  4149. ParmVarDecl *Param) {
  4150. if (Param->hasUnparsedDefaultArg()) {
  4151. Diag(CallLoc,
  4152. diag::err_use_of_default_argument_to_function_declared_later) <<
  4153. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  4154. Diag(UnparsedDefaultArgLocs[Param],
  4155. diag::note_default_argument_declared_here);
  4156. return true;
  4157. }
  4158. if (Param->hasUninstantiatedDefaultArg()) {
  4159. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  4160. EnterExpressionEvaluationContext EvalContext(
  4161. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  4162. // Instantiate the expression.
  4163. //
  4164. // FIXME: Pass in a correct Pattern argument, otherwise
  4165. // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
  4166. //
  4167. // template<typename T>
  4168. // struct A {
  4169. // static int FooImpl();
  4170. //
  4171. // template<typename Tp>
  4172. // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
  4173. // // template argument list [[T], [Tp]], should be [[Tp]].
  4174. // friend A<Tp> Foo(int a);
  4175. // };
  4176. //
  4177. // template<typename T>
  4178. // A<T> Foo(int a = A<T>::FooImpl());
  4179. MultiLevelTemplateArgumentList MutiLevelArgList
  4180. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  4181. InstantiatingTemplate Inst(*this, CallLoc, Param,
  4182. MutiLevelArgList.getInnermost());
  4183. if (Inst.isInvalid())
  4184. return true;
  4185. if (Inst.isAlreadyInstantiating()) {
  4186. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  4187. Param->setInvalidDecl();
  4188. return true;
  4189. }
  4190. ExprResult Result;
  4191. {
  4192. // C++ [dcl.fct.default]p5:
  4193. // The names in the [default argument] expression are bound, and
  4194. // the semantic constraints are checked, at the point where the
  4195. // default argument expression appears.
  4196. ContextRAII SavedContext(*this, FD);
  4197. LocalInstantiationScope Local(*this);
  4198. Result = SubstInitializer(UninstExpr, MutiLevelArgList,
  4199. /*DirectInit*/false);
  4200. }
  4201. if (Result.isInvalid())
  4202. return true;
  4203. // Check the expression as an initializer for the parameter.
  4204. InitializedEntity Entity
  4205. = InitializedEntity::InitializeParameter(Context, Param);
  4206. InitializationKind Kind = InitializationKind::CreateCopy(
  4207. Param->getLocation(),
  4208. /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
  4209. Expr *ResultE = Result.getAs<Expr>();
  4210. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  4211. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  4212. if (Result.isInvalid())
  4213. return true;
  4214. Result =
  4215. ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
  4216. /*DiscardedValue*/ false);
  4217. if (Result.isInvalid())
  4218. return true;
  4219. // Remember the instantiated default argument.
  4220. Param->setDefaultArg(Result.getAs<Expr>());
  4221. if (ASTMutationListener *L = getASTMutationListener()) {
  4222. L->DefaultArgumentInstantiated(Param);
  4223. }
  4224. }
  4225. // If the default argument expression is not set yet, we are building it now.
  4226. if (!Param->hasInit()) {
  4227. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  4228. Param->setInvalidDecl();
  4229. return true;
  4230. }
  4231. // If the default expression creates temporaries, we need to
  4232. // push them to the current stack of expression temporaries so they'll
  4233. // be properly destroyed.
  4234. // FIXME: We should really be rebuilding the default argument with new
  4235. // bound temporaries; see the comment in PR5810.
  4236. // We don't need to do that with block decls, though, because
  4237. // blocks in default argument expression can never capture anything.
  4238. if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
  4239. // Set the "needs cleanups" bit regardless of whether there are
  4240. // any explicit objects.
  4241. Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
  4242. // Append all the objects to the cleanup list. Right now, this
  4243. // should always be a no-op, because blocks in default argument
  4244. // expressions should never be able to capture anything.
  4245. assert(!Init->getNumObjects() &&
  4246. "default argument expression has capturing blocks?");
  4247. }
  4248. // We already type-checked the argument, so we know it works.
  4249. // Just mark all of the declarations in this potentially-evaluated expression
  4250. // as being "referenced".
  4251. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  4252. /*SkipLocalVariables=*/true);
  4253. return false;
  4254. }
  4255. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  4256. FunctionDecl *FD, ParmVarDecl *Param) {
  4257. if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
  4258. return ExprError();
  4259. return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
  4260. }
  4261. Sema::VariadicCallType
  4262. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  4263. Expr *Fn) {
  4264. if (Proto && Proto->isVariadic()) {
  4265. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  4266. return VariadicConstructor;
  4267. else if (Fn && Fn->getType()->isBlockPointerType())
  4268. return VariadicBlock;
  4269. else if (FDecl) {
  4270. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4271. if (Method->isInstance())
  4272. return VariadicMethod;
  4273. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  4274. return VariadicMethod;
  4275. return VariadicFunction;
  4276. }
  4277. return VariadicDoesNotApply;
  4278. }
  4279. namespace {
  4280. class FunctionCallCCC final : public FunctionCallFilterCCC {
  4281. public:
  4282. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  4283. unsigned NumArgs, MemberExpr *ME)
  4284. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  4285. FunctionName(FuncName) {}
  4286. bool ValidateCandidate(const TypoCorrection &candidate) override {
  4287. if (!candidate.getCorrectionSpecifier() ||
  4288. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  4289. return false;
  4290. }
  4291. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  4292. }
  4293. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  4294. return llvm::make_unique<FunctionCallCCC>(*this);
  4295. }
  4296. private:
  4297. const IdentifierInfo *const FunctionName;
  4298. };
  4299. }
  4300. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  4301. FunctionDecl *FDecl,
  4302. ArrayRef<Expr *> Args) {
  4303. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  4304. DeclarationName FuncName = FDecl->getDeclName();
  4305. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
  4306. FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
  4307. if (TypoCorrection Corrected = S.CorrectTypo(
  4308. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  4309. S.getScopeForContext(S.CurContext), nullptr, CCC,
  4310. Sema::CTK_ErrorRecovery)) {
  4311. if (NamedDecl *ND = Corrected.getFoundDecl()) {
  4312. if (Corrected.isOverloaded()) {
  4313. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  4314. OverloadCandidateSet::iterator Best;
  4315. for (NamedDecl *CD : Corrected) {
  4316. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  4317. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  4318. OCS);
  4319. }
  4320. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  4321. case OR_Success:
  4322. ND = Best->FoundDecl;
  4323. Corrected.setCorrectionDecl(ND);
  4324. break;
  4325. default:
  4326. break;
  4327. }
  4328. }
  4329. ND = ND->getUnderlyingDecl();
  4330. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
  4331. return Corrected;
  4332. }
  4333. }
  4334. return TypoCorrection();
  4335. }
  4336. /// ConvertArgumentsForCall - Converts the arguments specified in
  4337. /// Args/NumArgs to the parameter types of the function FDecl with
  4338. /// function prototype Proto. Call is the call expression itself, and
  4339. /// Fn is the function expression. For a C++ member function, this
  4340. /// routine does not attempt to convert the object argument. Returns
  4341. /// true if the call is ill-formed.
  4342. bool
  4343. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  4344. FunctionDecl *FDecl,
  4345. const FunctionProtoType *Proto,
  4346. ArrayRef<Expr *> Args,
  4347. SourceLocation RParenLoc,
  4348. bool IsExecConfig) {
  4349. // Bail out early if calling a builtin with custom typechecking.
  4350. if (FDecl)
  4351. if (unsigned ID = FDecl->getBuiltinID())
  4352. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  4353. return false;
  4354. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  4355. // assignment, to the types of the corresponding parameter, ...
  4356. unsigned NumParams = Proto->getNumParams();
  4357. bool Invalid = false;
  4358. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  4359. unsigned FnKind = Fn->getType()->isBlockPointerType()
  4360. ? 1 /* block */
  4361. : (IsExecConfig ? 3 /* kernel function (exec config) */
  4362. : 0 /* function */);
  4363. // If too few arguments are available (and we don't have default
  4364. // arguments for the remaining parameters), don't make the call.
  4365. if (Args.size() < NumParams) {
  4366. if (Args.size() < MinArgs) {
  4367. TypoCorrection TC;
  4368. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4369. unsigned diag_id =
  4370. MinArgs == NumParams && !Proto->isVariadic()
  4371. ? diag::err_typecheck_call_too_few_args_suggest
  4372. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  4373. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  4374. << static_cast<unsigned>(Args.size())
  4375. << TC.getCorrectionRange());
  4376. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  4377. Diag(RParenLoc,
  4378. MinArgs == NumParams && !Proto->isVariadic()
  4379. ? diag::err_typecheck_call_too_few_args_one
  4380. : diag::err_typecheck_call_too_few_args_at_least_one)
  4381. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  4382. else
  4383. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  4384. ? diag::err_typecheck_call_too_few_args
  4385. : diag::err_typecheck_call_too_few_args_at_least)
  4386. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  4387. << Fn->getSourceRange();
  4388. // Emit the location of the prototype.
  4389. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4390. Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
  4391. return true;
  4392. }
  4393. // We reserve space for the default arguments when we create
  4394. // the call expression, before calling ConvertArgumentsForCall.
  4395. assert((Call->getNumArgs() == NumParams) &&
  4396. "We should have reserved space for the default arguments before!");
  4397. }
  4398. // If too many are passed and not variadic, error on the extras and drop
  4399. // them.
  4400. if (Args.size() > NumParams) {
  4401. if (!Proto->isVariadic()) {
  4402. TypoCorrection TC;
  4403. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4404. unsigned diag_id =
  4405. MinArgs == NumParams && !Proto->isVariadic()
  4406. ? diag::err_typecheck_call_too_many_args_suggest
  4407. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  4408. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  4409. << static_cast<unsigned>(Args.size())
  4410. << TC.getCorrectionRange());
  4411. } else if (NumParams == 1 && FDecl &&
  4412. FDecl->getParamDecl(0)->getDeclName())
  4413. Diag(Args[NumParams]->getBeginLoc(),
  4414. MinArgs == NumParams
  4415. ? diag::err_typecheck_call_too_many_args_one
  4416. : diag::err_typecheck_call_too_many_args_at_most_one)
  4417. << FnKind << FDecl->getParamDecl(0)
  4418. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  4419. << SourceRange(Args[NumParams]->getBeginLoc(),
  4420. Args.back()->getEndLoc());
  4421. else
  4422. Diag(Args[NumParams]->getBeginLoc(),
  4423. MinArgs == NumParams
  4424. ? diag::err_typecheck_call_too_many_args
  4425. : diag::err_typecheck_call_too_many_args_at_most)
  4426. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  4427. << Fn->getSourceRange()
  4428. << SourceRange(Args[NumParams]->getBeginLoc(),
  4429. Args.back()->getEndLoc());
  4430. // Emit the location of the prototype.
  4431. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4432. Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
  4433. // This deletes the extra arguments.
  4434. Call->shrinkNumArgs(NumParams);
  4435. return true;
  4436. }
  4437. }
  4438. SmallVector<Expr *, 8> AllArgs;
  4439. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  4440. Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
  4441. AllArgs, CallType);
  4442. if (Invalid)
  4443. return true;
  4444. unsigned TotalNumArgs = AllArgs.size();
  4445. for (unsigned i = 0; i < TotalNumArgs; ++i)
  4446. Call->setArg(i, AllArgs[i]);
  4447. return false;
  4448. }
  4449. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  4450. const FunctionProtoType *Proto,
  4451. unsigned FirstParam, ArrayRef<Expr *> Args,
  4452. SmallVectorImpl<Expr *> &AllArgs,
  4453. VariadicCallType CallType, bool AllowExplicit,
  4454. bool IsListInitialization) {
  4455. unsigned NumParams = Proto->getNumParams();
  4456. bool Invalid = false;
  4457. size_t ArgIx = 0;
  4458. // Continue to check argument types (even if we have too few/many args).
  4459. for (unsigned i = FirstParam; i < NumParams; i++) {
  4460. QualType ProtoArgType = Proto->getParamType(i);
  4461. Expr *Arg;
  4462. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  4463. if (ArgIx < Args.size()) {
  4464. Arg = Args[ArgIx++];
  4465. if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
  4466. diag::err_call_incomplete_argument, Arg))
  4467. return true;
  4468. // Strip the unbridged-cast placeholder expression off, if applicable.
  4469. bool CFAudited = false;
  4470. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  4471. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4472. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4473. Arg = stripARCUnbridgedCast(Arg);
  4474. else if (getLangOpts().ObjCAutoRefCount &&
  4475. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4476. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4477. CFAudited = true;
  4478. if (Proto->getExtParameterInfo(i).isNoEscape())
  4479. if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
  4480. BE->getBlockDecl()->setDoesNotEscape();
  4481. InitializedEntity Entity =
  4482. Param ? InitializedEntity::InitializeParameter(Context, Param,
  4483. ProtoArgType)
  4484. : InitializedEntity::InitializeParameter(
  4485. Context, ProtoArgType, Proto->isParamConsumed(i));
  4486. // Remember that parameter belongs to a CF audited API.
  4487. if (CFAudited)
  4488. Entity.setParameterCFAudited();
  4489. ExprResult ArgE = PerformCopyInitialization(
  4490. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  4491. if (ArgE.isInvalid())
  4492. return true;
  4493. Arg = ArgE.getAs<Expr>();
  4494. } else {
  4495. assert(Param && "can't use default arguments without a known callee");
  4496. ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  4497. if (ArgExpr.isInvalid())
  4498. return true;
  4499. Arg = ArgExpr.getAs<Expr>();
  4500. }
  4501. // Check for array bounds violations for each argument to the call. This
  4502. // check only triggers warnings when the argument isn't a more complex Expr
  4503. // with its own checking, such as a BinaryOperator.
  4504. CheckArrayAccess(Arg);
  4505. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  4506. CheckStaticArrayArgument(CallLoc, Param, Arg);
  4507. AllArgs.push_back(Arg);
  4508. }
  4509. // If this is a variadic call, handle args passed through "...".
  4510. if (CallType != VariadicDoesNotApply) {
  4511. // Assume that extern "C" functions with variadic arguments that
  4512. // return __unknown_anytype aren't *really* variadic.
  4513. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  4514. FDecl->isExternC()) {
  4515. for (Expr *A : Args.slice(ArgIx)) {
  4516. QualType paramType; // ignored
  4517. ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
  4518. Invalid |= arg.isInvalid();
  4519. AllArgs.push_back(arg.get());
  4520. }
  4521. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  4522. } else {
  4523. for (Expr *A : Args.slice(ArgIx)) {
  4524. ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
  4525. Invalid |= Arg.isInvalid();
  4526. AllArgs.push_back(Arg.get());
  4527. }
  4528. }
  4529. // Check for array bounds violations.
  4530. for (Expr *A : Args.slice(ArgIx))
  4531. CheckArrayAccess(A);
  4532. }
  4533. return Invalid;
  4534. }
  4535. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  4536. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  4537. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  4538. TL = DTL.getOriginalLoc();
  4539. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  4540. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  4541. << ATL.getLocalSourceRange();
  4542. }
  4543. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  4544. /// array parameter, check that it is non-null, and that if it is formed by
  4545. /// array-to-pointer decay, the underlying array is sufficiently large.
  4546. ///
  4547. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  4548. /// array type derivation, then for each call to the function, the value of the
  4549. /// corresponding actual argument shall provide access to the first element of
  4550. /// an array with at least as many elements as specified by the size expression.
  4551. void
  4552. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  4553. ParmVarDecl *Param,
  4554. const Expr *ArgExpr) {
  4555. // Static array parameters are not supported in C++.
  4556. if (!Param || getLangOpts().CPlusPlus)
  4557. return;
  4558. QualType OrigTy = Param->getOriginalType();
  4559. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  4560. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  4561. return;
  4562. if (ArgExpr->isNullPointerConstant(Context,
  4563. Expr::NPC_NeverValueDependent)) {
  4564. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  4565. DiagnoseCalleeStaticArrayParam(*this, Param);
  4566. return;
  4567. }
  4568. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  4569. if (!CAT)
  4570. return;
  4571. const ConstantArrayType *ArgCAT =
  4572. Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
  4573. if (!ArgCAT)
  4574. return;
  4575. if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
  4576. ArgCAT->getElementType())) {
  4577. if (ArgCAT->getSize().ult(CAT->getSize())) {
  4578. Diag(CallLoc, diag::warn_static_array_too_small)
  4579. << ArgExpr->getSourceRange()
  4580. << (unsigned)ArgCAT->getSize().getZExtValue()
  4581. << (unsigned)CAT->getSize().getZExtValue() << 0;
  4582. DiagnoseCalleeStaticArrayParam(*this, Param);
  4583. }
  4584. return;
  4585. }
  4586. Optional<CharUnits> ArgSize =
  4587. getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
  4588. Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
  4589. if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
  4590. Diag(CallLoc, diag::warn_static_array_too_small)
  4591. << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
  4592. << (unsigned)ParmSize->getQuantity() << 1;
  4593. DiagnoseCalleeStaticArrayParam(*this, Param);
  4594. }
  4595. }
  4596. /// Given a function expression of unknown-any type, try to rebuild it
  4597. /// to have a function type.
  4598. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4599. /// Is the given type a placeholder that we need to lower out
  4600. /// immediately during argument processing?
  4601. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4602. // Placeholders are never sugared.
  4603. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4604. if (!placeholder) return false;
  4605. switch (placeholder->getKind()) {
  4606. // Ignore all the non-placeholder types.
  4607. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  4608. case BuiltinType::Id:
  4609. #include "clang/Basic/OpenCLImageTypes.def"
  4610. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  4611. case BuiltinType::Id:
  4612. #include "clang/Basic/OpenCLExtensionTypes.def"
  4613. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4614. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4615. #include "clang/AST/BuiltinTypes.def"
  4616. return false;
  4617. // We cannot lower out overload sets; they might validly be resolved
  4618. // by the call machinery.
  4619. case BuiltinType::Overload:
  4620. return false;
  4621. // Unbridged casts in ARC can be handled in some call positions and
  4622. // should be left in place.
  4623. case BuiltinType::ARCUnbridgedCast:
  4624. return false;
  4625. // Pseudo-objects should be converted as soon as possible.
  4626. case BuiltinType::PseudoObject:
  4627. return true;
  4628. // The debugger mode could theoretically but currently does not try
  4629. // to resolve unknown-typed arguments based on known parameter types.
  4630. case BuiltinType::UnknownAny:
  4631. return true;
  4632. // These are always invalid as call arguments and should be reported.
  4633. case BuiltinType::BoundMember:
  4634. case BuiltinType::BuiltinFn:
  4635. case BuiltinType::OMPArraySection:
  4636. return true;
  4637. }
  4638. llvm_unreachable("bad builtin type kind");
  4639. }
  4640. /// Check an argument list for placeholders that we won't try to
  4641. /// handle later.
  4642. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4643. // Apply this processing to all the arguments at once instead of
  4644. // dying at the first failure.
  4645. bool hasInvalid = false;
  4646. for (size_t i = 0, e = args.size(); i != e; i++) {
  4647. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4648. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4649. if (result.isInvalid()) hasInvalid = true;
  4650. else args[i] = result.get();
  4651. } else if (hasInvalid) {
  4652. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4653. }
  4654. }
  4655. return hasInvalid;
  4656. }
  4657. /// If a builtin function has a pointer argument with no explicit address
  4658. /// space, then it should be able to accept a pointer to any address
  4659. /// space as input. In order to do this, we need to replace the
  4660. /// standard builtin declaration with one that uses the same address space
  4661. /// as the call.
  4662. ///
  4663. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4664. /// it does not contain any pointer arguments without
  4665. /// an address space qualifer. Otherwise the rewritten
  4666. /// FunctionDecl is returned.
  4667. /// TODO: Handle pointer return types.
  4668. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4669. const FunctionDecl *FDecl,
  4670. MultiExprArg ArgExprs) {
  4671. QualType DeclType = FDecl->getType();
  4672. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4673. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
  4674. !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
  4675. return nullptr;
  4676. bool NeedsNewDecl = false;
  4677. unsigned i = 0;
  4678. SmallVector<QualType, 8> OverloadParams;
  4679. for (QualType ParamType : FT->param_types()) {
  4680. // Convert array arguments to pointer to simplify type lookup.
  4681. ExprResult ArgRes =
  4682. Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
  4683. if (ArgRes.isInvalid())
  4684. return nullptr;
  4685. Expr *Arg = ArgRes.get();
  4686. QualType ArgType = Arg->getType();
  4687. if (!ParamType->isPointerType() ||
  4688. ParamType.getQualifiers().hasAddressSpace() ||
  4689. !ArgType->isPointerType() ||
  4690. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4691. OverloadParams.push_back(ParamType);
  4692. continue;
  4693. }
  4694. QualType PointeeType = ParamType->getPointeeType();
  4695. if (PointeeType.getQualifiers().hasAddressSpace())
  4696. continue;
  4697. NeedsNewDecl = true;
  4698. LangAS AS = ArgType->getPointeeType().getAddressSpace();
  4699. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4700. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4701. }
  4702. if (!NeedsNewDecl)
  4703. return nullptr;
  4704. FunctionProtoType::ExtProtoInfo EPI;
  4705. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4706. OverloadParams, EPI);
  4707. DeclContext *Parent = Context.getTranslationUnitDecl();
  4708. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4709. FDecl->getLocation(),
  4710. FDecl->getLocation(),
  4711. FDecl->getIdentifier(),
  4712. OverloadTy,
  4713. /*TInfo=*/nullptr,
  4714. SC_Extern, false,
  4715. /*hasPrototype=*/true);
  4716. SmallVector<ParmVarDecl*, 16> Params;
  4717. FT = cast<FunctionProtoType>(OverloadTy);
  4718. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4719. QualType ParamType = FT->getParamType(i);
  4720. ParmVarDecl *Parm =
  4721. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4722. SourceLocation(), nullptr, ParamType,
  4723. /*TInfo=*/nullptr, SC_None, nullptr);
  4724. Parm->setScopeInfo(0, i);
  4725. Params.push_back(Parm);
  4726. }
  4727. OverloadDecl->setParams(Params);
  4728. return OverloadDecl;
  4729. }
  4730. static void checkDirectCallValidity(Sema &S, const Expr *Fn,
  4731. FunctionDecl *Callee,
  4732. MultiExprArg ArgExprs) {
  4733. // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
  4734. // similar attributes) really don't like it when functions are called with an
  4735. // invalid number of args.
  4736. if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
  4737. /*PartialOverloading=*/false) &&
  4738. !Callee->isVariadic())
  4739. return;
  4740. if (Callee->getMinRequiredArguments() > ArgExprs.size())
  4741. return;
  4742. if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
  4743. S.Diag(Fn->getBeginLoc(),
  4744. isa<CXXMethodDecl>(Callee)
  4745. ? diag::err_ovl_no_viable_member_function_in_call
  4746. : diag::err_ovl_no_viable_function_in_call)
  4747. << Callee << Callee->getSourceRange();
  4748. S.Diag(Callee->getLocation(),
  4749. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  4750. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4751. return;
  4752. }
  4753. }
  4754. static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
  4755. const UnresolvedMemberExpr *const UME, Sema &S) {
  4756. const auto GetFunctionLevelDCIfCXXClass =
  4757. [](Sema &S) -> const CXXRecordDecl * {
  4758. const DeclContext *const DC = S.getFunctionLevelDeclContext();
  4759. if (!DC || !DC->getParent())
  4760. return nullptr;
  4761. // If the call to some member function was made from within a member
  4762. // function body 'M' return return 'M's parent.
  4763. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  4764. return MD->getParent()->getCanonicalDecl();
  4765. // else the call was made from within a default member initializer of a
  4766. // class, so return the class.
  4767. if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
  4768. return RD->getCanonicalDecl();
  4769. return nullptr;
  4770. };
  4771. // If our DeclContext is neither a member function nor a class (in the
  4772. // case of a lambda in a default member initializer), we can't have an
  4773. // enclosing 'this'.
  4774. const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
  4775. if (!CurParentClass)
  4776. return false;
  4777. // The naming class for implicit member functions call is the class in which
  4778. // name lookup starts.
  4779. const CXXRecordDecl *const NamingClass =
  4780. UME->getNamingClass()->getCanonicalDecl();
  4781. assert(NamingClass && "Must have naming class even for implicit access");
  4782. // If the unresolved member functions were found in a 'naming class' that is
  4783. // related (either the same or derived from) to the class that contains the
  4784. // member function that itself contained the implicit member access.
  4785. return CurParentClass == NamingClass ||
  4786. CurParentClass->isDerivedFrom(NamingClass);
  4787. }
  4788. static void
  4789. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4790. Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
  4791. if (!UME)
  4792. return;
  4793. LambdaScopeInfo *const CurLSI = S.getCurLambda();
  4794. // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
  4795. // already been captured, or if this is an implicit member function call (if
  4796. // it isn't, an attempt to capture 'this' should already have been made).
  4797. if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
  4798. !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
  4799. return;
  4800. // Check if the naming class in which the unresolved members were found is
  4801. // related (same as or is a base of) to the enclosing class.
  4802. if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
  4803. return;
  4804. DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
  4805. // If the enclosing function is not dependent, then this lambda is
  4806. // capture ready, so if we can capture this, do so.
  4807. if (!EnclosingFunctionCtx->isDependentContext()) {
  4808. // If the current lambda and all enclosing lambdas can capture 'this' -
  4809. // then go ahead and capture 'this' (since our unresolved overload set
  4810. // contains at least one non-static member function).
  4811. if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
  4812. S.CheckCXXThisCapture(CallLoc);
  4813. } else if (S.CurContext->isDependentContext()) {
  4814. // ... since this is an implicit member reference, that might potentially
  4815. // involve a 'this' capture, mark 'this' for potential capture in
  4816. // enclosing lambdas.
  4817. if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
  4818. CurLSI->addPotentialThisCapture(CallLoc);
  4819. }
  4820. }
  4821. ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  4822. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4823. Expr *ExecConfig) {
  4824. ExprResult Call =
  4825. BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
  4826. if (Call.isInvalid())
  4827. return Call;
  4828. // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
  4829. // language modes.
  4830. if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
  4831. if (ULE->hasExplicitTemplateArgs() &&
  4832. ULE->decls_begin() == ULE->decls_end()) {
  4833. Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
  4834. ? diag::warn_cxx17_compat_adl_only_template_id
  4835. : diag::ext_adl_only_template_id)
  4836. << ULE->getName();
  4837. }
  4838. }
  4839. return Call;
  4840. }
  4841. /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
  4842. /// This provides the location of the left/right parens and a list of comma
  4843. /// locations.
  4844. ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  4845. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4846. Expr *ExecConfig, bool IsExecConfig) {
  4847. // Since this might be a postfix expression, get rid of ParenListExprs.
  4848. ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
  4849. if (Result.isInvalid()) return ExprError();
  4850. Fn = Result.get();
  4851. if (checkArgsForPlaceholders(*this, ArgExprs))
  4852. return ExprError();
  4853. if (getLangOpts().CPlusPlus) {
  4854. // If this is a pseudo-destructor expression, build the call immediately.
  4855. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4856. if (!ArgExprs.empty()) {
  4857. // Pseudo-destructor calls should not have any arguments.
  4858. Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
  4859. << FixItHint::CreateRemoval(
  4860. SourceRange(ArgExprs.front()->getBeginLoc(),
  4861. ArgExprs.back()->getEndLoc()));
  4862. }
  4863. return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
  4864. VK_RValue, RParenLoc);
  4865. }
  4866. if (Fn->getType() == Context.PseudoObjectTy) {
  4867. ExprResult result = CheckPlaceholderExpr(Fn);
  4868. if (result.isInvalid()) return ExprError();
  4869. Fn = result.get();
  4870. }
  4871. // Determine whether this is a dependent call inside a C++ template,
  4872. // in which case we won't do any semantic analysis now.
  4873. if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
  4874. if (ExecConfig) {
  4875. return CUDAKernelCallExpr::Create(
  4876. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4877. Context.DependentTy, VK_RValue, RParenLoc);
  4878. } else {
  4879. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4880. *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
  4881. Fn->getBeginLoc());
  4882. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  4883. VK_RValue, RParenLoc);
  4884. }
  4885. }
  4886. // Determine whether this is a call to an object (C++ [over.call.object]).
  4887. if (Fn->getType()->isRecordType())
  4888. return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
  4889. RParenLoc);
  4890. if (Fn->getType() == Context.UnknownAnyTy) {
  4891. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4892. if (result.isInvalid()) return ExprError();
  4893. Fn = result.get();
  4894. }
  4895. if (Fn->getType() == Context.BoundMemberTy) {
  4896. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4897. RParenLoc);
  4898. }
  4899. }
  4900. // Check for overloaded calls. This can happen even in C due to extensions.
  4901. if (Fn->getType() == Context.OverloadTy) {
  4902. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4903. // We aren't supposed to apply this logic if there's an '&' involved.
  4904. if (!find.HasFormOfMemberPointer) {
  4905. if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4906. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  4907. VK_RValue, RParenLoc);
  4908. OverloadExpr *ovl = find.Expression;
  4909. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
  4910. return BuildOverloadedCallExpr(
  4911. Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
  4912. /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
  4913. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4914. RParenLoc);
  4915. }
  4916. }
  4917. // If we're directly calling a function, get the appropriate declaration.
  4918. if (Fn->getType() == Context.UnknownAnyTy) {
  4919. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4920. if (result.isInvalid()) return ExprError();
  4921. Fn = result.get();
  4922. }
  4923. Expr *NakedFn = Fn->IgnoreParens();
  4924. bool CallingNDeclIndirectly = false;
  4925. NamedDecl *NDecl = nullptr;
  4926. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
  4927. if (UnOp->getOpcode() == UO_AddrOf) {
  4928. CallingNDeclIndirectly = true;
  4929. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4930. }
  4931. }
  4932. if (isa<DeclRefExpr>(NakedFn)) {
  4933. NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
  4934. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  4935. if (FDecl && FDecl->getBuiltinID()) {
  4936. // Rewrite the function decl for this builtin by replacing parameters
  4937. // with no explicit address space with the address space of the arguments
  4938. // in ArgExprs.
  4939. if ((FDecl =
  4940. rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  4941. NDecl = FDecl;
  4942. Fn = DeclRefExpr::Create(
  4943. Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
  4944. SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
  4945. }
  4946. }
  4947. } else if (isa<MemberExpr>(NakedFn))
  4948. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  4949. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  4950. if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
  4951. FD, /*Complain=*/true, Fn->getBeginLoc()))
  4952. return ExprError();
  4953. if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
  4954. return ExprError();
  4955. checkDirectCallValidity(*this, Fn, FD, ArgExprs);
  4956. }
  4957. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  4958. ExecConfig, IsExecConfig);
  4959. }
  4960. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  4961. ///
  4962. /// __builtin_astype( value, dst type )
  4963. ///
  4964. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  4965. SourceLocation BuiltinLoc,
  4966. SourceLocation RParenLoc) {
  4967. ExprValueKind VK = VK_RValue;
  4968. ExprObjectKind OK = OK_Ordinary;
  4969. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  4970. QualType SrcTy = E->getType();
  4971. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  4972. return ExprError(Diag(BuiltinLoc,
  4973. diag::err_invalid_astype_of_different_size)
  4974. << DstTy
  4975. << SrcTy
  4976. << E->getSourceRange());
  4977. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  4978. }
  4979. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  4980. /// provided arguments.
  4981. ///
  4982. /// __builtin_convertvector( value, dst type )
  4983. ///
  4984. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  4985. SourceLocation BuiltinLoc,
  4986. SourceLocation RParenLoc) {
  4987. TypeSourceInfo *TInfo;
  4988. GetTypeFromParser(ParsedDestTy, &TInfo);
  4989. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  4990. }
  4991. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  4992. /// i.e. an expression not of \p OverloadTy. The expression should
  4993. /// unary-convert to an expression of function-pointer or
  4994. /// block-pointer type.
  4995. ///
  4996. /// \param NDecl the declaration being called, if available
  4997. ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  4998. SourceLocation LParenLoc,
  4999. ArrayRef<Expr *> Args,
  5000. SourceLocation RParenLoc, Expr *Config,
  5001. bool IsExecConfig, ADLCallKind UsesADL) {
  5002. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  5003. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  5004. // Functions with 'interrupt' attribute cannot be called directly.
  5005. if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
  5006. Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
  5007. return ExprError();
  5008. }
  5009. // Interrupt handlers don't save off the VFP regs automatically on ARM,
  5010. // so there's some risk when calling out to non-interrupt handler functions
  5011. // that the callee might not preserve them. This is easy to diagnose here,
  5012. // but can be very challenging to debug.
  5013. if (auto *Caller = getCurFunctionDecl())
  5014. if (Caller->hasAttr<ARMInterruptAttr>()) {
  5015. bool VFP = Context.getTargetInfo().hasFeature("vfp");
  5016. if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
  5017. Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
  5018. }
  5019. // Promote the function operand.
  5020. // We special-case function promotion here because we only allow promoting
  5021. // builtin functions to function pointers in the callee of a call.
  5022. ExprResult Result;
  5023. QualType ResultTy;
  5024. if (BuiltinID &&
  5025. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  5026. // Extract the return type from the (builtin) function pointer type.
  5027. // FIXME Several builtins still have setType in
  5028. // Sema::CheckBuiltinFunctionCall. One should review their definitions in
  5029. // Builtins.def to ensure they are correct before removing setType calls.
  5030. QualType FnPtrTy = Context.getPointerType(FDecl->getType());
  5031. Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
  5032. ResultTy = FDecl->getCallResultType();
  5033. } else {
  5034. Result = CallExprUnaryConversions(Fn);
  5035. ResultTy = Context.BoolTy;
  5036. }
  5037. if (Result.isInvalid())
  5038. return ExprError();
  5039. Fn = Result.get();
  5040. // Check for a valid function type, but only if it is not a builtin which
  5041. // requires custom type checking. These will be handled by
  5042. // CheckBuiltinFunctionCall below just after creation of the call expression.
  5043. const FunctionType *FuncT = nullptr;
  5044. if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
  5045. retry:
  5046. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  5047. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  5048. // have type pointer to function".
  5049. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  5050. if (!FuncT)
  5051. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  5052. << Fn->getType() << Fn->getSourceRange());
  5053. } else if (const BlockPointerType *BPT =
  5054. Fn->getType()->getAs<BlockPointerType>()) {
  5055. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  5056. } else {
  5057. // Handle calls to expressions of unknown-any type.
  5058. if (Fn->getType() == Context.UnknownAnyTy) {
  5059. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  5060. if (rewrite.isInvalid()) return ExprError();
  5061. Fn = rewrite.get();
  5062. goto retry;
  5063. }
  5064. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  5065. << Fn->getType() << Fn->getSourceRange());
  5066. }
  5067. }
  5068. // Get the number of parameters in the function prototype, if any.
  5069. // We will allocate space for max(Args.size(), NumParams) arguments
  5070. // in the call expression.
  5071. const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
  5072. unsigned NumParams = Proto ? Proto->getNumParams() : 0;
  5073. CallExpr *TheCall;
  5074. if (Config) {
  5075. assert(UsesADL == ADLCallKind::NotADL &&
  5076. "CUDAKernelCallExpr should not use ADL");
  5077. TheCall =
  5078. CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
  5079. ResultTy, VK_RValue, RParenLoc, NumParams);
  5080. } else {
  5081. TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
  5082. RParenLoc, NumParams, UsesADL);
  5083. }
  5084. if (!getLangOpts().CPlusPlus) {
  5085. // Forget about the nulled arguments since typo correction
  5086. // do not handle them well.
  5087. TheCall->shrinkNumArgs(Args.size());
  5088. // C cannot always handle TypoExpr nodes in builtin calls and direct
  5089. // function calls as their argument checking don't necessarily handle
  5090. // dependent types properly, so make sure any TypoExprs have been
  5091. // dealt with.
  5092. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  5093. if (!Result.isUsable()) return ExprError();
  5094. CallExpr *TheOldCall = TheCall;
  5095. TheCall = dyn_cast<CallExpr>(Result.get());
  5096. bool CorrectedTypos = TheCall != TheOldCall;
  5097. if (!TheCall) return Result;
  5098. Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
  5099. // A new call expression node was created if some typos were corrected.
  5100. // However it may not have been constructed with enough storage. In this
  5101. // case, rebuild the node with enough storage. The waste of space is
  5102. // immaterial since this only happens when some typos were corrected.
  5103. if (CorrectedTypos && Args.size() < NumParams) {
  5104. if (Config)
  5105. TheCall = CUDAKernelCallExpr::Create(
  5106. Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
  5107. RParenLoc, NumParams);
  5108. else
  5109. TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
  5110. RParenLoc, NumParams, UsesADL);
  5111. }
  5112. // We can now handle the nulled arguments for the default arguments.
  5113. TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
  5114. }
  5115. // Bail out early if calling a builtin with custom type checking.
  5116. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  5117. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  5118. if (getLangOpts().CUDA) {
  5119. if (Config) {
  5120. // CUDA: Kernel calls must be to global functions
  5121. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  5122. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  5123. << FDecl << Fn->getSourceRange());
  5124. // CUDA: Kernel function must have 'void' return type
  5125. if (!FuncT->getReturnType()->isVoidType())
  5126. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  5127. << Fn->getType() << Fn->getSourceRange());
  5128. } else {
  5129. // CUDA: Calls to global functions must be configured
  5130. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  5131. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  5132. << FDecl << Fn->getSourceRange());
  5133. }
  5134. }
  5135. // Check for a valid return type
  5136. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
  5137. FDecl))
  5138. return ExprError();
  5139. // We know the result type of the call, set it.
  5140. TheCall->setType(FuncT->getCallResultType(Context));
  5141. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  5142. if (Proto) {
  5143. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  5144. IsExecConfig))
  5145. return ExprError();
  5146. } else {
  5147. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  5148. if (FDecl) {
  5149. // Check if we have too few/too many template arguments, based
  5150. // on our knowledge of the function definition.
  5151. const FunctionDecl *Def = nullptr;
  5152. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  5153. Proto = Def->getType()->getAs<FunctionProtoType>();
  5154. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  5155. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  5156. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  5157. }
  5158. // If the function we're calling isn't a function prototype, but we have
  5159. // a function prototype from a prior declaratiom, use that prototype.
  5160. if (!FDecl->hasPrototype())
  5161. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  5162. }
  5163. // Promote the arguments (C99 6.5.2.2p6).
  5164. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  5165. Expr *Arg = Args[i];
  5166. if (Proto && i < Proto->getNumParams()) {
  5167. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5168. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  5169. ExprResult ArgE =
  5170. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5171. if (ArgE.isInvalid())
  5172. return true;
  5173. Arg = ArgE.getAs<Expr>();
  5174. } else {
  5175. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  5176. if (ArgE.isInvalid())
  5177. return true;
  5178. Arg = ArgE.getAs<Expr>();
  5179. }
  5180. if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
  5181. diag::err_call_incomplete_argument, Arg))
  5182. return ExprError();
  5183. TheCall->setArg(i, Arg);
  5184. }
  5185. }
  5186. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  5187. if (!Method->isStatic())
  5188. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  5189. << Fn->getSourceRange());
  5190. // Check for sentinels
  5191. if (NDecl)
  5192. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  5193. // Do special checking on direct calls to functions.
  5194. if (FDecl) {
  5195. if (CheckFunctionCall(FDecl, TheCall, Proto))
  5196. return ExprError();
  5197. checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
  5198. if (BuiltinID)
  5199. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  5200. } else if (NDecl) {
  5201. if (CheckPointerCall(NDecl, TheCall, Proto))
  5202. return ExprError();
  5203. } else {
  5204. if (CheckOtherCall(TheCall, Proto))
  5205. return ExprError();
  5206. }
  5207. return MaybeBindToTemporary(TheCall);
  5208. }
  5209. ExprResult
  5210. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  5211. SourceLocation RParenLoc, Expr *InitExpr) {
  5212. assert(Ty && "ActOnCompoundLiteral(): missing type");
  5213. assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
  5214. TypeSourceInfo *TInfo;
  5215. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  5216. if (!TInfo)
  5217. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  5218. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  5219. }
  5220. ExprResult
  5221. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  5222. SourceLocation RParenLoc, Expr *LiteralExpr) {
  5223. QualType literalType = TInfo->getType();
  5224. if (literalType->isArrayType()) {
  5225. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  5226. diag::err_illegal_decl_array_incomplete_type,
  5227. SourceRange(LParenLoc,
  5228. LiteralExpr->getSourceRange().getEnd())))
  5229. return ExprError();
  5230. if (literalType->isVariableArrayType())
  5231. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  5232. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  5233. } else if (!literalType->isDependentType() &&
  5234. RequireCompleteType(LParenLoc, literalType,
  5235. diag::err_typecheck_decl_incomplete_type,
  5236. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  5237. return ExprError();
  5238. InitializedEntity Entity
  5239. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  5240. InitializationKind Kind
  5241. = InitializationKind::CreateCStyleCast(LParenLoc,
  5242. SourceRange(LParenLoc, RParenLoc),
  5243. /*InitList=*/true);
  5244. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  5245. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  5246. &literalType);
  5247. if (Result.isInvalid())
  5248. return ExprError();
  5249. LiteralExpr = Result.get();
  5250. bool isFileScope = !CurContext->isFunctionOrMethod();
  5251. // In C, compound literals are l-values for some reason.
  5252. // For GCC compatibility, in C++, file-scope array compound literals with
  5253. // constant initializers are also l-values, and compound literals are
  5254. // otherwise prvalues.
  5255. //
  5256. // (GCC also treats C++ list-initialized file-scope array prvalues with
  5257. // constant initializers as l-values, but that's non-conforming, so we don't
  5258. // follow it there.)
  5259. //
  5260. // FIXME: It would be better to handle the lvalue cases as materializing and
  5261. // lifetime-extending a temporary object, but our materialized temporaries
  5262. // representation only supports lifetime extension from a variable, not "out
  5263. // of thin air".
  5264. // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
  5265. // is bound to the result of applying array-to-pointer decay to the compound
  5266. // literal.
  5267. // FIXME: GCC supports compound literals of reference type, which should
  5268. // obviously have a value kind derived from the kind of reference involved.
  5269. ExprValueKind VK =
  5270. (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
  5271. ? VK_RValue
  5272. : VK_LValue;
  5273. if (isFileScope)
  5274. if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
  5275. for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
  5276. Expr *Init = ILE->getInit(i);
  5277. ILE->setInit(i, ConstantExpr::Create(Context, Init));
  5278. }
  5279. Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  5280. VK, LiteralExpr, isFileScope);
  5281. if (isFileScope) {
  5282. if (!LiteralExpr->isTypeDependent() &&
  5283. !LiteralExpr->isValueDependent() &&
  5284. !literalType->isDependentType()) // C99 6.5.2.5p3
  5285. if (CheckForConstantInitializer(LiteralExpr, literalType))
  5286. return ExprError();
  5287. } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
  5288. literalType.getAddressSpace() != LangAS::Default) {
  5289. // Embedded-C extensions to C99 6.5.2.5:
  5290. // "If the compound literal occurs inside the body of a function, the
  5291. // type name shall not be qualified by an address-space qualifier."
  5292. Diag(LParenLoc, diag::err_compound_literal_with_address_space)
  5293. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
  5294. return ExprError();
  5295. }
  5296. return MaybeBindToTemporary(E);
  5297. }
  5298. ExprResult
  5299. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  5300. SourceLocation RBraceLoc) {
  5301. // Immediately handle non-overload placeholders. Overloads can be
  5302. // resolved contextually, but everything else here can't.
  5303. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  5304. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  5305. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  5306. // Ignore failures; dropping the entire initializer list because
  5307. // of one failure would be terrible for indexing/etc.
  5308. if (result.isInvalid()) continue;
  5309. InitArgList[I] = result.get();
  5310. }
  5311. }
  5312. // Semantic analysis for initializers is done by ActOnDeclarator() and
  5313. // CheckInitializer() - it requires knowledge of the object being initialized.
  5314. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  5315. RBraceLoc);
  5316. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  5317. return E;
  5318. }
  5319. /// Do an explicit extend of the given block pointer if we're in ARC.
  5320. void Sema::maybeExtendBlockObject(ExprResult &E) {
  5321. assert(E.get()->getType()->isBlockPointerType());
  5322. assert(E.get()->isRValue());
  5323. // Only do this in an r-value context.
  5324. if (!getLangOpts().ObjCAutoRefCount) return;
  5325. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  5326. CK_ARCExtendBlockObject, E.get(),
  5327. /*base path*/ nullptr, VK_RValue);
  5328. Cleanup.setExprNeedsCleanups(true);
  5329. }
  5330. /// Prepare a conversion of the given expression to an ObjC object
  5331. /// pointer type.
  5332. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  5333. QualType type = E.get()->getType();
  5334. if (type->isObjCObjectPointerType()) {
  5335. return CK_BitCast;
  5336. } else if (type->isBlockPointerType()) {
  5337. maybeExtendBlockObject(E);
  5338. return CK_BlockPointerToObjCPointerCast;
  5339. } else {
  5340. assert(type->isPointerType());
  5341. return CK_CPointerToObjCPointerCast;
  5342. }
  5343. }
  5344. /// Prepares for a scalar cast, performing all the necessary stages
  5345. /// except the final cast and returning the kind required.
  5346. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  5347. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  5348. // Also, callers should have filtered out the invalid cases with
  5349. // pointers. Everything else should be possible.
  5350. QualType SrcTy = Src.get()->getType();
  5351. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  5352. return CK_NoOp;
  5353. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  5354. case Type::STK_MemberPointer:
  5355. llvm_unreachable("member pointer type in C");
  5356. case Type::STK_CPointer:
  5357. case Type::STK_BlockPointer:
  5358. case Type::STK_ObjCObjectPointer:
  5359. switch (DestTy->getScalarTypeKind()) {
  5360. case Type::STK_CPointer: {
  5361. LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
  5362. LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
  5363. if (SrcAS != DestAS)
  5364. return CK_AddressSpaceConversion;
  5365. if (Context.hasCvrSimilarType(SrcTy, DestTy))
  5366. return CK_NoOp;
  5367. return CK_BitCast;
  5368. }
  5369. case Type::STK_BlockPointer:
  5370. return (SrcKind == Type::STK_BlockPointer
  5371. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  5372. case Type::STK_ObjCObjectPointer:
  5373. if (SrcKind == Type::STK_ObjCObjectPointer)
  5374. return CK_BitCast;
  5375. if (SrcKind == Type::STK_CPointer)
  5376. return CK_CPointerToObjCPointerCast;
  5377. maybeExtendBlockObject(Src);
  5378. return CK_BlockPointerToObjCPointerCast;
  5379. case Type::STK_Bool:
  5380. return CK_PointerToBoolean;
  5381. case Type::STK_Integral:
  5382. return CK_PointerToIntegral;
  5383. case Type::STK_Floating:
  5384. case Type::STK_FloatingComplex:
  5385. case Type::STK_IntegralComplex:
  5386. case Type::STK_MemberPointer:
  5387. case Type::STK_FixedPoint:
  5388. llvm_unreachable("illegal cast from pointer");
  5389. }
  5390. llvm_unreachable("Should have returned before this");
  5391. case Type::STK_FixedPoint:
  5392. switch (DestTy->getScalarTypeKind()) {
  5393. case Type::STK_FixedPoint:
  5394. return CK_FixedPointCast;
  5395. case Type::STK_Bool:
  5396. return CK_FixedPointToBoolean;
  5397. case Type::STK_Integral:
  5398. return CK_FixedPointToIntegral;
  5399. case Type::STK_Floating:
  5400. case Type::STK_IntegralComplex:
  5401. case Type::STK_FloatingComplex:
  5402. Diag(Src.get()->getExprLoc(),
  5403. diag::err_unimplemented_conversion_with_fixed_point_type)
  5404. << DestTy;
  5405. return CK_IntegralCast;
  5406. case Type::STK_CPointer:
  5407. case Type::STK_ObjCObjectPointer:
  5408. case Type::STK_BlockPointer:
  5409. case Type::STK_MemberPointer:
  5410. llvm_unreachable("illegal cast to pointer type");
  5411. }
  5412. llvm_unreachable("Should have returned before this");
  5413. case Type::STK_Bool: // casting from bool is like casting from an integer
  5414. case Type::STK_Integral:
  5415. switch (DestTy->getScalarTypeKind()) {
  5416. case Type::STK_CPointer:
  5417. case Type::STK_ObjCObjectPointer:
  5418. case Type::STK_BlockPointer:
  5419. if (Src.get()->isNullPointerConstant(Context,
  5420. Expr::NPC_ValueDependentIsNull))
  5421. return CK_NullToPointer;
  5422. return CK_IntegralToPointer;
  5423. case Type::STK_Bool:
  5424. return CK_IntegralToBoolean;
  5425. case Type::STK_Integral:
  5426. return CK_IntegralCast;
  5427. case Type::STK_Floating:
  5428. return CK_IntegralToFloating;
  5429. case Type::STK_IntegralComplex:
  5430. Src = ImpCastExprToType(Src.get(),
  5431. DestTy->castAs<ComplexType>()->getElementType(),
  5432. CK_IntegralCast);
  5433. return CK_IntegralRealToComplex;
  5434. case Type::STK_FloatingComplex:
  5435. Src = ImpCastExprToType(Src.get(),
  5436. DestTy->castAs<ComplexType>()->getElementType(),
  5437. CK_IntegralToFloating);
  5438. return CK_FloatingRealToComplex;
  5439. case Type::STK_MemberPointer:
  5440. llvm_unreachable("member pointer type in C");
  5441. case Type::STK_FixedPoint:
  5442. return CK_IntegralToFixedPoint;
  5443. }
  5444. llvm_unreachable("Should have returned before this");
  5445. case Type::STK_Floating:
  5446. switch (DestTy->getScalarTypeKind()) {
  5447. case Type::STK_Floating:
  5448. return CK_FloatingCast;
  5449. case Type::STK_Bool:
  5450. return CK_FloatingToBoolean;
  5451. case Type::STK_Integral:
  5452. return CK_FloatingToIntegral;
  5453. case Type::STK_FloatingComplex:
  5454. Src = ImpCastExprToType(Src.get(),
  5455. DestTy->castAs<ComplexType>()->getElementType(),
  5456. CK_FloatingCast);
  5457. return CK_FloatingRealToComplex;
  5458. case Type::STK_IntegralComplex:
  5459. Src = ImpCastExprToType(Src.get(),
  5460. DestTy->castAs<ComplexType>()->getElementType(),
  5461. CK_FloatingToIntegral);
  5462. return CK_IntegralRealToComplex;
  5463. case Type::STK_CPointer:
  5464. case Type::STK_ObjCObjectPointer:
  5465. case Type::STK_BlockPointer:
  5466. llvm_unreachable("valid float->pointer cast?");
  5467. case Type::STK_MemberPointer:
  5468. llvm_unreachable("member pointer type in C");
  5469. case Type::STK_FixedPoint:
  5470. Diag(Src.get()->getExprLoc(),
  5471. diag::err_unimplemented_conversion_with_fixed_point_type)
  5472. << SrcTy;
  5473. return CK_IntegralCast;
  5474. }
  5475. llvm_unreachable("Should have returned before this");
  5476. case Type::STK_FloatingComplex:
  5477. switch (DestTy->getScalarTypeKind()) {
  5478. case Type::STK_FloatingComplex:
  5479. return CK_FloatingComplexCast;
  5480. case Type::STK_IntegralComplex:
  5481. return CK_FloatingComplexToIntegralComplex;
  5482. case Type::STK_Floating: {
  5483. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5484. if (Context.hasSameType(ET, DestTy))
  5485. return CK_FloatingComplexToReal;
  5486. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  5487. return CK_FloatingCast;
  5488. }
  5489. case Type::STK_Bool:
  5490. return CK_FloatingComplexToBoolean;
  5491. case Type::STK_Integral:
  5492. Src = ImpCastExprToType(Src.get(),
  5493. SrcTy->castAs<ComplexType>()->getElementType(),
  5494. CK_FloatingComplexToReal);
  5495. return CK_FloatingToIntegral;
  5496. case Type::STK_CPointer:
  5497. case Type::STK_ObjCObjectPointer:
  5498. case Type::STK_BlockPointer:
  5499. llvm_unreachable("valid complex float->pointer cast?");
  5500. case Type::STK_MemberPointer:
  5501. llvm_unreachable("member pointer type in C");
  5502. case Type::STK_FixedPoint:
  5503. Diag(Src.get()->getExprLoc(),
  5504. diag::err_unimplemented_conversion_with_fixed_point_type)
  5505. << SrcTy;
  5506. return CK_IntegralCast;
  5507. }
  5508. llvm_unreachable("Should have returned before this");
  5509. case Type::STK_IntegralComplex:
  5510. switch (DestTy->getScalarTypeKind()) {
  5511. case Type::STK_FloatingComplex:
  5512. return CK_IntegralComplexToFloatingComplex;
  5513. case Type::STK_IntegralComplex:
  5514. return CK_IntegralComplexCast;
  5515. case Type::STK_Integral: {
  5516. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5517. if (Context.hasSameType(ET, DestTy))
  5518. return CK_IntegralComplexToReal;
  5519. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  5520. return CK_IntegralCast;
  5521. }
  5522. case Type::STK_Bool:
  5523. return CK_IntegralComplexToBoolean;
  5524. case Type::STK_Floating:
  5525. Src = ImpCastExprToType(Src.get(),
  5526. SrcTy->castAs<ComplexType>()->getElementType(),
  5527. CK_IntegralComplexToReal);
  5528. return CK_IntegralToFloating;
  5529. case Type::STK_CPointer:
  5530. case Type::STK_ObjCObjectPointer:
  5531. case Type::STK_BlockPointer:
  5532. llvm_unreachable("valid complex int->pointer cast?");
  5533. case Type::STK_MemberPointer:
  5534. llvm_unreachable("member pointer type in C");
  5535. case Type::STK_FixedPoint:
  5536. Diag(Src.get()->getExprLoc(),
  5537. diag::err_unimplemented_conversion_with_fixed_point_type)
  5538. << SrcTy;
  5539. return CK_IntegralCast;
  5540. }
  5541. llvm_unreachable("Should have returned before this");
  5542. }
  5543. llvm_unreachable("Unhandled scalar cast");
  5544. }
  5545. static bool breakDownVectorType(QualType type, uint64_t &len,
  5546. QualType &eltType) {
  5547. // Vectors are simple.
  5548. if (const VectorType *vecType = type->getAs<VectorType>()) {
  5549. len = vecType->getNumElements();
  5550. eltType = vecType->getElementType();
  5551. assert(eltType->isScalarType());
  5552. return true;
  5553. }
  5554. // We allow lax conversion to and from non-vector types, but only if
  5555. // they're real types (i.e. non-complex, non-pointer scalar types).
  5556. if (!type->isRealType()) return false;
  5557. len = 1;
  5558. eltType = type;
  5559. return true;
  5560. }
  5561. /// Are the two types lax-compatible vector types? That is, given
  5562. /// that one of them is a vector, do they have equal storage sizes,
  5563. /// where the storage size is the number of elements times the element
  5564. /// size?
  5565. ///
  5566. /// This will also return false if either of the types is neither a
  5567. /// vector nor a real type.
  5568. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
  5569. assert(destTy->isVectorType() || srcTy->isVectorType());
  5570. // Disallow lax conversions between scalars and ExtVectors (these
  5571. // conversions are allowed for other vector types because common headers
  5572. // depend on them). Most scalar OP ExtVector cases are handled by the
  5573. // splat path anyway, which does what we want (convert, not bitcast).
  5574. // What this rules out for ExtVectors is crazy things like char4*float.
  5575. if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
  5576. if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
  5577. uint64_t srcLen, destLen;
  5578. QualType srcEltTy, destEltTy;
  5579. if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
  5580. if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
  5581. // ASTContext::getTypeSize will return the size rounded up to a
  5582. // power of 2, so instead of using that, we need to use the raw
  5583. // element size multiplied by the element count.
  5584. uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
  5585. uint64_t destEltSize = Context.getTypeSize(destEltTy);
  5586. return (srcLen * srcEltSize == destLen * destEltSize);
  5587. }
  5588. /// Is this a legal conversion between two types, one of which is
  5589. /// known to be a vector type?
  5590. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  5591. assert(destTy->isVectorType() || srcTy->isVectorType());
  5592. if (!Context.getLangOpts().LaxVectorConversions)
  5593. return false;
  5594. return areLaxCompatibleVectorTypes(srcTy, destTy);
  5595. }
  5596. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  5597. CastKind &Kind) {
  5598. assert(VectorTy->isVectorType() && "Not a vector type!");
  5599. if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
  5600. if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
  5601. return Diag(R.getBegin(),
  5602. Ty->isVectorType() ?
  5603. diag::err_invalid_conversion_between_vectors :
  5604. diag::err_invalid_conversion_between_vector_and_integer)
  5605. << VectorTy << Ty << R;
  5606. } else
  5607. return Diag(R.getBegin(),
  5608. diag::err_invalid_conversion_between_vector_and_scalar)
  5609. << VectorTy << Ty << R;
  5610. Kind = CK_BitCast;
  5611. return false;
  5612. }
  5613. ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
  5614. QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
  5615. if (DestElemTy == SplattedExpr->getType())
  5616. return SplattedExpr;
  5617. assert(DestElemTy->isFloatingType() ||
  5618. DestElemTy->isIntegralOrEnumerationType());
  5619. CastKind CK;
  5620. if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
  5621. // OpenCL requires that we convert `true` boolean expressions to -1, but
  5622. // only when splatting vectors.
  5623. if (DestElemTy->isFloatingType()) {
  5624. // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
  5625. // in two steps: boolean to signed integral, then to floating.
  5626. ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
  5627. CK_BooleanToSignedIntegral);
  5628. SplattedExpr = CastExprRes.get();
  5629. CK = CK_IntegralToFloating;
  5630. } else {
  5631. CK = CK_BooleanToSignedIntegral;
  5632. }
  5633. } else {
  5634. ExprResult CastExprRes = SplattedExpr;
  5635. CK = PrepareScalarCast(CastExprRes, DestElemTy);
  5636. if (CastExprRes.isInvalid())
  5637. return ExprError();
  5638. SplattedExpr = CastExprRes.get();
  5639. }
  5640. return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
  5641. }
  5642. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  5643. Expr *CastExpr, CastKind &Kind) {
  5644. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  5645. QualType SrcTy = CastExpr->getType();
  5646. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  5647. // an ExtVectorType.
  5648. // In OpenCL, casts between vectors of different types are not allowed.
  5649. // (See OpenCL 6.2).
  5650. if (SrcTy->isVectorType()) {
  5651. if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
  5652. (getLangOpts().OpenCL &&
  5653. !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
  5654. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  5655. << DestTy << SrcTy << R;
  5656. return ExprError();
  5657. }
  5658. Kind = CK_BitCast;
  5659. return CastExpr;
  5660. }
  5661. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  5662. // conversion will take place first from scalar to elt type, and then
  5663. // splat from elt type to vector.
  5664. if (SrcTy->isPointerType())
  5665. return Diag(R.getBegin(),
  5666. diag::err_invalid_conversion_between_vector_and_scalar)
  5667. << DestTy << SrcTy << R;
  5668. Kind = CK_VectorSplat;
  5669. return prepareVectorSplat(DestTy, CastExpr);
  5670. }
  5671. ExprResult
  5672. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  5673. Declarator &D, ParsedType &Ty,
  5674. SourceLocation RParenLoc, Expr *CastExpr) {
  5675. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  5676. "ActOnCastExpr(): missing type or expr");
  5677. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  5678. if (D.isInvalidType())
  5679. return ExprError();
  5680. if (getLangOpts().CPlusPlus) {
  5681. // Check that there are no default arguments (C++ only).
  5682. CheckExtraCXXDefaultArguments(D);
  5683. } else {
  5684. // Make sure any TypoExprs have been dealt with.
  5685. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  5686. if (!Res.isUsable())
  5687. return ExprError();
  5688. CastExpr = Res.get();
  5689. }
  5690. checkUnusedDeclAttributes(D);
  5691. QualType castType = castTInfo->getType();
  5692. Ty = CreateParsedType(castType, castTInfo);
  5693. bool isVectorLiteral = false;
  5694. // Check for an altivec or OpenCL literal,
  5695. // i.e. all the elements are integer constants.
  5696. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  5697. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  5698. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  5699. && castType->isVectorType() && (PE || PLE)) {
  5700. if (PLE && PLE->getNumExprs() == 0) {
  5701. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  5702. return ExprError();
  5703. }
  5704. if (PE || PLE->getNumExprs() == 1) {
  5705. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  5706. if (!E->getType()->isVectorType())
  5707. isVectorLiteral = true;
  5708. }
  5709. else
  5710. isVectorLiteral = true;
  5711. }
  5712. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  5713. // then handle it as such.
  5714. if (isVectorLiteral)
  5715. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  5716. // If the Expr being casted is a ParenListExpr, handle it specially.
  5717. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  5718. // sequence of BinOp comma operators.
  5719. if (isa<ParenListExpr>(CastExpr)) {
  5720. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  5721. if (Result.isInvalid()) return ExprError();
  5722. CastExpr = Result.get();
  5723. }
  5724. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  5725. !getSourceManager().isInSystemMacro(LParenLoc))
  5726. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  5727. CheckTollFreeBridgeCast(castType, CastExpr);
  5728. CheckObjCBridgeRelatedCast(castType, CastExpr);
  5729. DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
  5730. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  5731. }
  5732. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  5733. SourceLocation RParenLoc, Expr *E,
  5734. TypeSourceInfo *TInfo) {
  5735. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  5736. "Expected paren or paren list expression");
  5737. Expr **exprs;
  5738. unsigned numExprs;
  5739. Expr *subExpr;
  5740. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  5741. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  5742. LiteralLParenLoc = PE->getLParenLoc();
  5743. LiteralRParenLoc = PE->getRParenLoc();
  5744. exprs = PE->getExprs();
  5745. numExprs = PE->getNumExprs();
  5746. } else { // isa<ParenExpr> by assertion at function entrance
  5747. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  5748. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  5749. subExpr = cast<ParenExpr>(E)->getSubExpr();
  5750. exprs = &subExpr;
  5751. numExprs = 1;
  5752. }
  5753. QualType Ty = TInfo->getType();
  5754. assert(Ty->isVectorType() && "Expected vector type");
  5755. SmallVector<Expr *, 8> initExprs;
  5756. const VectorType *VTy = Ty->getAs<VectorType>();
  5757. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  5758. // '(...)' form of vector initialization in AltiVec: the number of
  5759. // initializers must be one or must match the size of the vector.
  5760. // If a single value is specified in the initializer then it will be
  5761. // replicated to all the components of the vector
  5762. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  5763. // The number of initializers must be one or must match the size of the
  5764. // vector. If a single value is specified in the initializer then it will
  5765. // be replicated to all the components of the vector
  5766. if (numExprs == 1) {
  5767. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5768. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5769. if (Literal.isInvalid())
  5770. return ExprError();
  5771. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5772. PrepareScalarCast(Literal, ElemTy));
  5773. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5774. }
  5775. else if (numExprs < numElems) {
  5776. Diag(E->getExprLoc(),
  5777. diag::err_incorrect_number_of_vector_initializers);
  5778. return ExprError();
  5779. }
  5780. else
  5781. initExprs.append(exprs, exprs + numExprs);
  5782. }
  5783. else {
  5784. // For OpenCL, when the number of initializers is a single value,
  5785. // it will be replicated to all components of the vector.
  5786. if (getLangOpts().OpenCL &&
  5787. VTy->getVectorKind() == VectorType::GenericVector &&
  5788. numExprs == 1) {
  5789. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5790. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5791. if (Literal.isInvalid())
  5792. return ExprError();
  5793. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5794. PrepareScalarCast(Literal, ElemTy));
  5795. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5796. }
  5797. initExprs.append(exprs, exprs + numExprs);
  5798. }
  5799. // FIXME: This means that pretty-printing the final AST will produce curly
  5800. // braces instead of the original commas.
  5801. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  5802. initExprs, LiteralRParenLoc);
  5803. initE->setType(Ty);
  5804. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  5805. }
  5806. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  5807. /// the ParenListExpr into a sequence of comma binary operators.
  5808. ExprResult
  5809. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  5810. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  5811. if (!E)
  5812. return OrigExpr;
  5813. ExprResult Result(E->getExpr(0));
  5814. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  5815. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  5816. E->getExpr(i));
  5817. if (Result.isInvalid()) return ExprError();
  5818. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  5819. }
  5820. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  5821. SourceLocation R,
  5822. MultiExprArg Val) {
  5823. return ParenListExpr::Create(Context, L, Val, R);
  5824. }
  5825. /// Emit a specialized diagnostic when one expression is a null pointer
  5826. /// constant and the other is not a pointer. Returns true if a diagnostic is
  5827. /// emitted.
  5828. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  5829. SourceLocation QuestionLoc) {
  5830. Expr *NullExpr = LHSExpr;
  5831. Expr *NonPointerExpr = RHSExpr;
  5832. Expr::NullPointerConstantKind NullKind =
  5833. NullExpr->isNullPointerConstant(Context,
  5834. Expr::NPC_ValueDependentIsNotNull);
  5835. if (NullKind == Expr::NPCK_NotNull) {
  5836. NullExpr = RHSExpr;
  5837. NonPointerExpr = LHSExpr;
  5838. NullKind =
  5839. NullExpr->isNullPointerConstant(Context,
  5840. Expr::NPC_ValueDependentIsNotNull);
  5841. }
  5842. if (NullKind == Expr::NPCK_NotNull)
  5843. return false;
  5844. if (NullKind == Expr::NPCK_ZeroExpression)
  5845. return false;
  5846. if (NullKind == Expr::NPCK_ZeroLiteral) {
  5847. // In this case, check to make sure that we got here from a "NULL"
  5848. // string in the source code.
  5849. NullExpr = NullExpr->IgnoreParenImpCasts();
  5850. SourceLocation loc = NullExpr->getExprLoc();
  5851. if (!findMacroSpelling(loc, "NULL"))
  5852. return false;
  5853. }
  5854. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  5855. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  5856. << NonPointerExpr->getType() << DiagType
  5857. << NonPointerExpr->getSourceRange();
  5858. return true;
  5859. }
  5860. /// Return false if the condition expression is valid, true otherwise.
  5861. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  5862. QualType CondTy = Cond->getType();
  5863. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  5864. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  5865. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5866. << CondTy << Cond->getSourceRange();
  5867. return true;
  5868. }
  5869. // C99 6.5.15p2
  5870. if (CondTy->isScalarType()) return false;
  5871. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  5872. << CondTy << Cond->getSourceRange();
  5873. return true;
  5874. }
  5875. /// Handle when one or both operands are void type.
  5876. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  5877. ExprResult &RHS) {
  5878. Expr *LHSExpr = LHS.get();
  5879. Expr *RHSExpr = RHS.get();
  5880. if (!LHSExpr->getType()->isVoidType())
  5881. S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  5882. << RHSExpr->getSourceRange();
  5883. if (!RHSExpr->getType()->isVoidType())
  5884. S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  5885. << LHSExpr->getSourceRange();
  5886. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  5887. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  5888. return S.Context.VoidTy;
  5889. }
  5890. /// Return false if the NullExpr can be promoted to PointerTy,
  5891. /// true otherwise.
  5892. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  5893. QualType PointerTy) {
  5894. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  5895. !NullExpr.get()->isNullPointerConstant(S.Context,
  5896. Expr::NPC_ValueDependentIsNull))
  5897. return true;
  5898. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  5899. return false;
  5900. }
  5901. /// Checks compatibility between two pointers and return the resulting
  5902. /// type.
  5903. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  5904. ExprResult &RHS,
  5905. SourceLocation Loc) {
  5906. QualType LHSTy = LHS.get()->getType();
  5907. QualType RHSTy = RHS.get()->getType();
  5908. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  5909. // Two identical pointers types are always compatible.
  5910. return LHSTy;
  5911. }
  5912. QualType lhptee, rhptee;
  5913. // Get the pointee types.
  5914. bool IsBlockPointer = false;
  5915. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  5916. lhptee = LHSBTy->getPointeeType();
  5917. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  5918. IsBlockPointer = true;
  5919. } else {
  5920. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  5921. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  5922. }
  5923. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  5924. // differently qualified versions of compatible types, the result type is
  5925. // a pointer to an appropriately qualified version of the composite
  5926. // type.
  5927. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  5928. // clause doesn't make sense for our extensions. E.g. address space 2 should
  5929. // be incompatible with address space 3: they may live on different devices or
  5930. // anything.
  5931. Qualifiers lhQual = lhptee.getQualifiers();
  5932. Qualifiers rhQual = rhptee.getQualifiers();
  5933. LangAS ResultAddrSpace = LangAS::Default;
  5934. LangAS LAddrSpace = lhQual.getAddressSpace();
  5935. LangAS RAddrSpace = rhQual.getAddressSpace();
  5936. // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
  5937. // spaces is disallowed.
  5938. if (lhQual.isAddressSpaceSupersetOf(rhQual))
  5939. ResultAddrSpace = LAddrSpace;
  5940. else if (rhQual.isAddressSpaceSupersetOf(lhQual))
  5941. ResultAddrSpace = RAddrSpace;
  5942. else {
  5943. S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  5944. << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
  5945. << RHS.get()->getSourceRange();
  5946. return QualType();
  5947. }
  5948. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  5949. auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
  5950. lhQual.removeCVRQualifiers();
  5951. rhQual.removeCVRQualifiers();
  5952. // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
  5953. // (C99 6.7.3) for address spaces. We assume that the check should behave in
  5954. // the same manner as it's defined for CVR qualifiers, so for OpenCL two
  5955. // qual types are compatible iff
  5956. // * corresponded types are compatible
  5957. // * CVR qualifiers are equal
  5958. // * address spaces are equal
  5959. // Thus for conditional operator we merge CVR and address space unqualified
  5960. // pointees and if there is a composite type we return a pointer to it with
  5961. // merged qualifiers.
  5962. LHSCastKind =
  5963. LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  5964. RHSCastKind =
  5965. RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  5966. lhQual.removeAddressSpace();
  5967. rhQual.removeAddressSpace();
  5968. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  5969. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  5970. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  5971. if (CompositeTy.isNull()) {
  5972. // In this situation, we assume void* type. No especially good
  5973. // reason, but this is what gcc does, and we do have to pick
  5974. // to get a consistent AST.
  5975. QualType incompatTy;
  5976. incompatTy = S.Context.getPointerType(
  5977. S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
  5978. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
  5979. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
  5980. // FIXME: For OpenCL the warning emission and cast to void* leaves a room
  5981. // for casts between types with incompatible address space qualifiers.
  5982. // For the following code the compiler produces casts between global and
  5983. // local address spaces of the corresponded innermost pointees:
  5984. // local int *global *a;
  5985. // global int *global *b;
  5986. // a = (0 ? a : b); // see C99 6.5.16.1.p1.
  5987. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  5988. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5989. << RHS.get()->getSourceRange();
  5990. return incompatTy;
  5991. }
  5992. // The pointer types are compatible.
  5993. // In case of OpenCL ResultTy should have the address space qualifier
  5994. // which is a superset of address spaces of both the 2nd and the 3rd
  5995. // operands of the conditional operator.
  5996. QualType ResultTy = [&, ResultAddrSpace]() {
  5997. if (S.getLangOpts().OpenCL) {
  5998. Qualifiers CompositeQuals = CompositeTy.getQualifiers();
  5999. CompositeQuals.setAddressSpace(ResultAddrSpace);
  6000. return S.Context
  6001. .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
  6002. .withCVRQualifiers(MergedCVRQual);
  6003. }
  6004. return CompositeTy.withCVRQualifiers(MergedCVRQual);
  6005. }();
  6006. if (IsBlockPointer)
  6007. ResultTy = S.Context.getBlockPointerType(ResultTy);
  6008. else
  6009. ResultTy = S.Context.getPointerType(ResultTy);
  6010. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
  6011. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
  6012. return ResultTy;
  6013. }
  6014. /// Return the resulting type when the operands are both block pointers.
  6015. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  6016. ExprResult &LHS,
  6017. ExprResult &RHS,
  6018. SourceLocation Loc) {
  6019. QualType LHSTy = LHS.get()->getType();
  6020. QualType RHSTy = RHS.get()->getType();
  6021. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  6022. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  6023. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  6024. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6025. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6026. return destType;
  6027. }
  6028. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  6029. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6030. << RHS.get()->getSourceRange();
  6031. return QualType();
  6032. }
  6033. // We have 2 block pointer types.
  6034. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  6035. }
  6036. /// Return the resulting type when the operands are both pointers.
  6037. static QualType
  6038. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  6039. ExprResult &RHS,
  6040. SourceLocation Loc) {
  6041. // get the pointer types
  6042. QualType LHSTy = LHS.get()->getType();
  6043. QualType RHSTy = RHS.get()->getType();
  6044. // get the "pointed to" types
  6045. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  6046. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  6047. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  6048. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  6049. // Figure out necessary qualifiers (C99 6.5.15p6)
  6050. QualType destPointee
  6051. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  6052. QualType destType = S.Context.getPointerType(destPointee);
  6053. // Add qualifiers if necessary.
  6054. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  6055. // Promote to void*.
  6056. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6057. return destType;
  6058. }
  6059. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  6060. QualType destPointee
  6061. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  6062. QualType destType = S.Context.getPointerType(destPointee);
  6063. // Add qualifiers if necessary.
  6064. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  6065. // Promote to void*.
  6066. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6067. return destType;
  6068. }
  6069. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  6070. }
  6071. /// Return false if the first expression is not an integer and the second
  6072. /// expression is not a pointer, true otherwise.
  6073. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  6074. Expr* PointerExpr, SourceLocation Loc,
  6075. bool IsIntFirstExpr) {
  6076. if (!PointerExpr->getType()->isPointerType() ||
  6077. !Int.get()->getType()->isIntegerType())
  6078. return false;
  6079. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  6080. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  6081. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  6082. << Expr1->getType() << Expr2->getType()
  6083. << Expr1->getSourceRange() << Expr2->getSourceRange();
  6084. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  6085. CK_IntegralToPointer);
  6086. return true;
  6087. }
  6088. /// Simple conversion between integer and floating point types.
  6089. ///
  6090. /// Used when handling the OpenCL conditional operator where the
  6091. /// condition is a vector while the other operands are scalar.
  6092. ///
  6093. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  6094. /// types are either integer or floating type. Between the two
  6095. /// operands, the type with the higher rank is defined as the "result
  6096. /// type". The other operand needs to be promoted to the same type. No
  6097. /// other type promotion is allowed. We cannot use
  6098. /// UsualArithmeticConversions() for this purpose, since it always
  6099. /// promotes promotable types.
  6100. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  6101. ExprResult &RHS,
  6102. SourceLocation QuestionLoc) {
  6103. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  6104. if (LHS.isInvalid())
  6105. return QualType();
  6106. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  6107. if (RHS.isInvalid())
  6108. return QualType();
  6109. // For conversion purposes, we ignore any qualifiers.
  6110. // For example, "const float" and "float" are equivalent.
  6111. QualType LHSType =
  6112. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  6113. QualType RHSType =
  6114. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  6115. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  6116. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  6117. << LHSType << LHS.get()->getSourceRange();
  6118. return QualType();
  6119. }
  6120. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  6121. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  6122. << RHSType << RHS.get()->getSourceRange();
  6123. return QualType();
  6124. }
  6125. // If both types are identical, no conversion is needed.
  6126. if (LHSType == RHSType)
  6127. return LHSType;
  6128. // Now handle "real" floating types (i.e. float, double, long double).
  6129. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  6130. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  6131. /*IsCompAssign = */ false);
  6132. // Finally, we have two differing integer types.
  6133. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  6134. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  6135. }
  6136. /// Convert scalar operands to a vector that matches the
  6137. /// condition in length.
  6138. ///
  6139. /// Used when handling the OpenCL conditional operator where the
  6140. /// condition is a vector while the other operands are scalar.
  6141. ///
  6142. /// We first compute the "result type" for the scalar operands
  6143. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  6144. /// into a vector of that type where the length matches the condition
  6145. /// vector type. s6.11.6 requires that the element types of the result
  6146. /// and the condition must have the same number of bits.
  6147. static QualType
  6148. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  6149. QualType CondTy, SourceLocation QuestionLoc) {
  6150. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  6151. if (ResTy.isNull()) return QualType();
  6152. const VectorType *CV = CondTy->getAs<VectorType>();
  6153. assert(CV);
  6154. // Determine the vector result type
  6155. unsigned NumElements = CV->getNumElements();
  6156. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  6157. // Ensure that all types have the same number of bits
  6158. if (S.Context.getTypeSize(CV->getElementType())
  6159. != S.Context.getTypeSize(ResTy)) {
  6160. // Since VectorTy is created internally, it does not pretty print
  6161. // with an OpenCL name. Instead, we just print a description.
  6162. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  6163. SmallString<64> Str;
  6164. llvm::raw_svector_ostream OS(Str);
  6165. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  6166. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  6167. << CondTy << OS.str();
  6168. return QualType();
  6169. }
  6170. // Convert operands to the vector result type
  6171. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  6172. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  6173. return VectorTy;
  6174. }
  6175. /// Return false if this is a valid OpenCL condition vector
  6176. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  6177. SourceLocation QuestionLoc) {
  6178. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  6179. // integral type.
  6180. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  6181. assert(CondTy);
  6182. QualType EleTy = CondTy->getElementType();
  6183. if (EleTy->isIntegerType()) return false;
  6184. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  6185. << Cond->getType() << Cond->getSourceRange();
  6186. return true;
  6187. }
  6188. /// Return false if the vector condition type and the vector
  6189. /// result type are compatible.
  6190. ///
  6191. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  6192. /// number of elements, and their element types have the same number
  6193. /// of bits.
  6194. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  6195. SourceLocation QuestionLoc) {
  6196. const VectorType *CV = CondTy->getAs<VectorType>();
  6197. const VectorType *RV = VecResTy->getAs<VectorType>();
  6198. assert(CV && RV);
  6199. if (CV->getNumElements() != RV->getNumElements()) {
  6200. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  6201. << CondTy << VecResTy;
  6202. return true;
  6203. }
  6204. QualType CVE = CV->getElementType();
  6205. QualType RVE = RV->getElementType();
  6206. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  6207. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  6208. << CondTy << VecResTy;
  6209. return true;
  6210. }
  6211. return false;
  6212. }
  6213. /// Return the resulting type for the conditional operator in
  6214. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  6215. /// s6.3.i) when the condition is a vector type.
  6216. static QualType
  6217. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  6218. ExprResult &LHS, ExprResult &RHS,
  6219. SourceLocation QuestionLoc) {
  6220. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  6221. if (Cond.isInvalid())
  6222. return QualType();
  6223. QualType CondTy = Cond.get()->getType();
  6224. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  6225. return QualType();
  6226. // If either operand is a vector then find the vector type of the
  6227. // result as specified in OpenCL v1.1 s6.3.i.
  6228. if (LHS.get()->getType()->isVectorType() ||
  6229. RHS.get()->getType()->isVectorType()) {
  6230. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  6231. /*isCompAssign*/false,
  6232. /*AllowBothBool*/true,
  6233. /*AllowBoolConversions*/false);
  6234. if (VecResTy.isNull()) return QualType();
  6235. // The result type must match the condition type as specified in
  6236. // OpenCL v1.1 s6.11.6.
  6237. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  6238. return QualType();
  6239. return VecResTy;
  6240. }
  6241. // Both operands are scalar.
  6242. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  6243. }
  6244. /// Return true if the Expr is block type
  6245. static bool checkBlockType(Sema &S, const Expr *E) {
  6246. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  6247. QualType Ty = CE->getCallee()->getType();
  6248. if (Ty->isBlockPointerType()) {
  6249. S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
  6250. return true;
  6251. }
  6252. }
  6253. return false;
  6254. }
  6255. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  6256. /// In that case, LHS = cond.
  6257. /// C99 6.5.15
  6258. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  6259. ExprResult &RHS, ExprValueKind &VK,
  6260. ExprObjectKind &OK,
  6261. SourceLocation QuestionLoc) {
  6262. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  6263. if (!LHSResult.isUsable()) return QualType();
  6264. LHS = LHSResult;
  6265. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  6266. if (!RHSResult.isUsable()) return QualType();
  6267. RHS = RHSResult;
  6268. // C++ is sufficiently different to merit its own checker.
  6269. if (getLangOpts().CPlusPlus)
  6270. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  6271. VK = VK_RValue;
  6272. OK = OK_Ordinary;
  6273. // The OpenCL operator with a vector condition is sufficiently
  6274. // different to merit its own checker.
  6275. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  6276. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  6277. // First, check the condition.
  6278. Cond = UsualUnaryConversions(Cond.get());
  6279. if (Cond.isInvalid())
  6280. return QualType();
  6281. if (checkCondition(*this, Cond.get(), QuestionLoc))
  6282. return QualType();
  6283. // Now check the two expressions.
  6284. if (LHS.get()->getType()->isVectorType() ||
  6285. RHS.get()->getType()->isVectorType())
  6286. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  6287. /*AllowBothBool*/true,
  6288. /*AllowBoolConversions*/false);
  6289. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  6290. if (LHS.isInvalid() || RHS.isInvalid())
  6291. return QualType();
  6292. QualType LHSTy = LHS.get()->getType();
  6293. QualType RHSTy = RHS.get()->getType();
  6294. // Diagnose attempts to convert between __float128 and long double where
  6295. // such conversions currently can't be handled.
  6296. if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
  6297. Diag(QuestionLoc,
  6298. diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
  6299. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6300. return QualType();
  6301. }
  6302. // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
  6303. // selection operator (?:).
  6304. if (getLangOpts().OpenCL &&
  6305. (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
  6306. return QualType();
  6307. }
  6308. // If both operands have arithmetic type, do the usual arithmetic conversions
  6309. // to find a common type: C99 6.5.15p3,5.
  6310. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  6311. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  6312. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  6313. return ResTy;
  6314. }
  6315. // If both operands are the same structure or union type, the result is that
  6316. // type.
  6317. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  6318. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  6319. if (LHSRT->getDecl() == RHSRT->getDecl())
  6320. // "If both the operands have structure or union type, the result has
  6321. // that type." This implies that CV qualifiers are dropped.
  6322. return LHSTy.getUnqualifiedType();
  6323. // FIXME: Type of conditional expression must be complete in C mode.
  6324. }
  6325. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  6326. // The following || allows only one side to be void (a GCC-ism).
  6327. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  6328. return checkConditionalVoidType(*this, LHS, RHS);
  6329. }
  6330. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  6331. // the type of the other operand."
  6332. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  6333. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  6334. // All objective-c pointer type analysis is done here.
  6335. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  6336. QuestionLoc);
  6337. if (LHS.isInvalid() || RHS.isInvalid())
  6338. return QualType();
  6339. if (!compositeType.isNull())
  6340. return compositeType;
  6341. // Handle block pointer types.
  6342. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  6343. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  6344. QuestionLoc);
  6345. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  6346. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  6347. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  6348. QuestionLoc);
  6349. // GCC compatibility: soften pointer/integer mismatch. Note that
  6350. // null pointers have been filtered out by this point.
  6351. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  6352. /*isIntFirstExpr=*/true))
  6353. return RHSTy;
  6354. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  6355. /*isIntFirstExpr=*/false))
  6356. return LHSTy;
  6357. // Emit a better diagnostic if one of the expressions is a null pointer
  6358. // constant and the other is not a pointer type. In this case, the user most
  6359. // likely forgot to take the address of the other expression.
  6360. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  6361. return QualType();
  6362. // Otherwise, the operands are not compatible.
  6363. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  6364. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6365. << RHS.get()->getSourceRange();
  6366. return QualType();
  6367. }
  6368. /// FindCompositeObjCPointerType - Helper method to find composite type of
  6369. /// two objective-c pointer types of the two input expressions.
  6370. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  6371. SourceLocation QuestionLoc) {
  6372. QualType LHSTy = LHS.get()->getType();
  6373. QualType RHSTy = RHS.get()->getType();
  6374. // Handle things like Class and struct objc_class*. Here we case the result
  6375. // to the pseudo-builtin, because that will be implicitly cast back to the
  6376. // redefinition type if an attempt is made to access its fields.
  6377. if (LHSTy->isObjCClassType() &&
  6378. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  6379. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6380. return LHSTy;
  6381. }
  6382. if (RHSTy->isObjCClassType() &&
  6383. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  6384. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6385. return RHSTy;
  6386. }
  6387. // And the same for struct objc_object* / id
  6388. if (LHSTy->isObjCIdType() &&
  6389. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  6390. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6391. return LHSTy;
  6392. }
  6393. if (RHSTy->isObjCIdType() &&
  6394. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  6395. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6396. return RHSTy;
  6397. }
  6398. // And the same for struct objc_selector* / SEL
  6399. if (Context.isObjCSelType(LHSTy) &&
  6400. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  6401. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  6402. return LHSTy;
  6403. }
  6404. if (Context.isObjCSelType(RHSTy) &&
  6405. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  6406. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  6407. return RHSTy;
  6408. }
  6409. // Check constraints for Objective-C object pointers types.
  6410. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  6411. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  6412. // Two identical object pointer types are always compatible.
  6413. return LHSTy;
  6414. }
  6415. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  6416. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  6417. QualType compositeType = LHSTy;
  6418. // If both operands are interfaces and either operand can be
  6419. // assigned to the other, use that type as the composite
  6420. // type. This allows
  6421. // xxx ? (A*) a : (B*) b
  6422. // where B is a subclass of A.
  6423. //
  6424. // Additionally, as for assignment, if either type is 'id'
  6425. // allow silent coercion. Finally, if the types are
  6426. // incompatible then make sure to use 'id' as the composite
  6427. // type so the result is acceptable for sending messages to.
  6428. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  6429. // It could return the composite type.
  6430. if (!(compositeType =
  6431. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  6432. // Nothing more to do.
  6433. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  6434. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  6435. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  6436. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  6437. } else if ((LHSTy->isObjCQualifiedIdType() ||
  6438. RHSTy->isObjCQualifiedIdType()) &&
  6439. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  6440. // Need to handle "id<xx>" explicitly.
  6441. // GCC allows qualified id and any Objective-C type to devolve to
  6442. // id. Currently localizing to here until clear this should be
  6443. // part of ObjCQualifiedIdTypesAreCompatible.
  6444. compositeType = Context.getObjCIdType();
  6445. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  6446. compositeType = Context.getObjCIdType();
  6447. } else {
  6448. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  6449. << LHSTy << RHSTy
  6450. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6451. QualType incompatTy = Context.getObjCIdType();
  6452. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  6453. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  6454. return incompatTy;
  6455. }
  6456. // The object pointer types are compatible.
  6457. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  6458. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  6459. return compositeType;
  6460. }
  6461. // Check Objective-C object pointer types and 'void *'
  6462. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  6463. if (getLangOpts().ObjCAutoRefCount) {
  6464. // ARC forbids the implicit conversion of object pointers to 'void *',
  6465. // so these types are not compatible.
  6466. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6467. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6468. LHS = RHS = true;
  6469. return QualType();
  6470. }
  6471. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  6472. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6473. QualType destPointee
  6474. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  6475. QualType destType = Context.getPointerType(destPointee);
  6476. // Add qualifiers if necessary.
  6477. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  6478. // Promote to void*.
  6479. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6480. return destType;
  6481. }
  6482. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  6483. if (getLangOpts().ObjCAutoRefCount) {
  6484. // ARC forbids the implicit conversion of object pointers to 'void *',
  6485. // so these types are not compatible.
  6486. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6487. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6488. LHS = RHS = true;
  6489. return QualType();
  6490. }
  6491. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6492. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  6493. QualType destPointee
  6494. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  6495. QualType destType = Context.getPointerType(destPointee);
  6496. // Add qualifiers if necessary.
  6497. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  6498. // Promote to void*.
  6499. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6500. return destType;
  6501. }
  6502. return QualType();
  6503. }
  6504. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  6505. /// ParenRange in parentheses.
  6506. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  6507. const PartialDiagnostic &Note,
  6508. SourceRange ParenRange) {
  6509. SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
  6510. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  6511. EndLoc.isValid()) {
  6512. Self.Diag(Loc, Note)
  6513. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  6514. << FixItHint::CreateInsertion(EndLoc, ")");
  6515. } else {
  6516. // We can't display the parentheses, so just show the bare note.
  6517. Self.Diag(Loc, Note) << ParenRange;
  6518. }
  6519. }
  6520. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  6521. return BinaryOperator::isAdditiveOp(Opc) ||
  6522. BinaryOperator::isMultiplicativeOp(Opc) ||
  6523. BinaryOperator::isShiftOp(Opc);
  6524. }
  6525. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  6526. /// expression, either using a built-in or overloaded operator,
  6527. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  6528. /// expression.
  6529. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  6530. Expr **RHSExprs) {
  6531. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  6532. E = E->IgnoreImpCasts();
  6533. E = E->IgnoreConversionOperator();
  6534. E = E->IgnoreImpCasts();
  6535. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
  6536. E = MTE->GetTemporaryExpr();
  6537. E = E->IgnoreImpCasts();
  6538. }
  6539. // Built-in binary operator.
  6540. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  6541. if (IsArithmeticOp(OP->getOpcode())) {
  6542. *Opcode = OP->getOpcode();
  6543. *RHSExprs = OP->getRHS();
  6544. return true;
  6545. }
  6546. }
  6547. // Overloaded operator.
  6548. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  6549. if (Call->getNumArgs() != 2)
  6550. return false;
  6551. // Make sure this is really a binary operator that is safe to pass into
  6552. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  6553. OverloadedOperatorKind OO = Call->getOperator();
  6554. if (OO < OO_Plus || OO > OO_Arrow ||
  6555. OO == OO_PlusPlus || OO == OO_MinusMinus)
  6556. return false;
  6557. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  6558. if (IsArithmeticOp(OpKind)) {
  6559. *Opcode = OpKind;
  6560. *RHSExprs = Call->getArg(1);
  6561. return true;
  6562. }
  6563. }
  6564. return false;
  6565. }
  6566. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  6567. /// or is a logical expression such as (x==y) which has int type, but is
  6568. /// commonly interpreted as boolean.
  6569. static bool ExprLooksBoolean(Expr *E) {
  6570. E = E->IgnoreParenImpCasts();
  6571. if (E->getType()->isBooleanType())
  6572. return true;
  6573. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  6574. return OP->isComparisonOp() || OP->isLogicalOp();
  6575. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  6576. return OP->getOpcode() == UO_LNot;
  6577. if (E->getType()->isPointerType())
  6578. return true;
  6579. // FIXME: What about overloaded operator calls returning "unspecified boolean
  6580. // type"s (commonly pointer-to-members)?
  6581. return false;
  6582. }
  6583. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  6584. /// and binary operator are mixed in a way that suggests the programmer assumed
  6585. /// the conditional operator has higher precedence, for example:
  6586. /// "int x = a + someBinaryCondition ? 1 : 2".
  6587. static void DiagnoseConditionalPrecedence(Sema &Self,
  6588. SourceLocation OpLoc,
  6589. Expr *Condition,
  6590. Expr *LHSExpr,
  6591. Expr *RHSExpr) {
  6592. BinaryOperatorKind CondOpcode;
  6593. Expr *CondRHS;
  6594. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  6595. return;
  6596. if (!ExprLooksBoolean(CondRHS))
  6597. return;
  6598. // The condition is an arithmetic binary expression, with a right-
  6599. // hand side that looks boolean, so warn.
  6600. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  6601. << Condition->getSourceRange()
  6602. << BinaryOperator::getOpcodeStr(CondOpcode);
  6603. SuggestParentheses(
  6604. Self, OpLoc,
  6605. Self.PDiag(diag::note_precedence_silence)
  6606. << BinaryOperator::getOpcodeStr(CondOpcode),
  6607. SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
  6608. SuggestParentheses(Self, OpLoc,
  6609. Self.PDiag(diag::note_precedence_conditional_first),
  6610. SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
  6611. }
  6612. /// Compute the nullability of a conditional expression.
  6613. static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
  6614. QualType LHSTy, QualType RHSTy,
  6615. ASTContext &Ctx) {
  6616. if (!ResTy->isAnyPointerType())
  6617. return ResTy;
  6618. auto GetNullability = [&Ctx](QualType Ty) {
  6619. Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
  6620. if (Kind)
  6621. return *Kind;
  6622. return NullabilityKind::Unspecified;
  6623. };
  6624. auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
  6625. NullabilityKind MergedKind;
  6626. // Compute nullability of a binary conditional expression.
  6627. if (IsBin) {
  6628. if (LHSKind == NullabilityKind::NonNull)
  6629. MergedKind = NullabilityKind::NonNull;
  6630. else
  6631. MergedKind = RHSKind;
  6632. // Compute nullability of a normal conditional expression.
  6633. } else {
  6634. if (LHSKind == NullabilityKind::Nullable ||
  6635. RHSKind == NullabilityKind::Nullable)
  6636. MergedKind = NullabilityKind::Nullable;
  6637. else if (LHSKind == NullabilityKind::NonNull)
  6638. MergedKind = RHSKind;
  6639. else if (RHSKind == NullabilityKind::NonNull)
  6640. MergedKind = LHSKind;
  6641. else
  6642. MergedKind = NullabilityKind::Unspecified;
  6643. }
  6644. // Return if ResTy already has the correct nullability.
  6645. if (GetNullability(ResTy) == MergedKind)
  6646. return ResTy;
  6647. // Strip all nullability from ResTy.
  6648. while (ResTy->getNullability(Ctx))
  6649. ResTy = ResTy.getSingleStepDesugaredType(Ctx);
  6650. // Create a new AttributedType with the new nullability kind.
  6651. auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
  6652. return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
  6653. }
  6654. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  6655. /// in the case of a the GNU conditional expr extension.
  6656. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  6657. SourceLocation ColonLoc,
  6658. Expr *CondExpr, Expr *LHSExpr,
  6659. Expr *RHSExpr) {
  6660. if (!getLangOpts().CPlusPlus) {
  6661. // C cannot handle TypoExpr nodes in the condition because it
  6662. // doesn't handle dependent types properly, so make sure any TypoExprs have
  6663. // been dealt with before checking the operands.
  6664. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  6665. ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
  6666. ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
  6667. if (!CondResult.isUsable())
  6668. return ExprError();
  6669. if (LHSExpr) {
  6670. if (!LHSResult.isUsable())
  6671. return ExprError();
  6672. }
  6673. if (!RHSResult.isUsable())
  6674. return ExprError();
  6675. CondExpr = CondResult.get();
  6676. LHSExpr = LHSResult.get();
  6677. RHSExpr = RHSResult.get();
  6678. }
  6679. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  6680. // was the condition.
  6681. OpaqueValueExpr *opaqueValue = nullptr;
  6682. Expr *commonExpr = nullptr;
  6683. if (!LHSExpr) {
  6684. commonExpr = CondExpr;
  6685. // Lower out placeholder types first. This is important so that we don't
  6686. // try to capture a placeholder. This happens in few cases in C++; such
  6687. // as Objective-C++'s dictionary subscripting syntax.
  6688. if (commonExpr->hasPlaceholderType()) {
  6689. ExprResult result = CheckPlaceholderExpr(commonExpr);
  6690. if (!result.isUsable()) return ExprError();
  6691. commonExpr = result.get();
  6692. }
  6693. // We usually want to apply unary conversions *before* saving, except
  6694. // in the special case of a C++ l-value conditional.
  6695. if (!(getLangOpts().CPlusPlus
  6696. && !commonExpr->isTypeDependent()
  6697. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  6698. && commonExpr->isGLValue()
  6699. && commonExpr->isOrdinaryOrBitFieldObject()
  6700. && RHSExpr->isOrdinaryOrBitFieldObject()
  6701. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  6702. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  6703. if (commonRes.isInvalid())
  6704. return ExprError();
  6705. commonExpr = commonRes.get();
  6706. }
  6707. // If the common expression is a class or array prvalue, materialize it
  6708. // so that we can safely refer to it multiple times.
  6709. if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
  6710. commonExpr->getType()->isArrayType())) {
  6711. ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
  6712. if (MatExpr.isInvalid())
  6713. return ExprError();
  6714. commonExpr = MatExpr.get();
  6715. }
  6716. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  6717. commonExpr->getType(),
  6718. commonExpr->getValueKind(),
  6719. commonExpr->getObjectKind(),
  6720. commonExpr);
  6721. LHSExpr = CondExpr = opaqueValue;
  6722. }
  6723. QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
  6724. ExprValueKind VK = VK_RValue;
  6725. ExprObjectKind OK = OK_Ordinary;
  6726. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  6727. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  6728. VK, OK, QuestionLoc);
  6729. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  6730. RHS.isInvalid())
  6731. return ExprError();
  6732. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  6733. RHS.get());
  6734. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  6735. result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
  6736. Context);
  6737. if (!commonExpr)
  6738. return new (Context)
  6739. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  6740. RHS.get(), result, VK, OK);
  6741. return new (Context) BinaryConditionalOperator(
  6742. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  6743. ColonLoc, result, VK, OK);
  6744. }
  6745. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  6746. // being closely modeled after the C99 spec:-). The odd characteristic of this
  6747. // routine is it effectively iqnores the qualifiers on the top level pointee.
  6748. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  6749. // FIXME: add a couple examples in this comment.
  6750. static Sema::AssignConvertType
  6751. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  6752. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6753. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6754. // get the "pointed to" type (ignoring qualifiers at the top level)
  6755. const Type *lhptee, *rhptee;
  6756. Qualifiers lhq, rhq;
  6757. std::tie(lhptee, lhq) =
  6758. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  6759. std::tie(rhptee, rhq) =
  6760. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  6761. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6762. // C99 6.5.16.1p1: This following citation is common to constraints
  6763. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  6764. // qualifiers of the type *pointed to* by the right;
  6765. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  6766. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  6767. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  6768. // Ignore lifetime for further calculation.
  6769. lhq.removeObjCLifetime();
  6770. rhq.removeObjCLifetime();
  6771. }
  6772. if (!lhq.compatiblyIncludes(rhq)) {
  6773. // Treat address-space mismatches as fatal.
  6774. if (!lhq.isAddressSpaceSupersetOf(rhq))
  6775. return Sema::IncompatiblePointerDiscardsQualifiers;
  6776. // It's okay to add or remove GC or lifetime qualifiers when converting to
  6777. // and from void*.
  6778. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  6779. .compatiblyIncludes(
  6780. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  6781. && (lhptee->isVoidType() || rhptee->isVoidType()))
  6782. ; // keep old
  6783. // Treat lifetime mismatches as fatal.
  6784. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  6785. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  6786. // For GCC/MS compatibility, other qualifier mismatches are treated
  6787. // as still compatible in C.
  6788. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6789. }
  6790. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  6791. // incomplete type and the other is a pointer to a qualified or unqualified
  6792. // version of void...
  6793. if (lhptee->isVoidType()) {
  6794. if (rhptee->isIncompleteOrObjectType())
  6795. return ConvTy;
  6796. // As an extension, we allow cast to/from void* to function pointer.
  6797. assert(rhptee->isFunctionType());
  6798. return Sema::FunctionVoidPointer;
  6799. }
  6800. if (rhptee->isVoidType()) {
  6801. if (lhptee->isIncompleteOrObjectType())
  6802. return ConvTy;
  6803. // As an extension, we allow cast to/from void* to function pointer.
  6804. assert(lhptee->isFunctionType());
  6805. return Sema::FunctionVoidPointer;
  6806. }
  6807. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  6808. // unqualified versions of compatible types, ...
  6809. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  6810. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  6811. // Check if the pointee types are compatible ignoring the sign.
  6812. // We explicitly check for char so that we catch "char" vs
  6813. // "unsigned char" on systems where "char" is unsigned.
  6814. if (lhptee->isCharType())
  6815. ltrans = S.Context.UnsignedCharTy;
  6816. else if (lhptee->hasSignedIntegerRepresentation())
  6817. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  6818. if (rhptee->isCharType())
  6819. rtrans = S.Context.UnsignedCharTy;
  6820. else if (rhptee->hasSignedIntegerRepresentation())
  6821. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  6822. if (ltrans == rtrans) {
  6823. // Types are compatible ignoring the sign. Qualifier incompatibility
  6824. // takes priority over sign incompatibility because the sign
  6825. // warning can be disabled.
  6826. if (ConvTy != Sema::Compatible)
  6827. return ConvTy;
  6828. return Sema::IncompatiblePointerSign;
  6829. }
  6830. // If we are a multi-level pointer, it's possible that our issue is simply
  6831. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  6832. // the eventual target type is the same and the pointers have the same
  6833. // level of indirection, this must be the issue.
  6834. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  6835. do {
  6836. std::tie(lhptee, lhq) =
  6837. cast<PointerType>(lhptee)->getPointeeType().split().asPair();
  6838. std::tie(rhptee, rhq) =
  6839. cast<PointerType>(rhptee)->getPointeeType().split().asPair();
  6840. // Inconsistent address spaces at this point is invalid, even if the
  6841. // address spaces would be compatible.
  6842. // FIXME: This doesn't catch address space mismatches for pointers of
  6843. // different nesting levels, like:
  6844. // __local int *** a;
  6845. // int ** b = a;
  6846. // It's not clear how to actually determine when such pointers are
  6847. // invalidly incompatible.
  6848. if (lhq.getAddressSpace() != rhq.getAddressSpace())
  6849. return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
  6850. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  6851. if (lhptee == rhptee)
  6852. return Sema::IncompatibleNestedPointerQualifiers;
  6853. }
  6854. // General pointer incompatibility takes priority over qualifiers.
  6855. return Sema::IncompatiblePointer;
  6856. }
  6857. if (!S.getLangOpts().CPlusPlus &&
  6858. S.IsFunctionConversion(ltrans, rtrans, ltrans))
  6859. return Sema::IncompatiblePointer;
  6860. return ConvTy;
  6861. }
  6862. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  6863. /// block pointer types are compatible or whether a block and normal pointer
  6864. /// are compatible. It is more restrict than comparing two function pointer
  6865. // types.
  6866. static Sema::AssignConvertType
  6867. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  6868. QualType RHSType) {
  6869. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6870. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6871. QualType lhptee, rhptee;
  6872. // get the "pointed to" type (ignoring qualifiers at the top level)
  6873. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  6874. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  6875. // In C++, the types have to match exactly.
  6876. if (S.getLangOpts().CPlusPlus)
  6877. return Sema::IncompatibleBlockPointer;
  6878. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6879. // For blocks we enforce that qualifiers are identical.
  6880. Qualifiers LQuals = lhptee.getLocalQualifiers();
  6881. Qualifiers RQuals = rhptee.getLocalQualifiers();
  6882. if (S.getLangOpts().OpenCL) {
  6883. LQuals.removeAddressSpace();
  6884. RQuals.removeAddressSpace();
  6885. }
  6886. if (LQuals != RQuals)
  6887. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6888. // FIXME: OpenCL doesn't define the exact compile time semantics for a block
  6889. // assignment.
  6890. // The current behavior is similar to C++ lambdas. A block might be
  6891. // assigned to a variable iff its return type and parameters are compatible
  6892. // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
  6893. // an assignment. Presumably it should behave in way that a function pointer
  6894. // assignment does in C, so for each parameter and return type:
  6895. // * CVR and address space of LHS should be a superset of CVR and address
  6896. // space of RHS.
  6897. // * unqualified types should be compatible.
  6898. if (S.getLangOpts().OpenCL) {
  6899. if (!S.Context.typesAreBlockPointerCompatible(
  6900. S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
  6901. S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
  6902. return Sema::IncompatibleBlockPointer;
  6903. } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  6904. return Sema::IncompatibleBlockPointer;
  6905. return ConvTy;
  6906. }
  6907. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  6908. /// for assignment compatibility.
  6909. static Sema::AssignConvertType
  6910. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  6911. QualType RHSType) {
  6912. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  6913. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  6914. if (LHSType->isObjCBuiltinType()) {
  6915. // Class is not compatible with ObjC object pointers.
  6916. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  6917. !RHSType->isObjCQualifiedClassType())
  6918. return Sema::IncompatiblePointer;
  6919. return Sema::Compatible;
  6920. }
  6921. if (RHSType->isObjCBuiltinType()) {
  6922. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  6923. !LHSType->isObjCQualifiedClassType())
  6924. return Sema::IncompatiblePointer;
  6925. return Sema::Compatible;
  6926. }
  6927. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6928. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6929. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  6930. // make an exception for id<P>
  6931. !LHSType->isObjCQualifiedIdType())
  6932. return Sema::CompatiblePointerDiscardsQualifiers;
  6933. if (S.Context.typesAreCompatible(LHSType, RHSType))
  6934. return Sema::Compatible;
  6935. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  6936. return Sema::IncompatibleObjCQualifiedId;
  6937. return Sema::IncompatiblePointer;
  6938. }
  6939. Sema::AssignConvertType
  6940. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  6941. QualType LHSType, QualType RHSType) {
  6942. // Fake up an opaque expression. We don't actually care about what
  6943. // cast operations are required, so if CheckAssignmentConstraints
  6944. // adds casts to this they'll be wasted, but fortunately that doesn't
  6945. // usually happen on valid code.
  6946. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  6947. ExprResult RHSPtr = &RHSExpr;
  6948. CastKind K;
  6949. return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
  6950. }
  6951. /// This helper function returns true if QT is a vector type that has element
  6952. /// type ElementType.
  6953. static bool isVector(QualType QT, QualType ElementType) {
  6954. if (const VectorType *VT = QT->getAs<VectorType>())
  6955. return VT->getElementType() == ElementType;
  6956. return false;
  6957. }
  6958. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  6959. /// has code to accommodate several GCC extensions when type checking
  6960. /// pointers. Here are some objectionable examples that GCC considers warnings:
  6961. ///
  6962. /// int a, *pint;
  6963. /// short *pshort;
  6964. /// struct foo *pfoo;
  6965. ///
  6966. /// pint = pshort; // warning: assignment from incompatible pointer type
  6967. /// a = pint; // warning: assignment makes integer from pointer without a cast
  6968. /// pint = a; // warning: assignment makes pointer from integer without a cast
  6969. /// pint = pfoo; // warning: assignment from incompatible pointer type
  6970. ///
  6971. /// As a result, the code for dealing with pointers is more complex than the
  6972. /// C99 spec dictates.
  6973. ///
  6974. /// Sets 'Kind' for any result kind except Incompatible.
  6975. Sema::AssignConvertType
  6976. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6977. CastKind &Kind, bool ConvertRHS) {
  6978. QualType RHSType = RHS.get()->getType();
  6979. QualType OrigLHSType = LHSType;
  6980. // Get canonical types. We're not formatting these types, just comparing
  6981. // them.
  6982. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  6983. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  6984. // Common case: no conversion required.
  6985. if (LHSType == RHSType) {
  6986. Kind = CK_NoOp;
  6987. return Compatible;
  6988. }
  6989. // If we have an atomic type, try a non-atomic assignment, then just add an
  6990. // atomic qualification step.
  6991. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  6992. Sema::AssignConvertType result =
  6993. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  6994. if (result != Compatible)
  6995. return result;
  6996. if (Kind != CK_NoOp && ConvertRHS)
  6997. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  6998. Kind = CK_NonAtomicToAtomic;
  6999. return Compatible;
  7000. }
  7001. // If the left-hand side is a reference type, then we are in a
  7002. // (rare!) case where we've allowed the use of references in C,
  7003. // e.g., as a parameter type in a built-in function. In this case,
  7004. // just make sure that the type referenced is compatible with the
  7005. // right-hand side type. The caller is responsible for adjusting
  7006. // LHSType so that the resulting expression does not have reference
  7007. // type.
  7008. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  7009. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  7010. Kind = CK_LValueBitCast;
  7011. return Compatible;
  7012. }
  7013. return Incompatible;
  7014. }
  7015. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  7016. // to the same ExtVector type.
  7017. if (LHSType->isExtVectorType()) {
  7018. if (RHSType->isExtVectorType())
  7019. return Incompatible;
  7020. if (RHSType->isArithmeticType()) {
  7021. // CK_VectorSplat does T -> vector T, so first cast to the element type.
  7022. if (ConvertRHS)
  7023. RHS = prepareVectorSplat(LHSType, RHS.get());
  7024. Kind = CK_VectorSplat;
  7025. return Compatible;
  7026. }
  7027. }
  7028. // Conversions to or from vector type.
  7029. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  7030. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  7031. // Allow assignments of an AltiVec vector type to an equivalent GCC
  7032. // vector type and vice versa
  7033. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7034. Kind = CK_BitCast;
  7035. return Compatible;
  7036. }
  7037. // If we are allowing lax vector conversions, and LHS and RHS are both
  7038. // vectors, the total size only needs to be the same. This is a bitcast;
  7039. // no bits are changed but the result type is different.
  7040. if (isLaxVectorConversion(RHSType, LHSType)) {
  7041. Kind = CK_BitCast;
  7042. return IncompatibleVectors;
  7043. }
  7044. }
  7045. // When the RHS comes from another lax conversion (e.g. binops between
  7046. // scalars and vectors) the result is canonicalized as a vector. When the
  7047. // LHS is also a vector, the lax is allowed by the condition above. Handle
  7048. // the case where LHS is a scalar.
  7049. if (LHSType->isScalarType()) {
  7050. const VectorType *VecType = RHSType->getAs<VectorType>();
  7051. if (VecType && VecType->getNumElements() == 1 &&
  7052. isLaxVectorConversion(RHSType, LHSType)) {
  7053. ExprResult *VecExpr = &RHS;
  7054. *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
  7055. Kind = CK_BitCast;
  7056. return Compatible;
  7057. }
  7058. }
  7059. return Incompatible;
  7060. }
  7061. // Diagnose attempts to convert between __float128 and long double where
  7062. // such conversions currently can't be handled.
  7063. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  7064. return Incompatible;
  7065. // Disallow assigning a _Complex to a real type in C++ mode since it simply
  7066. // discards the imaginary part.
  7067. if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
  7068. !LHSType->getAs<ComplexType>())
  7069. return Incompatible;
  7070. // Arithmetic conversions.
  7071. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  7072. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  7073. if (ConvertRHS)
  7074. Kind = PrepareScalarCast(RHS, LHSType);
  7075. return Compatible;
  7076. }
  7077. // Conversions to normal pointers.
  7078. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  7079. // U* -> T*
  7080. if (isa<PointerType>(RHSType)) {
  7081. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  7082. LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  7083. if (AddrSpaceL != AddrSpaceR)
  7084. Kind = CK_AddressSpaceConversion;
  7085. else if (Context.hasCvrSimilarType(RHSType, LHSType))
  7086. Kind = CK_NoOp;
  7087. else
  7088. Kind = CK_BitCast;
  7089. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  7090. }
  7091. // int -> T*
  7092. if (RHSType->isIntegerType()) {
  7093. Kind = CK_IntegralToPointer; // FIXME: null?
  7094. return IntToPointer;
  7095. }
  7096. // C pointers are not compatible with ObjC object pointers,
  7097. // with two exceptions:
  7098. if (isa<ObjCObjectPointerType>(RHSType)) {
  7099. // - conversions to void*
  7100. if (LHSPointer->getPointeeType()->isVoidType()) {
  7101. Kind = CK_BitCast;
  7102. return Compatible;
  7103. }
  7104. // - conversions from 'Class' to the redefinition type
  7105. if (RHSType->isObjCClassType() &&
  7106. Context.hasSameType(LHSType,
  7107. Context.getObjCClassRedefinitionType())) {
  7108. Kind = CK_BitCast;
  7109. return Compatible;
  7110. }
  7111. Kind = CK_BitCast;
  7112. return IncompatiblePointer;
  7113. }
  7114. // U^ -> void*
  7115. if (RHSType->getAs<BlockPointerType>()) {
  7116. if (LHSPointer->getPointeeType()->isVoidType()) {
  7117. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  7118. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  7119. ->getPointeeType()
  7120. .getAddressSpace();
  7121. Kind =
  7122. AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  7123. return Compatible;
  7124. }
  7125. }
  7126. return Incompatible;
  7127. }
  7128. // Conversions to block pointers.
  7129. if (isa<BlockPointerType>(LHSType)) {
  7130. // U^ -> T^
  7131. if (RHSType->isBlockPointerType()) {
  7132. LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
  7133. ->getPointeeType()
  7134. .getAddressSpace();
  7135. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  7136. ->getPointeeType()
  7137. .getAddressSpace();
  7138. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  7139. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  7140. }
  7141. // int or null -> T^
  7142. if (RHSType->isIntegerType()) {
  7143. Kind = CK_IntegralToPointer; // FIXME: null
  7144. return IntToBlockPointer;
  7145. }
  7146. // id -> T^
  7147. if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
  7148. Kind = CK_AnyPointerToBlockPointerCast;
  7149. return Compatible;
  7150. }
  7151. // void* -> T^
  7152. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  7153. if (RHSPT->getPointeeType()->isVoidType()) {
  7154. Kind = CK_AnyPointerToBlockPointerCast;
  7155. return Compatible;
  7156. }
  7157. return Incompatible;
  7158. }
  7159. // Conversions to Objective-C pointers.
  7160. if (isa<ObjCObjectPointerType>(LHSType)) {
  7161. // A* -> B*
  7162. if (RHSType->isObjCObjectPointerType()) {
  7163. Kind = CK_BitCast;
  7164. Sema::AssignConvertType result =
  7165. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  7166. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7167. result == Compatible &&
  7168. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  7169. result = IncompatibleObjCWeakRef;
  7170. return result;
  7171. }
  7172. // int or null -> A*
  7173. if (RHSType->isIntegerType()) {
  7174. Kind = CK_IntegralToPointer; // FIXME: null
  7175. return IntToPointer;
  7176. }
  7177. // In general, C pointers are not compatible with ObjC object pointers,
  7178. // with two exceptions:
  7179. if (isa<PointerType>(RHSType)) {
  7180. Kind = CK_CPointerToObjCPointerCast;
  7181. // - conversions from 'void*'
  7182. if (RHSType->isVoidPointerType()) {
  7183. return Compatible;
  7184. }
  7185. // - conversions to 'Class' from its redefinition type
  7186. if (LHSType->isObjCClassType() &&
  7187. Context.hasSameType(RHSType,
  7188. Context.getObjCClassRedefinitionType())) {
  7189. return Compatible;
  7190. }
  7191. return IncompatiblePointer;
  7192. }
  7193. // Only under strict condition T^ is compatible with an Objective-C pointer.
  7194. if (RHSType->isBlockPointerType() &&
  7195. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  7196. if (ConvertRHS)
  7197. maybeExtendBlockObject(RHS);
  7198. Kind = CK_BlockPointerToObjCPointerCast;
  7199. return Compatible;
  7200. }
  7201. return Incompatible;
  7202. }
  7203. // Conversions from pointers that are not covered by the above.
  7204. if (isa<PointerType>(RHSType)) {
  7205. // T* -> _Bool
  7206. if (LHSType == Context.BoolTy) {
  7207. Kind = CK_PointerToBoolean;
  7208. return Compatible;
  7209. }
  7210. // T* -> int
  7211. if (LHSType->isIntegerType()) {
  7212. Kind = CK_PointerToIntegral;
  7213. return PointerToInt;
  7214. }
  7215. return Incompatible;
  7216. }
  7217. // Conversions from Objective-C pointers that are not covered by the above.
  7218. if (isa<ObjCObjectPointerType>(RHSType)) {
  7219. // T* -> _Bool
  7220. if (LHSType == Context.BoolTy) {
  7221. Kind = CK_PointerToBoolean;
  7222. return Compatible;
  7223. }
  7224. // T* -> int
  7225. if (LHSType->isIntegerType()) {
  7226. Kind = CK_PointerToIntegral;
  7227. return PointerToInt;
  7228. }
  7229. return Incompatible;
  7230. }
  7231. // struct A -> struct B
  7232. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  7233. if (Context.typesAreCompatible(LHSType, RHSType)) {
  7234. Kind = CK_NoOp;
  7235. return Compatible;
  7236. }
  7237. }
  7238. if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
  7239. Kind = CK_IntToOCLSampler;
  7240. return Compatible;
  7241. }
  7242. return Incompatible;
  7243. }
  7244. /// Constructs a transparent union from an expression that is
  7245. /// used to initialize the transparent union.
  7246. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  7247. ExprResult &EResult, QualType UnionType,
  7248. FieldDecl *Field) {
  7249. // Build an initializer list that designates the appropriate member
  7250. // of the transparent union.
  7251. Expr *E = EResult.get();
  7252. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  7253. E, SourceLocation());
  7254. Initializer->setType(UnionType);
  7255. Initializer->setInitializedFieldInUnion(Field);
  7256. // Build a compound literal constructing a value of the transparent
  7257. // union type from this initializer list.
  7258. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  7259. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  7260. VK_RValue, Initializer, false);
  7261. }
  7262. Sema::AssignConvertType
  7263. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  7264. ExprResult &RHS) {
  7265. QualType RHSType = RHS.get()->getType();
  7266. // If the ArgType is a Union type, we want to handle a potential
  7267. // transparent_union GCC extension.
  7268. const RecordType *UT = ArgType->getAsUnionType();
  7269. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  7270. return Incompatible;
  7271. // The field to initialize within the transparent union.
  7272. RecordDecl *UD = UT->getDecl();
  7273. FieldDecl *InitField = nullptr;
  7274. // It's compatible if the expression matches any of the fields.
  7275. for (auto *it : UD->fields()) {
  7276. if (it->getType()->isPointerType()) {
  7277. // If the transparent union contains a pointer type, we allow:
  7278. // 1) void pointer
  7279. // 2) null pointer constant
  7280. if (RHSType->isPointerType())
  7281. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  7282. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  7283. InitField = it;
  7284. break;
  7285. }
  7286. if (RHS.get()->isNullPointerConstant(Context,
  7287. Expr::NPC_ValueDependentIsNull)) {
  7288. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  7289. CK_NullToPointer);
  7290. InitField = it;
  7291. break;
  7292. }
  7293. }
  7294. CastKind Kind;
  7295. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  7296. == Compatible) {
  7297. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  7298. InitField = it;
  7299. break;
  7300. }
  7301. }
  7302. if (!InitField)
  7303. return Incompatible;
  7304. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  7305. return Compatible;
  7306. }
  7307. Sema::AssignConvertType
  7308. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
  7309. bool Diagnose,
  7310. bool DiagnoseCFAudited,
  7311. bool ConvertRHS) {
  7312. // We need to be able to tell the caller whether we diagnosed a problem, if
  7313. // they ask us to issue diagnostics.
  7314. assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
  7315. // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
  7316. // we can't avoid *all* modifications at the moment, so we need some somewhere
  7317. // to put the updated value.
  7318. ExprResult LocalRHS = CallerRHS;
  7319. ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
  7320. if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
  7321. if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
  7322. if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
  7323. !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
  7324. Diag(RHS.get()->getExprLoc(),
  7325. diag::warn_noderef_to_dereferenceable_pointer)
  7326. << RHS.get()->getSourceRange();
  7327. }
  7328. }
  7329. }
  7330. if (getLangOpts().CPlusPlus) {
  7331. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  7332. // C++ 5.17p3: If the left operand is not of class type, the
  7333. // expression is implicitly converted (C++ 4) to the
  7334. // cv-unqualified type of the left operand.
  7335. QualType RHSType = RHS.get()->getType();
  7336. if (Diagnose) {
  7337. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7338. AA_Assigning);
  7339. } else {
  7340. ImplicitConversionSequence ICS =
  7341. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7342. /*SuppressUserConversions=*/false,
  7343. /*AllowExplicit=*/false,
  7344. /*InOverloadResolution=*/false,
  7345. /*CStyle=*/false,
  7346. /*AllowObjCWritebackConversion=*/false);
  7347. if (ICS.isFailure())
  7348. return Incompatible;
  7349. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7350. ICS, AA_Assigning);
  7351. }
  7352. if (RHS.isInvalid())
  7353. return Incompatible;
  7354. Sema::AssignConvertType result = Compatible;
  7355. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7356. !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
  7357. result = IncompatibleObjCWeakRef;
  7358. return result;
  7359. }
  7360. // FIXME: Currently, we fall through and treat C++ classes like C
  7361. // structures.
  7362. // FIXME: We also fall through for atomics; not sure what should
  7363. // happen there, though.
  7364. } else if (RHS.get()->getType() == Context.OverloadTy) {
  7365. // As a set of extensions to C, we support overloading on functions. These
  7366. // functions need to be resolved here.
  7367. DeclAccessPair DAP;
  7368. if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
  7369. RHS.get(), LHSType, /*Complain=*/false, DAP))
  7370. RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
  7371. else
  7372. return Incompatible;
  7373. }
  7374. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  7375. // a null pointer constant.
  7376. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  7377. LHSType->isBlockPointerType()) &&
  7378. RHS.get()->isNullPointerConstant(Context,
  7379. Expr::NPC_ValueDependentIsNull)) {
  7380. if (Diagnose || ConvertRHS) {
  7381. CastKind Kind;
  7382. CXXCastPath Path;
  7383. CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
  7384. /*IgnoreBaseAccess=*/false, Diagnose);
  7385. if (ConvertRHS)
  7386. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  7387. }
  7388. return Compatible;
  7389. }
  7390. // OpenCL queue_t type assignment.
  7391. if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
  7392. Context, Expr::NPC_ValueDependentIsNull)) {
  7393. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7394. return Compatible;
  7395. }
  7396. // This check seems unnatural, however it is necessary to ensure the proper
  7397. // conversion of functions/arrays. If the conversion were done for all
  7398. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  7399. // expressions that suppress this implicit conversion (&, sizeof).
  7400. //
  7401. // Suppress this for references: C++ 8.5.3p5.
  7402. if (!LHSType->isReferenceType()) {
  7403. // FIXME: We potentially allocate here even if ConvertRHS is false.
  7404. RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
  7405. if (RHS.isInvalid())
  7406. return Incompatible;
  7407. }
  7408. CastKind Kind;
  7409. Sema::AssignConvertType result =
  7410. CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
  7411. // C99 6.5.16.1p2: The value of the right operand is converted to the
  7412. // type of the assignment expression.
  7413. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  7414. // so that we can use references in built-in functions even in C.
  7415. // The getNonReferenceType() call makes sure that the resulting expression
  7416. // does not have reference type.
  7417. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  7418. QualType Ty = LHSType.getNonLValueExprType(Context);
  7419. Expr *E = RHS.get();
  7420. // Check for various Objective-C errors. If we are not reporting
  7421. // diagnostics and just checking for errors, e.g., during overload
  7422. // resolution, return Incompatible to indicate the failure.
  7423. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7424. CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  7425. Diagnose, DiagnoseCFAudited) != ACR_okay) {
  7426. if (!Diagnose)
  7427. return Incompatible;
  7428. }
  7429. if (getLangOpts().ObjC &&
  7430. (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
  7431. E->getType(), E, Diagnose) ||
  7432. ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
  7433. if (!Diagnose)
  7434. return Incompatible;
  7435. // Replace the expression with a corrected version and continue so we
  7436. // can find further errors.
  7437. RHS = E;
  7438. return Compatible;
  7439. }
  7440. if (ConvertRHS)
  7441. RHS = ImpCastExprToType(E, Ty, Kind);
  7442. }
  7443. return result;
  7444. }
  7445. namespace {
  7446. /// The original operand to an operator, prior to the application of the usual
  7447. /// arithmetic conversions and converting the arguments of a builtin operator
  7448. /// candidate.
  7449. struct OriginalOperand {
  7450. explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
  7451. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
  7452. Op = MTE->GetTemporaryExpr();
  7453. if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
  7454. Op = BTE->getSubExpr();
  7455. if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
  7456. Orig = ICE->getSubExprAsWritten();
  7457. Conversion = ICE->getConversionFunction();
  7458. }
  7459. }
  7460. QualType getType() const { return Orig->getType(); }
  7461. Expr *Orig;
  7462. NamedDecl *Conversion;
  7463. };
  7464. }
  7465. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  7466. ExprResult &RHS) {
  7467. OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
  7468. Diag(Loc, diag::err_typecheck_invalid_operands)
  7469. << OrigLHS.getType() << OrigRHS.getType()
  7470. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7471. // If a user-defined conversion was applied to either of the operands prior
  7472. // to applying the built-in operator rules, tell the user about it.
  7473. if (OrigLHS.Conversion) {
  7474. Diag(OrigLHS.Conversion->getLocation(),
  7475. diag::note_typecheck_invalid_operands_converted)
  7476. << 0 << LHS.get()->getType();
  7477. }
  7478. if (OrigRHS.Conversion) {
  7479. Diag(OrigRHS.Conversion->getLocation(),
  7480. diag::note_typecheck_invalid_operands_converted)
  7481. << 1 << RHS.get()->getType();
  7482. }
  7483. return QualType();
  7484. }
  7485. // Diagnose cases where a scalar was implicitly converted to a vector and
  7486. // diagnose the underlying types. Otherwise, diagnose the error
  7487. // as invalid vector logical operands for non-C++ cases.
  7488. QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
  7489. ExprResult &RHS) {
  7490. QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
  7491. QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
  7492. bool LHSNatVec = LHSType->isVectorType();
  7493. bool RHSNatVec = RHSType->isVectorType();
  7494. if (!(LHSNatVec && RHSNatVec)) {
  7495. Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
  7496. Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
  7497. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7498. << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
  7499. << Vector->getSourceRange();
  7500. return QualType();
  7501. }
  7502. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7503. << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
  7504. << RHS.get()->getSourceRange();
  7505. return QualType();
  7506. }
  7507. /// Try to convert a value of non-vector type to a vector type by converting
  7508. /// the type to the element type of the vector and then performing a splat.
  7509. /// If the language is OpenCL, we only use conversions that promote scalar
  7510. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  7511. /// for float->int.
  7512. ///
  7513. /// OpenCL V2.0 6.2.6.p2:
  7514. /// An error shall occur if any scalar operand type has greater rank
  7515. /// than the type of the vector element.
  7516. ///
  7517. /// \param scalar - if non-null, actually perform the conversions
  7518. /// \return true if the operation fails (but without diagnosing the failure)
  7519. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  7520. QualType scalarTy,
  7521. QualType vectorEltTy,
  7522. QualType vectorTy,
  7523. unsigned &DiagID) {
  7524. // The conversion to apply to the scalar before splatting it,
  7525. // if necessary.
  7526. CastKind scalarCast = CK_NoOp;
  7527. if (vectorEltTy->isIntegralType(S.Context)) {
  7528. if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
  7529. (scalarTy->isIntegerType() &&
  7530. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
  7531. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7532. return true;
  7533. }
  7534. if (!scalarTy->isIntegralType(S.Context))
  7535. return true;
  7536. scalarCast = CK_IntegralCast;
  7537. } else if (vectorEltTy->isRealFloatingType()) {
  7538. if (scalarTy->isRealFloatingType()) {
  7539. if (S.getLangOpts().OpenCL &&
  7540. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
  7541. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7542. return true;
  7543. }
  7544. scalarCast = CK_FloatingCast;
  7545. }
  7546. else if (scalarTy->isIntegralType(S.Context))
  7547. scalarCast = CK_IntegralToFloating;
  7548. else
  7549. return true;
  7550. } else {
  7551. return true;
  7552. }
  7553. // Adjust scalar if desired.
  7554. if (scalar) {
  7555. if (scalarCast != CK_NoOp)
  7556. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  7557. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  7558. }
  7559. return false;
  7560. }
  7561. /// Convert vector E to a vector with the same number of elements but different
  7562. /// element type.
  7563. static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
  7564. const auto *VecTy = E->getType()->getAs<VectorType>();
  7565. assert(VecTy && "Expression E must be a vector");
  7566. QualType NewVecTy = S.Context.getVectorType(ElementType,
  7567. VecTy->getNumElements(),
  7568. VecTy->getVectorKind());
  7569. // Look through the implicit cast. Return the subexpression if its type is
  7570. // NewVecTy.
  7571. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  7572. if (ICE->getSubExpr()->getType() == NewVecTy)
  7573. return ICE->getSubExpr();
  7574. auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
  7575. return S.ImpCastExprToType(E, NewVecTy, Cast);
  7576. }
  7577. /// Test if a (constant) integer Int can be casted to another integer type
  7578. /// IntTy without losing precision.
  7579. static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
  7580. QualType OtherIntTy) {
  7581. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7582. // Reject cases where the value of the Int is unknown as that would
  7583. // possibly cause truncation, but accept cases where the scalar can be
  7584. // demoted without loss of precision.
  7585. Expr::EvalResult EVResult;
  7586. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  7587. int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
  7588. bool IntSigned = IntTy->hasSignedIntegerRepresentation();
  7589. bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
  7590. if (CstInt) {
  7591. // If the scalar is constant and is of a higher order and has more active
  7592. // bits that the vector element type, reject it.
  7593. llvm::APSInt Result = EVResult.Val.getInt();
  7594. unsigned NumBits = IntSigned
  7595. ? (Result.isNegative() ? Result.getMinSignedBits()
  7596. : Result.getActiveBits())
  7597. : Result.getActiveBits();
  7598. if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
  7599. return true;
  7600. // If the signedness of the scalar type and the vector element type
  7601. // differs and the number of bits is greater than that of the vector
  7602. // element reject it.
  7603. return (IntSigned != OtherIntSigned &&
  7604. NumBits > S.Context.getIntWidth(OtherIntTy));
  7605. }
  7606. // Reject cases where the value of the scalar is not constant and it's
  7607. // order is greater than that of the vector element type.
  7608. return (Order < 0);
  7609. }
  7610. /// Test if a (constant) integer Int can be casted to floating point type
  7611. /// FloatTy without losing precision.
  7612. static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
  7613. QualType FloatTy) {
  7614. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7615. // Determine if the integer constant can be expressed as a floating point
  7616. // number of the appropriate type.
  7617. Expr::EvalResult EVResult;
  7618. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  7619. uint64_t Bits = 0;
  7620. if (CstInt) {
  7621. // Reject constants that would be truncated if they were converted to
  7622. // the floating point type. Test by simple to/from conversion.
  7623. // FIXME: Ideally the conversion to an APFloat and from an APFloat
  7624. // could be avoided if there was a convertFromAPInt method
  7625. // which could signal back if implicit truncation occurred.
  7626. llvm::APSInt Result = EVResult.Val.getInt();
  7627. llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
  7628. Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
  7629. llvm::APFloat::rmTowardZero);
  7630. llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
  7631. !IntTy->hasSignedIntegerRepresentation());
  7632. bool Ignored = false;
  7633. Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
  7634. &Ignored);
  7635. if (Result != ConvertBack)
  7636. return true;
  7637. } else {
  7638. // Reject types that cannot be fully encoded into the mantissa of
  7639. // the float.
  7640. Bits = S.Context.getTypeSize(IntTy);
  7641. unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
  7642. S.Context.getFloatTypeSemantics(FloatTy));
  7643. if (Bits > FloatPrec)
  7644. return true;
  7645. }
  7646. return false;
  7647. }
  7648. /// Attempt to convert and splat Scalar into a vector whose types matches
  7649. /// Vector following GCC conversion rules. The rule is that implicit
  7650. /// conversion can occur when Scalar can be casted to match Vector's element
  7651. /// type without causing truncation of Scalar.
  7652. static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
  7653. ExprResult *Vector) {
  7654. QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
  7655. QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
  7656. const VectorType *VT = VectorTy->getAs<VectorType>();
  7657. assert(!isa<ExtVectorType>(VT) &&
  7658. "ExtVectorTypes should not be handled here!");
  7659. QualType VectorEltTy = VT->getElementType();
  7660. // Reject cases where the vector element type or the scalar element type are
  7661. // not integral or floating point types.
  7662. if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
  7663. return true;
  7664. // The conversion to apply to the scalar before splatting it,
  7665. // if necessary.
  7666. CastKind ScalarCast = CK_NoOp;
  7667. // Accept cases where the vector elements are integers and the scalar is
  7668. // an integer.
  7669. // FIXME: Notionally if the scalar was a floating point value with a precise
  7670. // integral representation, we could cast it to an appropriate integer
  7671. // type and then perform the rest of the checks here. GCC will perform
  7672. // this conversion in some cases as determined by the input language.
  7673. // We should accept it on a language independent basis.
  7674. if (VectorEltTy->isIntegralType(S.Context) &&
  7675. ScalarTy->isIntegralType(S.Context) &&
  7676. S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
  7677. if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
  7678. return true;
  7679. ScalarCast = CK_IntegralCast;
  7680. } else if (VectorEltTy->isRealFloatingType()) {
  7681. if (ScalarTy->isRealFloatingType()) {
  7682. // Reject cases where the scalar type is not a constant and has a higher
  7683. // Order than the vector element type.
  7684. llvm::APFloat Result(0.0);
  7685. bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
  7686. int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
  7687. if (!CstScalar && Order < 0)
  7688. return true;
  7689. // If the scalar cannot be safely casted to the vector element type,
  7690. // reject it.
  7691. if (CstScalar) {
  7692. bool Truncated = false;
  7693. Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
  7694. llvm::APFloat::rmNearestTiesToEven, &Truncated);
  7695. if (Truncated)
  7696. return true;
  7697. }
  7698. ScalarCast = CK_FloatingCast;
  7699. } else if (ScalarTy->isIntegralType(S.Context)) {
  7700. if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
  7701. return true;
  7702. ScalarCast = CK_IntegralToFloating;
  7703. } else
  7704. return true;
  7705. }
  7706. // Adjust scalar if desired.
  7707. if (Scalar) {
  7708. if (ScalarCast != CK_NoOp)
  7709. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
  7710. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
  7711. }
  7712. return false;
  7713. }
  7714. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  7715. SourceLocation Loc, bool IsCompAssign,
  7716. bool AllowBothBool,
  7717. bool AllowBoolConversions) {
  7718. if (!IsCompAssign) {
  7719. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  7720. if (LHS.isInvalid())
  7721. return QualType();
  7722. }
  7723. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  7724. if (RHS.isInvalid())
  7725. return QualType();
  7726. // For conversion purposes, we ignore any qualifiers.
  7727. // For example, "const float" and "float" are equivalent.
  7728. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  7729. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  7730. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  7731. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  7732. assert(LHSVecType || RHSVecType);
  7733. // AltiVec-style "vector bool op vector bool" combinations are allowed
  7734. // for some operators but not others.
  7735. if (!AllowBothBool &&
  7736. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7737. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7738. return InvalidOperands(Loc, LHS, RHS);
  7739. // If the vector types are identical, return.
  7740. if (Context.hasSameType(LHSType, RHSType))
  7741. return LHSType;
  7742. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  7743. if (LHSVecType && RHSVecType &&
  7744. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7745. if (isa<ExtVectorType>(LHSVecType)) {
  7746. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7747. return LHSType;
  7748. }
  7749. if (!IsCompAssign)
  7750. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7751. return RHSType;
  7752. }
  7753. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  7754. // can be mixed, with the result being the non-bool type. The non-bool
  7755. // operand must have integer element type.
  7756. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  7757. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  7758. (Context.getTypeSize(LHSVecType->getElementType()) ==
  7759. Context.getTypeSize(RHSVecType->getElementType()))) {
  7760. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7761. LHSVecType->getElementType()->isIntegerType() &&
  7762. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  7763. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7764. return LHSType;
  7765. }
  7766. if (!IsCompAssign &&
  7767. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7768. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7769. RHSVecType->getElementType()->isIntegerType()) {
  7770. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7771. return RHSType;
  7772. }
  7773. }
  7774. // If there's a vector type and a scalar, try to convert the scalar to
  7775. // the vector element type and splat.
  7776. unsigned DiagID = diag::err_typecheck_vector_not_convertable;
  7777. if (!RHSVecType) {
  7778. if (isa<ExtVectorType>(LHSVecType)) {
  7779. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  7780. LHSVecType->getElementType(), LHSType,
  7781. DiagID))
  7782. return LHSType;
  7783. } else {
  7784. if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
  7785. return LHSType;
  7786. }
  7787. }
  7788. if (!LHSVecType) {
  7789. if (isa<ExtVectorType>(RHSVecType)) {
  7790. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  7791. LHSType, RHSVecType->getElementType(),
  7792. RHSType, DiagID))
  7793. return RHSType;
  7794. } else {
  7795. if (LHS.get()->getValueKind() == VK_LValue ||
  7796. !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
  7797. return RHSType;
  7798. }
  7799. }
  7800. // FIXME: The code below also handles conversion between vectors and
  7801. // non-scalars, we should break this down into fine grained specific checks
  7802. // and emit proper diagnostics.
  7803. QualType VecType = LHSVecType ? LHSType : RHSType;
  7804. const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
  7805. QualType OtherType = LHSVecType ? RHSType : LHSType;
  7806. ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
  7807. if (isLaxVectorConversion(OtherType, VecType)) {
  7808. // If we're allowing lax vector conversions, only the total (data) size
  7809. // needs to be the same. For non compound assignment, if one of the types is
  7810. // scalar, the result is always the vector type.
  7811. if (!IsCompAssign) {
  7812. *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
  7813. return VecType;
  7814. // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
  7815. // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
  7816. // type. Note that this is already done by non-compound assignments in
  7817. // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
  7818. // <1 x T> -> T. The result is also a vector type.
  7819. } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
  7820. (OtherType->isScalarType() && VT->getNumElements() == 1)) {
  7821. ExprResult *RHSExpr = &RHS;
  7822. *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
  7823. return VecType;
  7824. }
  7825. }
  7826. // Okay, the expression is invalid.
  7827. // If there's a non-vector, non-real operand, diagnose that.
  7828. if ((!RHSVecType && !RHSType->isRealType()) ||
  7829. (!LHSVecType && !LHSType->isRealType())) {
  7830. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  7831. << LHSType << RHSType
  7832. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7833. return QualType();
  7834. }
  7835. // OpenCL V1.1 6.2.6.p1:
  7836. // If the operands are of more than one vector type, then an error shall
  7837. // occur. Implicit conversions between vector types are not permitted, per
  7838. // section 6.2.1.
  7839. if (getLangOpts().OpenCL &&
  7840. RHSVecType && isa<ExtVectorType>(RHSVecType) &&
  7841. LHSVecType && isa<ExtVectorType>(LHSVecType)) {
  7842. Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
  7843. << RHSType;
  7844. return QualType();
  7845. }
  7846. // If there is a vector type that is not a ExtVector and a scalar, we reach
  7847. // this point if scalar could not be converted to the vector's element type
  7848. // without truncation.
  7849. if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
  7850. (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
  7851. QualType Scalar = LHSVecType ? RHSType : LHSType;
  7852. QualType Vector = LHSVecType ? LHSType : RHSType;
  7853. unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
  7854. Diag(Loc,
  7855. diag::err_typecheck_vector_not_convertable_implict_truncation)
  7856. << ScalarOrVector << Scalar << Vector;
  7857. return QualType();
  7858. }
  7859. // Otherwise, use the generic diagnostic.
  7860. Diag(Loc, DiagID)
  7861. << LHSType << RHSType
  7862. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7863. return QualType();
  7864. }
  7865. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  7866. // expression. These are mainly cases where the null pointer is used as an
  7867. // integer instead of a pointer.
  7868. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  7869. SourceLocation Loc, bool IsCompare) {
  7870. // The canonical way to check for a GNU null is with isNullPointerConstant,
  7871. // but we use a bit of a hack here for speed; this is a relatively
  7872. // hot path, and isNullPointerConstant is slow.
  7873. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  7874. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  7875. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  7876. // Avoid analyzing cases where the result will either be invalid (and
  7877. // diagnosed as such) or entirely valid and not something to warn about.
  7878. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  7879. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  7880. return;
  7881. // Comparison operations would not make sense with a null pointer no matter
  7882. // what the other expression is.
  7883. if (!IsCompare) {
  7884. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  7885. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  7886. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  7887. return;
  7888. }
  7889. // The rest of the operations only make sense with a null pointer
  7890. // if the other expression is a pointer.
  7891. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  7892. NonNullType->canDecayToPointerType())
  7893. return;
  7894. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  7895. << LHSNull /* LHS is NULL */ << NonNullType
  7896. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7897. }
  7898. static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
  7899. SourceLocation Loc) {
  7900. const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
  7901. const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
  7902. if (!LUE || !RUE)
  7903. return;
  7904. if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
  7905. RUE->getKind() != UETT_SizeOf)
  7906. return;
  7907. QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
  7908. QualType RHSTy;
  7909. if (RUE->isArgumentType())
  7910. RHSTy = RUE->getArgumentType();
  7911. else
  7912. RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
  7913. if (!LHSTy->isPointerType() || RHSTy->isPointerType())
  7914. return;
  7915. if (LHSTy->getPointeeType() != RHSTy)
  7916. return;
  7917. S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
  7918. }
  7919. static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
  7920. ExprResult &RHS,
  7921. SourceLocation Loc, bool IsDiv) {
  7922. // Check for division/remainder by zero.
  7923. Expr::EvalResult RHSValue;
  7924. if (!RHS.get()->isValueDependent() &&
  7925. RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
  7926. RHSValue.Val.getInt() == 0)
  7927. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7928. S.PDiag(diag::warn_remainder_division_by_zero)
  7929. << IsDiv << RHS.get()->getSourceRange());
  7930. }
  7931. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  7932. SourceLocation Loc,
  7933. bool IsCompAssign, bool IsDiv) {
  7934. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7935. if (LHS.get()->getType()->isVectorType() ||
  7936. RHS.get()->getType()->isVectorType())
  7937. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7938. /*AllowBothBool*/getLangOpts().AltiVec,
  7939. /*AllowBoolConversions*/false);
  7940. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  7941. if (LHS.isInvalid() || RHS.isInvalid())
  7942. return QualType();
  7943. if (compType.isNull() || !compType->isArithmeticType())
  7944. return InvalidOperands(Loc, LHS, RHS);
  7945. if (IsDiv) {
  7946. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
  7947. DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
  7948. }
  7949. return compType;
  7950. }
  7951. QualType Sema::CheckRemainderOperands(
  7952. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  7953. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7954. if (LHS.get()->getType()->isVectorType() ||
  7955. RHS.get()->getType()->isVectorType()) {
  7956. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  7957. RHS.get()->getType()->hasIntegerRepresentation())
  7958. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7959. /*AllowBothBool*/getLangOpts().AltiVec,
  7960. /*AllowBoolConversions*/false);
  7961. return InvalidOperands(Loc, LHS, RHS);
  7962. }
  7963. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  7964. if (LHS.isInvalid() || RHS.isInvalid())
  7965. return QualType();
  7966. if (compType.isNull() || !compType->isIntegerType())
  7967. return InvalidOperands(Loc, LHS, RHS);
  7968. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
  7969. return compType;
  7970. }
  7971. /// Diagnose invalid arithmetic on two void pointers.
  7972. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  7973. Expr *LHSExpr, Expr *RHSExpr) {
  7974. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7975. ? diag::err_typecheck_pointer_arith_void_type
  7976. : diag::ext_gnu_void_ptr)
  7977. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  7978. << RHSExpr->getSourceRange();
  7979. }
  7980. /// Diagnose invalid arithmetic on a void pointer.
  7981. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  7982. Expr *Pointer) {
  7983. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7984. ? diag::err_typecheck_pointer_arith_void_type
  7985. : diag::ext_gnu_void_ptr)
  7986. << 0 /* one pointer */ << Pointer->getSourceRange();
  7987. }
  7988. /// Diagnose invalid arithmetic on a null pointer.
  7989. ///
  7990. /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
  7991. /// idiom, which we recognize as a GNU extension.
  7992. ///
  7993. static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
  7994. Expr *Pointer, bool IsGNUIdiom) {
  7995. if (IsGNUIdiom)
  7996. S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
  7997. << Pointer->getSourceRange();
  7998. else
  7999. S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
  8000. << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
  8001. }
  8002. /// Diagnose invalid arithmetic on two function pointers.
  8003. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  8004. Expr *LHS, Expr *RHS) {
  8005. assert(LHS->getType()->isAnyPointerType());
  8006. assert(RHS->getType()->isAnyPointerType());
  8007. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8008. ? diag::err_typecheck_pointer_arith_function_type
  8009. : diag::ext_gnu_ptr_func_arith)
  8010. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  8011. // We only show the second type if it differs from the first.
  8012. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  8013. RHS->getType())
  8014. << RHS->getType()->getPointeeType()
  8015. << LHS->getSourceRange() << RHS->getSourceRange();
  8016. }
  8017. /// Diagnose invalid arithmetic on a function pointer.
  8018. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  8019. Expr *Pointer) {
  8020. assert(Pointer->getType()->isAnyPointerType());
  8021. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8022. ? diag::err_typecheck_pointer_arith_function_type
  8023. : diag::ext_gnu_ptr_func_arith)
  8024. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  8025. << 0 /* one pointer, so only one type */
  8026. << Pointer->getSourceRange();
  8027. }
  8028. /// Emit error if Operand is incomplete pointer type
  8029. ///
  8030. /// \returns True if pointer has incomplete type
  8031. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  8032. Expr *Operand) {
  8033. QualType ResType = Operand->getType();
  8034. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8035. ResType = ResAtomicType->getValueType();
  8036. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  8037. QualType PointeeTy = ResType->getPointeeType();
  8038. return S.RequireCompleteType(Loc, PointeeTy,
  8039. diag::err_typecheck_arithmetic_incomplete_type,
  8040. PointeeTy, Operand->getSourceRange());
  8041. }
  8042. /// Check the validity of an arithmetic pointer operand.
  8043. ///
  8044. /// If the operand has pointer type, this code will check for pointer types
  8045. /// which are invalid in arithmetic operations. These will be diagnosed
  8046. /// appropriately, including whether or not the use is supported as an
  8047. /// extension.
  8048. ///
  8049. /// \returns True when the operand is valid to use (even if as an extension).
  8050. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  8051. Expr *Operand) {
  8052. QualType ResType = Operand->getType();
  8053. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8054. ResType = ResAtomicType->getValueType();
  8055. if (!ResType->isAnyPointerType()) return true;
  8056. QualType PointeeTy = ResType->getPointeeType();
  8057. if (PointeeTy->isVoidType()) {
  8058. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  8059. return !S.getLangOpts().CPlusPlus;
  8060. }
  8061. if (PointeeTy->isFunctionType()) {
  8062. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  8063. return !S.getLangOpts().CPlusPlus;
  8064. }
  8065. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  8066. return true;
  8067. }
  8068. /// Check the validity of a binary arithmetic operation w.r.t. pointer
  8069. /// operands.
  8070. ///
  8071. /// This routine will diagnose any invalid arithmetic on pointer operands much
  8072. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  8073. /// for emitting a single diagnostic even for operations where both LHS and RHS
  8074. /// are (potentially problematic) pointers.
  8075. ///
  8076. /// \returns True when the operand is valid to use (even if as an extension).
  8077. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  8078. Expr *LHSExpr, Expr *RHSExpr) {
  8079. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  8080. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  8081. if (!isLHSPointer && !isRHSPointer) return true;
  8082. QualType LHSPointeeTy, RHSPointeeTy;
  8083. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  8084. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  8085. // if both are pointers check if operation is valid wrt address spaces
  8086. if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
  8087. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  8088. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  8089. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  8090. S.Diag(Loc,
  8091. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  8092. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  8093. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  8094. return false;
  8095. }
  8096. }
  8097. // Check for arithmetic on pointers to incomplete types.
  8098. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  8099. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  8100. if (isLHSVoidPtr || isRHSVoidPtr) {
  8101. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  8102. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  8103. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  8104. return !S.getLangOpts().CPlusPlus;
  8105. }
  8106. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  8107. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  8108. if (isLHSFuncPtr || isRHSFuncPtr) {
  8109. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  8110. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  8111. RHSExpr);
  8112. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  8113. return !S.getLangOpts().CPlusPlus;
  8114. }
  8115. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  8116. return false;
  8117. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  8118. return false;
  8119. return true;
  8120. }
  8121. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  8122. /// literal.
  8123. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  8124. Expr *LHSExpr, Expr *RHSExpr) {
  8125. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  8126. Expr* IndexExpr = RHSExpr;
  8127. if (!StrExpr) {
  8128. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  8129. IndexExpr = LHSExpr;
  8130. }
  8131. bool IsStringPlusInt = StrExpr &&
  8132. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  8133. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  8134. return;
  8135. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  8136. Self.Diag(OpLoc, diag::warn_string_plus_int)
  8137. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  8138. // Only print a fixit for "str" + int, not for int + "str".
  8139. if (IndexExpr == RHSExpr) {
  8140. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  8141. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  8142. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  8143. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  8144. << FixItHint::CreateInsertion(EndLoc, "]");
  8145. } else
  8146. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  8147. }
  8148. /// Emit a warning when adding a char literal to a string.
  8149. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  8150. Expr *LHSExpr, Expr *RHSExpr) {
  8151. const Expr *StringRefExpr = LHSExpr;
  8152. const CharacterLiteral *CharExpr =
  8153. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  8154. if (!CharExpr) {
  8155. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  8156. StringRefExpr = RHSExpr;
  8157. }
  8158. if (!CharExpr || !StringRefExpr)
  8159. return;
  8160. const QualType StringType = StringRefExpr->getType();
  8161. // Return if not a PointerType.
  8162. if (!StringType->isAnyPointerType())
  8163. return;
  8164. // Return if not a CharacterType.
  8165. if (!StringType->getPointeeType()->isAnyCharacterType())
  8166. return;
  8167. ASTContext &Ctx = Self.getASTContext();
  8168. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  8169. const QualType CharType = CharExpr->getType();
  8170. if (!CharType->isAnyCharacterType() &&
  8171. CharType->isIntegerType() &&
  8172. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  8173. Self.Diag(OpLoc, diag::warn_string_plus_char)
  8174. << DiagRange << Ctx.CharTy;
  8175. } else {
  8176. Self.Diag(OpLoc, diag::warn_string_plus_char)
  8177. << DiagRange << CharExpr->getType();
  8178. }
  8179. // Only print a fixit for str + char, not for char + str.
  8180. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  8181. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  8182. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  8183. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  8184. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  8185. << FixItHint::CreateInsertion(EndLoc, "]");
  8186. } else {
  8187. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  8188. }
  8189. }
  8190. /// Emit error when two pointers are incompatible.
  8191. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  8192. Expr *LHSExpr, Expr *RHSExpr) {
  8193. assert(LHSExpr->getType()->isAnyPointerType());
  8194. assert(RHSExpr->getType()->isAnyPointerType());
  8195. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  8196. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  8197. << RHSExpr->getSourceRange();
  8198. }
  8199. // C99 6.5.6
  8200. QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
  8201. SourceLocation Loc, BinaryOperatorKind Opc,
  8202. QualType* CompLHSTy) {
  8203. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  8204. if (LHS.get()->getType()->isVectorType() ||
  8205. RHS.get()->getType()->isVectorType()) {
  8206. QualType compType = CheckVectorOperands(
  8207. LHS, RHS, Loc, CompLHSTy,
  8208. /*AllowBothBool*/getLangOpts().AltiVec,
  8209. /*AllowBoolConversions*/getLangOpts().ZVector);
  8210. if (CompLHSTy) *CompLHSTy = compType;
  8211. return compType;
  8212. }
  8213. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  8214. if (LHS.isInvalid() || RHS.isInvalid())
  8215. return QualType();
  8216. // Diagnose "string literal" '+' int and string '+' "char literal".
  8217. if (Opc == BO_Add) {
  8218. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  8219. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  8220. }
  8221. // handle the common case first (both operands are arithmetic).
  8222. if (!compType.isNull() && compType->isArithmeticType()) {
  8223. if (CompLHSTy) *CompLHSTy = compType;
  8224. return compType;
  8225. }
  8226. // Type-checking. Ultimately the pointer's going to be in PExp;
  8227. // note that we bias towards the LHS being the pointer.
  8228. Expr *PExp = LHS.get(), *IExp = RHS.get();
  8229. bool isObjCPointer;
  8230. if (PExp->getType()->isPointerType()) {
  8231. isObjCPointer = false;
  8232. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8233. isObjCPointer = true;
  8234. } else {
  8235. std::swap(PExp, IExp);
  8236. if (PExp->getType()->isPointerType()) {
  8237. isObjCPointer = false;
  8238. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8239. isObjCPointer = true;
  8240. } else {
  8241. return InvalidOperands(Loc, LHS, RHS);
  8242. }
  8243. }
  8244. assert(PExp->getType()->isAnyPointerType());
  8245. if (!IExp->getType()->isIntegerType())
  8246. return InvalidOperands(Loc, LHS, RHS);
  8247. // Adding to a null pointer results in undefined behavior.
  8248. if (PExp->IgnoreParenCasts()->isNullPointerConstant(
  8249. Context, Expr::NPC_ValueDependentIsNotNull)) {
  8250. // In C++ adding zero to a null pointer is defined.
  8251. Expr::EvalResult KnownVal;
  8252. if (!getLangOpts().CPlusPlus ||
  8253. (!IExp->isValueDependent() &&
  8254. (!IExp->EvaluateAsInt(KnownVal, Context) ||
  8255. KnownVal.Val.getInt() != 0))) {
  8256. // Check the conditions to see if this is the 'p = nullptr + n' idiom.
  8257. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
  8258. Context, BO_Add, PExp, IExp);
  8259. diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
  8260. }
  8261. }
  8262. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  8263. return QualType();
  8264. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  8265. return QualType();
  8266. // Check array bounds for pointer arithemtic
  8267. CheckArrayAccess(PExp, IExp);
  8268. if (CompLHSTy) {
  8269. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  8270. if (LHSTy.isNull()) {
  8271. LHSTy = LHS.get()->getType();
  8272. if (LHSTy->isPromotableIntegerType())
  8273. LHSTy = Context.getPromotedIntegerType(LHSTy);
  8274. }
  8275. *CompLHSTy = LHSTy;
  8276. }
  8277. return PExp->getType();
  8278. }
  8279. // C99 6.5.6
  8280. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  8281. SourceLocation Loc,
  8282. QualType* CompLHSTy) {
  8283. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  8284. if (LHS.get()->getType()->isVectorType() ||
  8285. RHS.get()->getType()->isVectorType()) {
  8286. QualType compType = CheckVectorOperands(
  8287. LHS, RHS, Loc, CompLHSTy,
  8288. /*AllowBothBool*/getLangOpts().AltiVec,
  8289. /*AllowBoolConversions*/getLangOpts().ZVector);
  8290. if (CompLHSTy) *CompLHSTy = compType;
  8291. return compType;
  8292. }
  8293. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  8294. if (LHS.isInvalid() || RHS.isInvalid())
  8295. return QualType();
  8296. // Enforce type constraints: C99 6.5.6p3.
  8297. // Handle the common case first (both operands are arithmetic).
  8298. if (!compType.isNull() && compType->isArithmeticType()) {
  8299. if (CompLHSTy) *CompLHSTy = compType;
  8300. return compType;
  8301. }
  8302. // Either ptr - int or ptr - ptr.
  8303. if (LHS.get()->getType()->isAnyPointerType()) {
  8304. QualType lpointee = LHS.get()->getType()->getPointeeType();
  8305. // Diagnose bad cases where we step over interface counts.
  8306. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  8307. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  8308. return QualType();
  8309. // The result type of a pointer-int computation is the pointer type.
  8310. if (RHS.get()->getType()->isIntegerType()) {
  8311. // Subtracting from a null pointer should produce a warning.
  8312. // The last argument to the diagnose call says this doesn't match the
  8313. // GNU int-to-pointer idiom.
  8314. if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
  8315. Expr::NPC_ValueDependentIsNotNull)) {
  8316. // In C++ adding zero to a null pointer is defined.
  8317. Expr::EvalResult KnownVal;
  8318. if (!getLangOpts().CPlusPlus ||
  8319. (!RHS.get()->isValueDependent() &&
  8320. (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
  8321. KnownVal.Val.getInt() != 0))) {
  8322. diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
  8323. }
  8324. }
  8325. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  8326. return QualType();
  8327. // Check array bounds for pointer arithemtic
  8328. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  8329. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  8330. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8331. return LHS.get()->getType();
  8332. }
  8333. // Handle pointer-pointer subtractions.
  8334. if (const PointerType *RHSPTy
  8335. = RHS.get()->getType()->getAs<PointerType>()) {
  8336. QualType rpointee = RHSPTy->getPointeeType();
  8337. if (getLangOpts().CPlusPlus) {
  8338. // Pointee types must be the same: C++ [expr.add]
  8339. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  8340. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8341. }
  8342. } else {
  8343. // Pointee types must be compatible C99 6.5.6p3
  8344. if (!Context.typesAreCompatible(
  8345. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  8346. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  8347. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8348. return QualType();
  8349. }
  8350. }
  8351. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  8352. LHS.get(), RHS.get()))
  8353. return QualType();
  8354. // FIXME: Add warnings for nullptr - ptr.
  8355. // The pointee type may have zero size. As an extension, a structure or
  8356. // union may have zero size or an array may have zero length. In this
  8357. // case subtraction does not make sense.
  8358. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  8359. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  8360. if (ElementSize.isZero()) {
  8361. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  8362. << rpointee.getUnqualifiedType()
  8363. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8364. }
  8365. }
  8366. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8367. return Context.getPointerDiffType();
  8368. }
  8369. }
  8370. return InvalidOperands(Loc, LHS, RHS);
  8371. }
  8372. static bool isScopedEnumerationType(QualType T) {
  8373. if (const EnumType *ET = T->getAs<EnumType>())
  8374. return ET->getDecl()->isScoped();
  8375. return false;
  8376. }
  8377. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  8378. SourceLocation Loc, BinaryOperatorKind Opc,
  8379. QualType LHSType) {
  8380. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  8381. // so skip remaining warnings as we don't want to modify values within Sema.
  8382. if (S.getLangOpts().OpenCL)
  8383. return;
  8384. // Check right/shifter operand
  8385. Expr::EvalResult RHSResult;
  8386. if (RHS.get()->isValueDependent() ||
  8387. !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
  8388. return;
  8389. llvm::APSInt Right = RHSResult.Val.getInt();
  8390. if (Right.isNegative()) {
  8391. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8392. S.PDiag(diag::warn_shift_negative)
  8393. << RHS.get()->getSourceRange());
  8394. return;
  8395. }
  8396. llvm::APInt LeftBits(Right.getBitWidth(),
  8397. S.Context.getTypeSize(LHS.get()->getType()));
  8398. if (Right.uge(LeftBits)) {
  8399. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8400. S.PDiag(diag::warn_shift_gt_typewidth)
  8401. << RHS.get()->getSourceRange());
  8402. return;
  8403. }
  8404. if (Opc != BO_Shl)
  8405. return;
  8406. // When left shifting an ICE which is signed, we can check for overflow which
  8407. // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
  8408. // integers have defined behavior modulo one more than the maximum value
  8409. // representable in the result type, so never warn for those.
  8410. Expr::EvalResult LHSResult;
  8411. if (LHS.get()->isValueDependent() ||
  8412. LHSType->hasUnsignedIntegerRepresentation() ||
  8413. !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
  8414. return;
  8415. llvm::APSInt Left = LHSResult.Val.getInt();
  8416. // If LHS does not have a signed type and non-negative value
  8417. // then, the behavior is undefined. Warn about it.
  8418. if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
  8419. S.DiagRuntimeBehavior(Loc, LHS.get(),
  8420. S.PDiag(diag::warn_shift_lhs_negative)
  8421. << LHS.get()->getSourceRange());
  8422. return;
  8423. }
  8424. llvm::APInt ResultBits =
  8425. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  8426. if (LeftBits.uge(ResultBits))
  8427. return;
  8428. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  8429. Result = Result.shl(Right);
  8430. // Print the bit representation of the signed integer as an unsigned
  8431. // hexadecimal number.
  8432. SmallString<40> HexResult;
  8433. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  8434. // If we are only missing a sign bit, this is less likely to result in actual
  8435. // bugs -- if the result is cast back to an unsigned type, it will have the
  8436. // expected value. Thus we place this behind a different warning that can be
  8437. // turned off separately if needed.
  8438. if (LeftBits == ResultBits - 1) {
  8439. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  8440. << HexResult << LHSType
  8441. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8442. return;
  8443. }
  8444. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  8445. << HexResult.str() << Result.getMinSignedBits() << LHSType
  8446. << Left.getBitWidth() << LHS.get()->getSourceRange()
  8447. << RHS.get()->getSourceRange();
  8448. }
  8449. /// Return the resulting type when a vector is shifted
  8450. /// by a scalar or vector shift amount.
  8451. static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8452. SourceLocation Loc, bool IsCompAssign) {
  8453. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  8454. if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
  8455. !LHS.get()->getType()->isVectorType()) {
  8456. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  8457. << RHS.get()->getType() << LHS.get()->getType()
  8458. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8459. return QualType();
  8460. }
  8461. if (!IsCompAssign) {
  8462. LHS = S.UsualUnaryConversions(LHS.get());
  8463. if (LHS.isInvalid()) return QualType();
  8464. }
  8465. RHS = S.UsualUnaryConversions(RHS.get());
  8466. if (RHS.isInvalid()) return QualType();
  8467. QualType LHSType = LHS.get()->getType();
  8468. // Note that LHS might be a scalar because the routine calls not only in
  8469. // OpenCL case.
  8470. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  8471. QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
  8472. // Note that RHS might not be a vector.
  8473. QualType RHSType = RHS.get()->getType();
  8474. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  8475. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  8476. // The operands need to be integers.
  8477. if (!LHSEleType->isIntegerType()) {
  8478. S.Diag(Loc, diag::err_typecheck_expect_int)
  8479. << LHS.get()->getType() << LHS.get()->getSourceRange();
  8480. return QualType();
  8481. }
  8482. if (!RHSEleType->isIntegerType()) {
  8483. S.Diag(Loc, diag::err_typecheck_expect_int)
  8484. << RHS.get()->getType() << RHS.get()->getSourceRange();
  8485. return QualType();
  8486. }
  8487. if (!LHSVecTy) {
  8488. assert(RHSVecTy);
  8489. if (IsCompAssign)
  8490. return RHSType;
  8491. if (LHSEleType != RHSEleType) {
  8492. LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
  8493. LHSEleType = RHSEleType;
  8494. }
  8495. QualType VecTy =
  8496. S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
  8497. LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
  8498. LHSType = VecTy;
  8499. } else if (RHSVecTy) {
  8500. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  8501. // are applied component-wise. So if RHS is a vector, then ensure
  8502. // that the number of elements is the same as LHS...
  8503. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  8504. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  8505. << LHS.get()->getType() << RHS.get()->getType()
  8506. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8507. return QualType();
  8508. }
  8509. if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
  8510. const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
  8511. const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
  8512. if (LHSBT != RHSBT &&
  8513. S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
  8514. S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
  8515. << LHS.get()->getType() << RHS.get()->getType()
  8516. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8517. }
  8518. }
  8519. } else {
  8520. // ...else expand RHS to match the number of elements in LHS.
  8521. QualType VecTy =
  8522. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  8523. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  8524. }
  8525. return LHSType;
  8526. }
  8527. // C99 6.5.7
  8528. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  8529. SourceLocation Loc, BinaryOperatorKind Opc,
  8530. bool IsCompAssign) {
  8531. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  8532. // Vector shifts promote their scalar inputs to vector type.
  8533. if (LHS.get()->getType()->isVectorType() ||
  8534. RHS.get()->getType()->isVectorType()) {
  8535. if (LangOpts.ZVector) {
  8536. // The shift operators for the z vector extensions work basically
  8537. // like general shifts, except that neither the LHS nor the RHS is
  8538. // allowed to be a "vector bool".
  8539. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  8540. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8541. return InvalidOperands(Loc, LHS, RHS);
  8542. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  8543. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8544. return InvalidOperands(Loc, LHS, RHS);
  8545. }
  8546. return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  8547. }
  8548. // Shifts don't perform usual arithmetic conversions, they just do integer
  8549. // promotions on each operand. C99 6.5.7p3
  8550. // For the LHS, do usual unary conversions, but then reset them away
  8551. // if this is a compound assignment.
  8552. ExprResult OldLHS = LHS;
  8553. LHS = UsualUnaryConversions(LHS.get());
  8554. if (LHS.isInvalid())
  8555. return QualType();
  8556. QualType LHSType = LHS.get()->getType();
  8557. if (IsCompAssign) LHS = OldLHS;
  8558. // The RHS is simpler.
  8559. RHS = UsualUnaryConversions(RHS.get());
  8560. if (RHS.isInvalid())
  8561. return QualType();
  8562. QualType RHSType = RHS.get()->getType();
  8563. // C99 6.5.7p2: Each of the operands shall have integer type.
  8564. if (!LHSType->hasIntegerRepresentation() ||
  8565. !RHSType->hasIntegerRepresentation())
  8566. return InvalidOperands(Loc, LHS, RHS);
  8567. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  8568. // hasIntegerRepresentation() above instead of this.
  8569. if (isScopedEnumerationType(LHSType) ||
  8570. isScopedEnumerationType(RHSType)) {
  8571. return InvalidOperands(Loc, LHS, RHS);
  8572. }
  8573. // Sanity-check shift operands
  8574. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  8575. // "The type of the result is that of the promoted left operand."
  8576. return LHSType;
  8577. }
  8578. /// If two different enums are compared, raise a warning.
  8579. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  8580. Expr *RHS) {
  8581. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  8582. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  8583. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  8584. if (!LHSEnumType)
  8585. return;
  8586. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  8587. if (!RHSEnumType)
  8588. return;
  8589. // Ignore anonymous enums.
  8590. if (!LHSEnumType->getDecl()->getIdentifier() &&
  8591. !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8592. return;
  8593. if (!RHSEnumType->getDecl()->getIdentifier() &&
  8594. !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8595. return;
  8596. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  8597. return;
  8598. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  8599. << LHSStrippedType << RHSStrippedType
  8600. << LHS->getSourceRange() << RHS->getSourceRange();
  8601. }
  8602. /// Diagnose bad pointer comparisons.
  8603. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  8604. ExprResult &LHS, ExprResult &RHS,
  8605. bool IsError) {
  8606. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  8607. : diag::ext_typecheck_comparison_of_distinct_pointers)
  8608. << LHS.get()->getType() << RHS.get()->getType()
  8609. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8610. }
  8611. /// Returns false if the pointers are converted to a composite type,
  8612. /// true otherwise.
  8613. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  8614. ExprResult &LHS, ExprResult &RHS) {
  8615. // C++ [expr.rel]p2:
  8616. // [...] Pointer conversions (4.10) and qualification
  8617. // conversions (4.4) are performed on pointer operands (or on
  8618. // a pointer operand and a null pointer constant) to bring
  8619. // them to their composite pointer type. [...]
  8620. //
  8621. // C++ [expr.eq]p1 uses the same notion for (in)equality
  8622. // comparisons of pointers.
  8623. QualType LHSType = LHS.get()->getType();
  8624. QualType RHSType = RHS.get()->getType();
  8625. assert(LHSType->isPointerType() || RHSType->isPointerType() ||
  8626. LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
  8627. QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
  8628. if (T.isNull()) {
  8629. if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
  8630. (RHSType->isPointerType() || RHSType->isMemberPointerType()))
  8631. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  8632. else
  8633. S.InvalidOperands(Loc, LHS, RHS);
  8634. return true;
  8635. }
  8636. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  8637. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  8638. return false;
  8639. }
  8640. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  8641. ExprResult &LHS,
  8642. ExprResult &RHS,
  8643. bool IsError) {
  8644. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  8645. : diag::ext_typecheck_comparison_of_fptr_to_void)
  8646. << LHS.get()->getType() << RHS.get()->getType()
  8647. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8648. }
  8649. static bool isObjCObjectLiteral(ExprResult &E) {
  8650. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  8651. case Stmt::ObjCArrayLiteralClass:
  8652. case Stmt::ObjCDictionaryLiteralClass:
  8653. case Stmt::ObjCStringLiteralClass:
  8654. case Stmt::ObjCBoxedExprClass:
  8655. return true;
  8656. default:
  8657. // Note that ObjCBoolLiteral is NOT an object literal!
  8658. return false;
  8659. }
  8660. }
  8661. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  8662. const ObjCObjectPointerType *Type =
  8663. LHS->getType()->getAs<ObjCObjectPointerType>();
  8664. // If this is not actually an Objective-C object, bail out.
  8665. if (!Type)
  8666. return false;
  8667. // Get the LHS object's interface type.
  8668. QualType InterfaceType = Type->getPointeeType();
  8669. // If the RHS isn't an Objective-C object, bail out.
  8670. if (!RHS->getType()->isObjCObjectPointerType())
  8671. return false;
  8672. // Try to find the -isEqual: method.
  8673. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  8674. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  8675. InterfaceType,
  8676. /*instance=*/true);
  8677. if (!Method) {
  8678. if (Type->isObjCIdType()) {
  8679. // For 'id', just check the global pool.
  8680. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  8681. /*receiverId=*/true);
  8682. } else {
  8683. // Check protocols.
  8684. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  8685. /*instance=*/true);
  8686. }
  8687. }
  8688. if (!Method)
  8689. return false;
  8690. QualType T = Method->parameters()[0]->getType();
  8691. if (!T->isObjCObjectPointerType())
  8692. return false;
  8693. QualType R = Method->getReturnType();
  8694. if (!R->isScalarType())
  8695. return false;
  8696. return true;
  8697. }
  8698. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  8699. FromE = FromE->IgnoreParenImpCasts();
  8700. switch (FromE->getStmtClass()) {
  8701. default:
  8702. break;
  8703. case Stmt::ObjCStringLiteralClass:
  8704. // "string literal"
  8705. return LK_String;
  8706. case Stmt::ObjCArrayLiteralClass:
  8707. // "array literal"
  8708. return LK_Array;
  8709. case Stmt::ObjCDictionaryLiteralClass:
  8710. // "dictionary literal"
  8711. return LK_Dictionary;
  8712. case Stmt::BlockExprClass:
  8713. return LK_Block;
  8714. case Stmt::ObjCBoxedExprClass: {
  8715. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  8716. switch (Inner->getStmtClass()) {
  8717. case Stmt::IntegerLiteralClass:
  8718. case Stmt::FloatingLiteralClass:
  8719. case Stmt::CharacterLiteralClass:
  8720. case Stmt::ObjCBoolLiteralExprClass:
  8721. case Stmt::CXXBoolLiteralExprClass:
  8722. // "numeric literal"
  8723. return LK_Numeric;
  8724. case Stmt::ImplicitCastExprClass: {
  8725. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  8726. // Boolean literals can be represented by implicit casts.
  8727. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  8728. return LK_Numeric;
  8729. break;
  8730. }
  8731. default:
  8732. break;
  8733. }
  8734. return LK_Boxed;
  8735. }
  8736. }
  8737. return LK_None;
  8738. }
  8739. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  8740. ExprResult &LHS, ExprResult &RHS,
  8741. BinaryOperator::Opcode Opc){
  8742. Expr *Literal;
  8743. Expr *Other;
  8744. if (isObjCObjectLiteral(LHS)) {
  8745. Literal = LHS.get();
  8746. Other = RHS.get();
  8747. } else {
  8748. Literal = RHS.get();
  8749. Other = LHS.get();
  8750. }
  8751. // Don't warn on comparisons against nil.
  8752. Other = Other->IgnoreParenCasts();
  8753. if (Other->isNullPointerConstant(S.getASTContext(),
  8754. Expr::NPC_ValueDependentIsNotNull))
  8755. return;
  8756. // This should be kept in sync with warn_objc_literal_comparison.
  8757. // LK_String should always be after the other literals, since it has its own
  8758. // warning flag.
  8759. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  8760. assert(LiteralKind != Sema::LK_Block);
  8761. if (LiteralKind == Sema::LK_None) {
  8762. llvm_unreachable("Unknown Objective-C object literal kind");
  8763. }
  8764. if (LiteralKind == Sema::LK_String)
  8765. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  8766. << Literal->getSourceRange();
  8767. else
  8768. S.Diag(Loc, diag::warn_objc_literal_comparison)
  8769. << LiteralKind << Literal->getSourceRange();
  8770. if (BinaryOperator::isEqualityOp(Opc) &&
  8771. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  8772. SourceLocation Start = LHS.get()->getBeginLoc();
  8773. SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
  8774. CharSourceRange OpRange =
  8775. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  8776. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  8777. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  8778. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  8779. << FixItHint::CreateInsertion(End, "]");
  8780. }
  8781. }
  8782. /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
  8783. static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
  8784. ExprResult &RHS, SourceLocation Loc,
  8785. BinaryOperatorKind Opc) {
  8786. // Check that left hand side is !something.
  8787. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  8788. if (!UO || UO->getOpcode() != UO_LNot) return;
  8789. // Only check if the right hand side is non-bool arithmetic type.
  8790. if (RHS.get()->isKnownToHaveBooleanValue()) return;
  8791. // Make sure that the something in !something is not bool.
  8792. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  8793. if (SubExpr->isKnownToHaveBooleanValue()) return;
  8794. // Emit warning.
  8795. bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
  8796. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
  8797. << Loc << IsBitwiseOp;
  8798. // First note suggest !(x < y)
  8799. SourceLocation FirstOpen = SubExpr->getBeginLoc();
  8800. SourceLocation FirstClose = RHS.get()->getEndLoc();
  8801. FirstClose = S.getLocForEndOfToken(FirstClose);
  8802. if (FirstClose.isInvalid())
  8803. FirstOpen = SourceLocation();
  8804. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  8805. << IsBitwiseOp
  8806. << FixItHint::CreateInsertion(FirstOpen, "(")
  8807. << FixItHint::CreateInsertion(FirstClose, ")");
  8808. // Second note suggests (!x) < y
  8809. SourceLocation SecondOpen = LHS.get()->getBeginLoc();
  8810. SourceLocation SecondClose = LHS.get()->getEndLoc();
  8811. SecondClose = S.getLocForEndOfToken(SecondClose);
  8812. if (SecondClose.isInvalid())
  8813. SecondOpen = SourceLocation();
  8814. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  8815. << FixItHint::CreateInsertion(SecondOpen, "(")
  8816. << FixItHint::CreateInsertion(SecondClose, ")");
  8817. }
  8818. // Get the decl for a simple expression: a reference to a variable,
  8819. // an implicit C++ field reference, or an implicit ObjC ivar reference.
  8820. static ValueDecl *getCompareDecl(Expr *E) {
  8821. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
  8822. return DR->getDecl();
  8823. if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
  8824. if (Ivar->isFreeIvar())
  8825. return Ivar->getDecl();
  8826. }
  8827. if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
  8828. if (Mem->isImplicitAccess())
  8829. return Mem->getMemberDecl();
  8830. }
  8831. return nullptr;
  8832. }
  8833. /// Diagnose some forms of syntactically-obvious tautological comparison.
  8834. static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
  8835. Expr *LHS, Expr *RHS,
  8836. BinaryOperatorKind Opc) {
  8837. Expr *LHSStripped = LHS->IgnoreParenImpCasts();
  8838. Expr *RHSStripped = RHS->IgnoreParenImpCasts();
  8839. QualType LHSType = LHS->getType();
  8840. QualType RHSType = RHS->getType();
  8841. if (LHSType->hasFloatingRepresentation() ||
  8842. (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
  8843. LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
  8844. S.inTemplateInstantiation())
  8845. return;
  8846. // Comparisons between two array types are ill-formed for operator<=>, so
  8847. // we shouldn't emit any additional warnings about it.
  8848. if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
  8849. return;
  8850. // For non-floating point types, check for self-comparisons of the form
  8851. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  8852. // often indicate logic errors in the program.
  8853. //
  8854. // NOTE: Don't warn about comparison expressions resulting from macro
  8855. // expansion. Also don't warn about comparisons which are only self
  8856. // comparisons within a template instantiation. The warnings should catch
  8857. // obvious cases in the definition of the template anyways. The idea is to
  8858. // warn when the typed comparison operator will always evaluate to the same
  8859. // result.
  8860. ValueDecl *DL = getCompareDecl(LHSStripped);
  8861. ValueDecl *DR = getCompareDecl(RHSStripped);
  8862. if (DL && DR && declaresSameEntity(DL, DR)) {
  8863. StringRef Result;
  8864. switch (Opc) {
  8865. case BO_EQ: case BO_LE: case BO_GE:
  8866. Result = "true";
  8867. break;
  8868. case BO_NE: case BO_LT: case BO_GT:
  8869. Result = "false";
  8870. break;
  8871. case BO_Cmp:
  8872. Result = "'std::strong_ordering::equal'";
  8873. break;
  8874. default:
  8875. break;
  8876. }
  8877. S.DiagRuntimeBehavior(Loc, nullptr,
  8878. S.PDiag(diag::warn_comparison_always)
  8879. << 0 /*self-comparison*/ << !Result.empty()
  8880. << Result);
  8881. } else if (DL && DR &&
  8882. DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
  8883. !DL->isWeak() && !DR->isWeak()) {
  8884. // What is it always going to evaluate to?
  8885. StringRef Result;
  8886. switch(Opc) {
  8887. case BO_EQ: // e.g. array1 == array2
  8888. Result = "false";
  8889. break;
  8890. case BO_NE: // e.g. array1 != array2
  8891. Result = "true";
  8892. break;
  8893. default: // e.g. array1 <= array2
  8894. // The best we can say is 'a constant'
  8895. break;
  8896. }
  8897. S.DiagRuntimeBehavior(Loc, nullptr,
  8898. S.PDiag(diag::warn_comparison_always)
  8899. << 1 /*array comparison*/
  8900. << !Result.empty() << Result);
  8901. }
  8902. if (isa<CastExpr>(LHSStripped))
  8903. LHSStripped = LHSStripped->IgnoreParenCasts();
  8904. if (isa<CastExpr>(RHSStripped))
  8905. RHSStripped = RHSStripped->IgnoreParenCasts();
  8906. // Warn about comparisons against a string constant (unless the other
  8907. // operand is null); the user probably wants strcmp.
  8908. Expr *LiteralString = nullptr;
  8909. Expr *LiteralStringStripped = nullptr;
  8910. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  8911. !RHSStripped->isNullPointerConstant(S.Context,
  8912. Expr::NPC_ValueDependentIsNull)) {
  8913. LiteralString = LHS;
  8914. LiteralStringStripped = LHSStripped;
  8915. } else if ((isa<StringLiteral>(RHSStripped) ||
  8916. isa<ObjCEncodeExpr>(RHSStripped)) &&
  8917. !LHSStripped->isNullPointerConstant(S.Context,
  8918. Expr::NPC_ValueDependentIsNull)) {
  8919. LiteralString = RHS;
  8920. LiteralStringStripped = RHSStripped;
  8921. }
  8922. if (LiteralString) {
  8923. S.DiagRuntimeBehavior(Loc, nullptr,
  8924. S.PDiag(diag::warn_stringcompare)
  8925. << isa<ObjCEncodeExpr>(LiteralStringStripped)
  8926. << LiteralString->getSourceRange());
  8927. }
  8928. }
  8929. static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
  8930. switch (CK) {
  8931. default: {
  8932. #ifndef NDEBUG
  8933. llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
  8934. << "\n";
  8935. #endif
  8936. llvm_unreachable("unhandled cast kind");
  8937. }
  8938. case CK_UserDefinedConversion:
  8939. return ICK_Identity;
  8940. case CK_LValueToRValue:
  8941. return ICK_Lvalue_To_Rvalue;
  8942. case CK_ArrayToPointerDecay:
  8943. return ICK_Array_To_Pointer;
  8944. case CK_FunctionToPointerDecay:
  8945. return ICK_Function_To_Pointer;
  8946. case CK_IntegralCast:
  8947. return ICK_Integral_Conversion;
  8948. case CK_FloatingCast:
  8949. return ICK_Floating_Conversion;
  8950. case CK_IntegralToFloating:
  8951. case CK_FloatingToIntegral:
  8952. return ICK_Floating_Integral;
  8953. case CK_IntegralComplexCast:
  8954. case CK_FloatingComplexCast:
  8955. case CK_FloatingComplexToIntegralComplex:
  8956. case CK_IntegralComplexToFloatingComplex:
  8957. return ICK_Complex_Conversion;
  8958. case CK_FloatingComplexToReal:
  8959. case CK_FloatingRealToComplex:
  8960. case CK_IntegralComplexToReal:
  8961. case CK_IntegralRealToComplex:
  8962. return ICK_Complex_Real;
  8963. }
  8964. }
  8965. static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
  8966. QualType FromType,
  8967. SourceLocation Loc) {
  8968. // Check for a narrowing implicit conversion.
  8969. StandardConversionSequence SCS;
  8970. SCS.setAsIdentityConversion();
  8971. SCS.setToType(0, FromType);
  8972. SCS.setToType(1, ToType);
  8973. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  8974. SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
  8975. APValue PreNarrowingValue;
  8976. QualType PreNarrowingType;
  8977. switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
  8978. PreNarrowingType,
  8979. /*IgnoreFloatToIntegralConversion*/ true)) {
  8980. case NK_Dependent_Narrowing:
  8981. // Implicit conversion to a narrower type, but the expression is
  8982. // value-dependent so we can't tell whether it's actually narrowing.
  8983. case NK_Not_Narrowing:
  8984. return false;
  8985. case NK_Constant_Narrowing:
  8986. // Implicit conversion to a narrower type, and the value is not a constant
  8987. // expression.
  8988. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  8989. << /*Constant*/ 1
  8990. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
  8991. return true;
  8992. case NK_Variable_Narrowing:
  8993. // Implicit conversion to a narrower type, and the value is not a constant
  8994. // expression.
  8995. case NK_Type_Narrowing:
  8996. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  8997. << /*Constant*/ 0 << FromType << ToType;
  8998. // TODO: It's not a constant expression, but what if the user intended it
  8999. // to be? Can we produce notes to help them figure out why it isn't?
  9000. return true;
  9001. }
  9002. llvm_unreachable("unhandled case in switch");
  9003. }
  9004. static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
  9005. ExprResult &LHS,
  9006. ExprResult &RHS,
  9007. SourceLocation Loc) {
  9008. using CCT = ComparisonCategoryType;
  9009. QualType LHSType = LHS.get()->getType();
  9010. QualType RHSType = RHS.get()->getType();
  9011. // Dig out the original argument type and expression before implicit casts
  9012. // were applied. These are the types/expressions we need to check the
  9013. // [expr.spaceship] requirements against.
  9014. ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
  9015. ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
  9016. QualType LHSStrippedType = LHSStripped.get()->getType();
  9017. QualType RHSStrippedType = RHSStripped.get()->getType();
  9018. // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
  9019. // other is not, the program is ill-formed.
  9020. if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
  9021. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  9022. return QualType();
  9023. }
  9024. int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
  9025. RHSStrippedType->isEnumeralType();
  9026. if (NumEnumArgs == 1) {
  9027. bool LHSIsEnum = LHSStrippedType->isEnumeralType();
  9028. QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
  9029. if (OtherTy->hasFloatingRepresentation()) {
  9030. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  9031. return QualType();
  9032. }
  9033. }
  9034. if (NumEnumArgs == 2) {
  9035. // C++2a [expr.spaceship]p5: If both operands have the same enumeration
  9036. // type E, the operator yields the result of converting the operands
  9037. // to the underlying type of E and applying <=> to the converted operands.
  9038. if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
  9039. S.InvalidOperands(Loc, LHS, RHS);
  9040. return QualType();
  9041. }
  9042. QualType IntType =
  9043. LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
  9044. assert(IntType->isArithmeticType());
  9045. // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
  9046. // promote the boolean type, and all other promotable integer types, to
  9047. // avoid this.
  9048. if (IntType->isPromotableIntegerType())
  9049. IntType = S.Context.getPromotedIntegerType(IntType);
  9050. LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
  9051. RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
  9052. LHSType = RHSType = IntType;
  9053. }
  9054. // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
  9055. // usual arithmetic conversions are applied to the operands.
  9056. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  9057. if (LHS.isInvalid() || RHS.isInvalid())
  9058. return QualType();
  9059. if (Type.isNull())
  9060. return S.InvalidOperands(Loc, LHS, RHS);
  9061. assert(Type->isArithmeticType() || Type->isEnumeralType());
  9062. bool HasNarrowing = checkThreeWayNarrowingConversion(
  9063. S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
  9064. HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
  9065. RHS.get()->getBeginLoc());
  9066. if (HasNarrowing)
  9067. return QualType();
  9068. assert(!Type.isNull() && "composite type for <=> has not been set");
  9069. auto TypeKind = [&]() {
  9070. if (const ComplexType *CT = Type->getAs<ComplexType>()) {
  9071. if (CT->getElementType()->hasFloatingRepresentation())
  9072. return CCT::WeakEquality;
  9073. return CCT::StrongEquality;
  9074. }
  9075. if (Type->isIntegralOrEnumerationType())
  9076. return CCT::StrongOrdering;
  9077. if (Type->hasFloatingRepresentation())
  9078. return CCT::PartialOrdering;
  9079. llvm_unreachable("other types are unimplemented");
  9080. }();
  9081. return S.CheckComparisonCategoryType(TypeKind, Loc);
  9082. }
  9083. static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
  9084. ExprResult &RHS,
  9085. SourceLocation Loc,
  9086. BinaryOperatorKind Opc) {
  9087. if (Opc == BO_Cmp)
  9088. return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
  9089. // C99 6.5.8p3 / C99 6.5.9p4
  9090. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  9091. if (LHS.isInvalid() || RHS.isInvalid())
  9092. return QualType();
  9093. if (Type.isNull())
  9094. return S.InvalidOperands(Loc, LHS, RHS);
  9095. assert(Type->isArithmeticType() || Type->isEnumeralType());
  9096. checkEnumComparison(S, Loc, LHS.get(), RHS.get());
  9097. if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
  9098. return S.InvalidOperands(Loc, LHS, RHS);
  9099. // Check for comparisons of floating point operands using != and ==.
  9100. if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
  9101. S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9102. // The result of comparisons is 'bool' in C++, 'int' in C.
  9103. return S.Context.getLogicalOperationType();
  9104. }
  9105. // C99 6.5.8, C++ [expr.rel]
  9106. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9107. SourceLocation Loc,
  9108. BinaryOperatorKind Opc) {
  9109. bool IsRelational = BinaryOperator::isRelationalOp(Opc);
  9110. bool IsThreeWay = Opc == BO_Cmp;
  9111. auto IsAnyPointerType = [](ExprResult E) {
  9112. QualType Ty = E.get()->getType();
  9113. return Ty->isPointerType() || Ty->isMemberPointerType();
  9114. };
  9115. // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
  9116. // type, array-to-pointer, ..., conversions are performed on both operands to
  9117. // bring them to their composite type.
  9118. // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
  9119. // any type-related checks.
  9120. if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
  9121. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  9122. if (LHS.isInvalid())
  9123. return QualType();
  9124. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  9125. if (RHS.isInvalid())
  9126. return QualType();
  9127. } else {
  9128. LHS = DefaultLvalueConversion(LHS.get());
  9129. if (LHS.isInvalid())
  9130. return QualType();
  9131. RHS = DefaultLvalueConversion(RHS.get());
  9132. if (RHS.isInvalid())
  9133. return QualType();
  9134. }
  9135. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
  9136. // Handle vector comparisons separately.
  9137. if (LHS.get()->getType()->isVectorType() ||
  9138. RHS.get()->getType()->isVectorType())
  9139. return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
  9140. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9141. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9142. QualType LHSType = LHS.get()->getType();
  9143. QualType RHSType = RHS.get()->getType();
  9144. if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
  9145. (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
  9146. return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
  9147. const Expr::NullPointerConstantKind LHSNullKind =
  9148. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  9149. const Expr::NullPointerConstantKind RHSNullKind =
  9150. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  9151. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  9152. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  9153. auto computeResultTy = [&]() {
  9154. if (Opc != BO_Cmp)
  9155. return Context.getLogicalOperationType();
  9156. assert(getLangOpts().CPlusPlus);
  9157. assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
  9158. QualType CompositeTy = LHS.get()->getType();
  9159. assert(!CompositeTy->isReferenceType());
  9160. auto buildResultTy = [&](ComparisonCategoryType Kind) {
  9161. return CheckComparisonCategoryType(Kind, Loc);
  9162. };
  9163. // C++2a [expr.spaceship]p7: If the composite pointer type is a function
  9164. // pointer type, a pointer-to-member type, or std::nullptr_t, the
  9165. // result is of type std::strong_equality
  9166. if (CompositeTy->isFunctionPointerType() ||
  9167. CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
  9168. // FIXME: consider making the function pointer case produce
  9169. // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
  9170. // and direction polls
  9171. return buildResultTy(ComparisonCategoryType::StrongEquality);
  9172. // C++2a [expr.spaceship]p8: If the composite pointer type is an object
  9173. // pointer type, p <=> q is of type std::strong_ordering.
  9174. if (CompositeTy->isPointerType()) {
  9175. // P0946R0: Comparisons between a null pointer constant and an object
  9176. // pointer result in std::strong_equality
  9177. if (LHSIsNull != RHSIsNull)
  9178. return buildResultTy(ComparisonCategoryType::StrongEquality);
  9179. return buildResultTy(ComparisonCategoryType::StrongOrdering);
  9180. }
  9181. // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
  9182. // TODO: Extend support for operator<=> to ObjC types.
  9183. return InvalidOperands(Loc, LHS, RHS);
  9184. };
  9185. if (!IsRelational && LHSIsNull != RHSIsNull) {
  9186. bool IsEquality = Opc == BO_EQ;
  9187. if (RHSIsNull)
  9188. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  9189. RHS.get()->getSourceRange());
  9190. else
  9191. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  9192. LHS.get()->getSourceRange());
  9193. }
  9194. if ((LHSType->isIntegerType() && !LHSIsNull) ||
  9195. (RHSType->isIntegerType() && !RHSIsNull)) {
  9196. // Skip normal pointer conversion checks in this case; we have better
  9197. // diagnostics for this below.
  9198. } else if (getLangOpts().CPlusPlus) {
  9199. // Equality comparison of a function pointer to a void pointer is invalid,
  9200. // but we allow it as an extension.
  9201. // FIXME: If we really want to allow this, should it be part of composite
  9202. // pointer type computation so it works in conditionals too?
  9203. if (!IsRelational &&
  9204. ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
  9205. (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
  9206. // This is a gcc extension compatibility comparison.
  9207. // In a SFINAE context, we treat this as a hard error to maintain
  9208. // conformance with the C++ standard.
  9209. diagnoseFunctionPointerToVoidComparison(
  9210. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  9211. if (isSFINAEContext())
  9212. return QualType();
  9213. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9214. return computeResultTy();
  9215. }
  9216. // C++ [expr.eq]p2:
  9217. // If at least one operand is a pointer [...] bring them to their
  9218. // composite pointer type.
  9219. // C++ [expr.spaceship]p6
  9220. // If at least one of the operands is of pointer type, [...] bring them
  9221. // to their composite pointer type.
  9222. // C++ [expr.rel]p2:
  9223. // If both operands are pointers, [...] bring them to their composite
  9224. // pointer type.
  9225. if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
  9226. (IsRelational ? 2 : 1) &&
  9227. (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
  9228. RHSType->isObjCObjectPointerType()))) {
  9229. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  9230. return QualType();
  9231. return computeResultTy();
  9232. }
  9233. } else if (LHSType->isPointerType() &&
  9234. RHSType->isPointerType()) { // C99 6.5.8p2
  9235. // All of the following pointer-related warnings are GCC extensions, except
  9236. // when handling null pointer constants.
  9237. QualType LCanPointeeTy =
  9238. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9239. QualType RCanPointeeTy =
  9240. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9241. // C99 6.5.9p2 and C99 6.5.8p2
  9242. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  9243. RCanPointeeTy.getUnqualifiedType())) {
  9244. // Valid unless a relational comparison of function pointers
  9245. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  9246. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  9247. << LHSType << RHSType << LHS.get()->getSourceRange()
  9248. << RHS.get()->getSourceRange();
  9249. }
  9250. } else if (!IsRelational &&
  9251. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  9252. // Valid unless comparison between non-null pointer and function pointer
  9253. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  9254. && !LHSIsNull && !RHSIsNull)
  9255. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  9256. /*isError*/false);
  9257. } else {
  9258. // Invalid
  9259. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  9260. }
  9261. if (LCanPointeeTy != RCanPointeeTy) {
  9262. // Treat NULL constant as a special case in OpenCL.
  9263. if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
  9264. const PointerType *LHSPtr = LHSType->getAs<PointerType>();
  9265. if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  9266. Diag(Loc,
  9267. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  9268. << LHSType << RHSType << 0 /* comparison */
  9269. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9270. }
  9271. }
  9272. LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
  9273. LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
  9274. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  9275. : CK_BitCast;
  9276. if (LHSIsNull && !RHSIsNull)
  9277. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  9278. else
  9279. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  9280. }
  9281. return computeResultTy();
  9282. }
  9283. if (getLangOpts().CPlusPlus) {
  9284. // C++ [expr.eq]p4:
  9285. // Two operands of type std::nullptr_t or one operand of type
  9286. // std::nullptr_t and the other a null pointer constant compare equal.
  9287. if (!IsRelational && LHSIsNull && RHSIsNull) {
  9288. if (LHSType->isNullPtrType()) {
  9289. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9290. return computeResultTy();
  9291. }
  9292. if (RHSType->isNullPtrType()) {
  9293. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9294. return computeResultTy();
  9295. }
  9296. }
  9297. // Comparison of Objective-C pointers and block pointers against nullptr_t.
  9298. // These aren't covered by the composite pointer type rules.
  9299. if (!IsRelational && RHSType->isNullPtrType() &&
  9300. (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
  9301. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9302. return computeResultTy();
  9303. }
  9304. if (!IsRelational && LHSType->isNullPtrType() &&
  9305. (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
  9306. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9307. return computeResultTy();
  9308. }
  9309. if (IsRelational &&
  9310. ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
  9311. (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
  9312. // HACK: Relational comparison of nullptr_t against a pointer type is
  9313. // invalid per DR583, but we allow it within std::less<> and friends,
  9314. // since otherwise common uses of it break.
  9315. // FIXME: Consider removing this hack once LWG fixes std::less<> and
  9316. // friends to have std::nullptr_t overload candidates.
  9317. DeclContext *DC = CurContext;
  9318. if (isa<FunctionDecl>(DC))
  9319. DC = DC->getParent();
  9320. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  9321. if (CTSD->isInStdNamespace() &&
  9322. llvm::StringSwitch<bool>(CTSD->getName())
  9323. .Cases("less", "less_equal", "greater", "greater_equal", true)
  9324. .Default(false)) {
  9325. if (RHSType->isNullPtrType())
  9326. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9327. else
  9328. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9329. return computeResultTy();
  9330. }
  9331. }
  9332. }
  9333. // C++ [expr.eq]p2:
  9334. // If at least one operand is a pointer to member, [...] bring them to
  9335. // their composite pointer type.
  9336. if (!IsRelational &&
  9337. (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
  9338. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  9339. return QualType();
  9340. else
  9341. return computeResultTy();
  9342. }
  9343. }
  9344. // Handle block pointer types.
  9345. if (!IsRelational && LHSType->isBlockPointerType() &&
  9346. RHSType->isBlockPointerType()) {
  9347. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  9348. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  9349. if (!LHSIsNull && !RHSIsNull &&
  9350. !Context.typesAreCompatible(lpointee, rpointee)) {
  9351. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9352. << LHSType << RHSType << LHS.get()->getSourceRange()
  9353. << RHS.get()->getSourceRange();
  9354. }
  9355. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9356. return computeResultTy();
  9357. }
  9358. // Allow block pointers to be compared with null pointer constants.
  9359. if (!IsRelational
  9360. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  9361. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  9362. if (!LHSIsNull && !RHSIsNull) {
  9363. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  9364. ->getPointeeType()->isVoidType())
  9365. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  9366. ->getPointeeType()->isVoidType())))
  9367. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9368. << LHSType << RHSType << LHS.get()->getSourceRange()
  9369. << RHS.get()->getSourceRange();
  9370. }
  9371. if (LHSIsNull && !RHSIsNull)
  9372. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9373. RHSType->isPointerType() ? CK_BitCast
  9374. : CK_AnyPointerToBlockPointerCast);
  9375. else
  9376. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9377. LHSType->isPointerType() ? CK_BitCast
  9378. : CK_AnyPointerToBlockPointerCast);
  9379. return computeResultTy();
  9380. }
  9381. if (LHSType->isObjCObjectPointerType() ||
  9382. RHSType->isObjCObjectPointerType()) {
  9383. const PointerType *LPT = LHSType->getAs<PointerType>();
  9384. const PointerType *RPT = RHSType->getAs<PointerType>();
  9385. if (LPT || RPT) {
  9386. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  9387. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  9388. if (!LPtrToVoid && !RPtrToVoid &&
  9389. !Context.typesAreCompatible(LHSType, RHSType)) {
  9390. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9391. /*isError*/false);
  9392. }
  9393. if (LHSIsNull && !RHSIsNull) {
  9394. Expr *E = LHS.get();
  9395. if (getLangOpts().ObjCAutoRefCount)
  9396. CheckObjCConversion(SourceRange(), RHSType, E,
  9397. CCK_ImplicitConversion);
  9398. LHS = ImpCastExprToType(E, RHSType,
  9399. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9400. }
  9401. else {
  9402. Expr *E = RHS.get();
  9403. if (getLangOpts().ObjCAutoRefCount)
  9404. CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
  9405. /*Diagnose=*/true,
  9406. /*DiagnoseCFAudited=*/false, Opc);
  9407. RHS = ImpCastExprToType(E, LHSType,
  9408. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9409. }
  9410. return computeResultTy();
  9411. }
  9412. if (LHSType->isObjCObjectPointerType() &&
  9413. RHSType->isObjCObjectPointerType()) {
  9414. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  9415. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9416. /*isError*/false);
  9417. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  9418. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  9419. if (LHSIsNull && !RHSIsNull)
  9420. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  9421. else
  9422. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9423. return computeResultTy();
  9424. }
  9425. if (!IsRelational && LHSType->isBlockPointerType() &&
  9426. RHSType->isBlockCompatibleObjCPointerType(Context)) {
  9427. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9428. CK_BlockPointerToObjCPointerCast);
  9429. return computeResultTy();
  9430. } else if (!IsRelational &&
  9431. LHSType->isBlockCompatibleObjCPointerType(Context) &&
  9432. RHSType->isBlockPointerType()) {
  9433. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9434. CK_BlockPointerToObjCPointerCast);
  9435. return computeResultTy();
  9436. }
  9437. }
  9438. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  9439. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  9440. unsigned DiagID = 0;
  9441. bool isError = false;
  9442. if (LangOpts.DebuggerSupport) {
  9443. // Under a debugger, allow the comparison of pointers to integers,
  9444. // since users tend to want to compare addresses.
  9445. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  9446. (RHSIsNull && RHSType->isIntegerType())) {
  9447. if (IsRelational) {
  9448. isError = getLangOpts().CPlusPlus;
  9449. DiagID =
  9450. isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
  9451. : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  9452. }
  9453. } else if (getLangOpts().CPlusPlus) {
  9454. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  9455. isError = true;
  9456. } else if (IsRelational)
  9457. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  9458. else
  9459. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  9460. if (DiagID) {
  9461. Diag(Loc, DiagID)
  9462. << LHSType << RHSType << LHS.get()->getSourceRange()
  9463. << RHS.get()->getSourceRange();
  9464. if (isError)
  9465. return QualType();
  9466. }
  9467. if (LHSType->isIntegerType())
  9468. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9469. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9470. else
  9471. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9472. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9473. return computeResultTy();
  9474. }
  9475. // Handle block pointers.
  9476. if (!IsRelational && RHSIsNull
  9477. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  9478. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9479. return computeResultTy();
  9480. }
  9481. if (!IsRelational && LHSIsNull
  9482. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  9483. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9484. return computeResultTy();
  9485. }
  9486. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
  9487. if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
  9488. return computeResultTy();
  9489. }
  9490. if (LHSType->isQueueT() && RHSType->isQueueT()) {
  9491. return computeResultTy();
  9492. }
  9493. if (LHSIsNull && RHSType->isQueueT()) {
  9494. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9495. return computeResultTy();
  9496. }
  9497. if (LHSType->isQueueT() && RHSIsNull) {
  9498. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9499. return computeResultTy();
  9500. }
  9501. }
  9502. return InvalidOperands(Loc, LHS, RHS);
  9503. }
  9504. // Return a signed ext_vector_type that is of identical size and number of
  9505. // elements. For floating point vectors, return an integer type of identical
  9506. // size and number of elements. In the non ext_vector_type case, search from
  9507. // the largest type to the smallest type to avoid cases where long long == long,
  9508. // where long gets picked over long long.
  9509. QualType Sema::GetSignedVectorType(QualType V) {
  9510. const VectorType *VTy = V->getAs<VectorType>();
  9511. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  9512. if (isa<ExtVectorType>(VTy)) {
  9513. if (TypeSize == Context.getTypeSize(Context.CharTy))
  9514. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  9515. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9516. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  9517. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9518. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  9519. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9520. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  9521. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  9522. "Unhandled vector element size in vector compare");
  9523. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  9524. }
  9525. if (TypeSize == Context.getTypeSize(Context.LongLongTy))
  9526. return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
  9527. VectorType::GenericVector);
  9528. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9529. return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
  9530. VectorType::GenericVector);
  9531. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9532. return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
  9533. VectorType::GenericVector);
  9534. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9535. return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
  9536. VectorType::GenericVector);
  9537. assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
  9538. "Unhandled vector element size in vector compare");
  9539. return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
  9540. VectorType::GenericVector);
  9541. }
  9542. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  9543. /// operates on extended vector types. Instead of producing an IntTy result,
  9544. /// like a scalar comparison, a vector comparison produces a vector of integer
  9545. /// types.
  9546. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9547. SourceLocation Loc,
  9548. BinaryOperatorKind Opc) {
  9549. // Check to make sure we're operating on vectors of the same type and width,
  9550. // Allowing one side to be a scalar of element type.
  9551. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  9552. /*AllowBothBool*/true,
  9553. /*AllowBoolConversions*/getLangOpts().ZVector);
  9554. if (vType.isNull())
  9555. return vType;
  9556. QualType LHSType = LHS.get()->getType();
  9557. // If AltiVec, the comparison results in a numeric type, i.e.
  9558. // bool for C++, int for C
  9559. if (getLangOpts().AltiVec &&
  9560. vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  9561. return Context.getLogicalOperationType();
  9562. // For non-floating point types, check for self-comparisons of the form
  9563. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  9564. // often indicate logic errors in the program.
  9565. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9566. // Check for comparisons of floating point operands using != and ==.
  9567. if (BinaryOperator::isEqualityOp(Opc) &&
  9568. LHSType->hasFloatingRepresentation()) {
  9569. assert(RHS.get()->getType()->hasFloatingRepresentation());
  9570. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9571. }
  9572. // Return a signed type for the vector.
  9573. return GetSignedVectorType(vType);
  9574. }
  9575. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9576. SourceLocation Loc) {
  9577. // Ensure that either both operands are of the same vector type, or
  9578. // one operand is of a vector type and the other is of its element type.
  9579. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  9580. /*AllowBothBool*/true,
  9581. /*AllowBoolConversions*/false);
  9582. if (vType.isNull())
  9583. return InvalidOperands(Loc, LHS, RHS);
  9584. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  9585. !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
  9586. return InvalidOperands(Loc, LHS, RHS);
  9587. // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
  9588. // usage of the logical operators && and || with vectors in C. This
  9589. // check could be notionally dropped.
  9590. if (!getLangOpts().CPlusPlus &&
  9591. !(isa<ExtVectorType>(vType->getAs<VectorType>())))
  9592. return InvalidLogicalVectorOperands(Loc, LHS, RHS);
  9593. return GetSignedVectorType(LHS.get()->getType());
  9594. }
  9595. inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
  9596. SourceLocation Loc,
  9597. BinaryOperatorKind Opc) {
  9598. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  9599. bool IsCompAssign =
  9600. Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
  9601. if (LHS.get()->getType()->isVectorType() ||
  9602. RHS.get()->getType()->isVectorType()) {
  9603. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  9604. RHS.get()->getType()->hasIntegerRepresentation())
  9605. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9606. /*AllowBothBool*/true,
  9607. /*AllowBoolConversions*/getLangOpts().ZVector);
  9608. return InvalidOperands(Loc, LHS, RHS);
  9609. }
  9610. if (Opc == BO_And)
  9611. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9612. ExprResult LHSResult = LHS, RHSResult = RHS;
  9613. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  9614. IsCompAssign);
  9615. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  9616. return QualType();
  9617. LHS = LHSResult.get();
  9618. RHS = RHSResult.get();
  9619. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  9620. return compType;
  9621. return InvalidOperands(Loc, LHS, RHS);
  9622. }
  9623. // C99 6.5.[13,14]
  9624. inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9625. SourceLocation Loc,
  9626. BinaryOperatorKind Opc) {
  9627. // Check vector operands differently.
  9628. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  9629. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  9630. // Diagnose cases where the user write a logical and/or but probably meant a
  9631. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  9632. // is a constant.
  9633. if (LHS.get()->getType()->isIntegerType() &&
  9634. !LHS.get()->getType()->isBooleanType() &&
  9635. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  9636. // Don't warn in macros or template instantiations.
  9637. !Loc.isMacroID() && !inTemplateInstantiation()) {
  9638. // If the RHS can be constant folded, and if it constant folds to something
  9639. // that isn't 0 or 1 (which indicate a potential logical operation that
  9640. // happened to fold to true/false) then warn.
  9641. // Parens on the RHS are ignored.
  9642. Expr::EvalResult EVResult;
  9643. if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
  9644. llvm::APSInt Result = EVResult.Val.getInt();
  9645. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  9646. !RHS.get()->getExprLoc().isMacroID()) ||
  9647. (Result != 0 && Result != 1)) {
  9648. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  9649. << RHS.get()->getSourceRange()
  9650. << (Opc == BO_LAnd ? "&&" : "||");
  9651. // Suggest replacing the logical operator with the bitwise version
  9652. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  9653. << (Opc == BO_LAnd ? "&" : "|")
  9654. << FixItHint::CreateReplacement(SourceRange(
  9655. Loc, getLocForEndOfToken(Loc)),
  9656. Opc == BO_LAnd ? "&" : "|");
  9657. if (Opc == BO_LAnd)
  9658. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  9659. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  9660. << FixItHint::CreateRemoval(
  9661. SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
  9662. RHS.get()->getEndLoc()));
  9663. }
  9664. }
  9665. }
  9666. if (!Context.getLangOpts().CPlusPlus) {
  9667. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  9668. // not operate on the built-in scalar and vector float types.
  9669. if (Context.getLangOpts().OpenCL &&
  9670. Context.getLangOpts().OpenCLVersion < 120) {
  9671. if (LHS.get()->getType()->isFloatingType() ||
  9672. RHS.get()->getType()->isFloatingType())
  9673. return InvalidOperands(Loc, LHS, RHS);
  9674. }
  9675. LHS = UsualUnaryConversions(LHS.get());
  9676. if (LHS.isInvalid())
  9677. return QualType();
  9678. RHS = UsualUnaryConversions(RHS.get());
  9679. if (RHS.isInvalid())
  9680. return QualType();
  9681. if (!LHS.get()->getType()->isScalarType() ||
  9682. !RHS.get()->getType()->isScalarType())
  9683. return InvalidOperands(Loc, LHS, RHS);
  9684. return Context.IntTy;
  9685. }
  9686. // The following is safe because we only use this method for
  9687. // non-overloadable operands.
  9688. // C++ [expr.log.and]p1
  9689. // C++ [expr.log.or]p1
  9690. // The operands are both contextually converted to type bool.
  9691. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  9692. if (LHSRes.isInvalid())
  9693. return InvalidOperands(Loc, LHS, RHS);
  9694. LHS = LHSRes;
  9695. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  9696. if (RHSRes.isInvalid())
  9697. return InvalidOperands(Loc, LHS, RHS);
  9698. RHS = RHSRes;
  9699. // C++ [expr.log.and]p2
  9700. // C++ [expr.log.or]p2
  9701. // The result is a bool.
  9702. return Context.BoolTy;
  9703. }
  9704. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  9705. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  9706. if (!ME) return false;
  9707. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  9708. ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
  9709. ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
  9710. if (!Base) return false;
  9711. return Base->getMethodDecl() != nullptr;
  9712. }
  9713. /// Is the given expression (which must be 'const') a reference to a
  9714. /// variable which was originally non-const, but which has become
  9715. /// 'const' due to being captured within a block?
  9716. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  9717. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  9718. assert(E->isLValue() && E->getType().isConstQualified());
  9719. E = E->IgnoreParens();
  9720. // Must be a reference to a declaration from an enclosing scope.
  9721. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  9722. if (!DRE) return NCCK_None;
  9723. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  9724. // The declaration must be a variable which is not declared 'const'.
  9725. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  9726. if (!var) return NCCK_None;
  9727. if (var->getType().isConstQualified()) return NCCK_None;
  9728. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  9729. // Decide whether the first capture was for a block or a lambda.
  9730. DeclContext *DC = S.CurContext, *Prev = nullptr;
  9731. // Decide whether the first capture was for a block or a lambda.
  9732. while (DC) {
  9733. // For init-capture, it is possible that the variable belongs to the
  9734. // template pattern of the current context.
  9735. if (auto *FD = dyn_cast<FunctionDecl>(DC))
  9736. if (var->isInitCapture() &&
  9737. FD->getTemplateInstantiationPattern() == var->getDeclContext())
  9738. break;
  9739. if (DC == var->getDeclContext())
  9740. break;
  9741. Prev = DC;
  9742. DC = DC->getParent();
  9743. }
  9744. // Unless we have an init-capture, we've gone one step too far.
  9745. if (!var->isInitCapture())
  9746. DC = Prev;
  9747. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  9748. }
  9749. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  9750. Ty = Ty.getNonReferenceType();
  9751. if (IsDereference && Ty->isPointerType())
  9752. Ty = Ty->getPointeeType();
  9753. return !Ty.isConstQualified();
  9754. }
  9755. // Update err_typecheck_assign_const and note_typecheck_assign_const
  9756. // when this enum is changed.
  9757. enum {
  9758. ConstFunction,
  9759. ConstVariable,
  9760. ConstMember,
  9761. ConstMethod,
  9762. NestedConstMember,
  9763. ConstUnknown, // Keep as last element
  9764. };
  9765. /// Emit the "read-only variable not assignable" error and print notes to give
  9766. /// more information about why the variable is not assignable, such as pointing
  9767. /// to the declaration of a const variable, showing that a method is const, or
  9768. /// that the function is returning a const reference.
  9769. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  9770. SourceLocation Loc) {
  9771. SourceRange ExprRange = E->getSourceRange();
  9772. // Only emit one error on the first const found. All other consts will emit
  9773. // a note to the error.
  9774. bool DiagnosticEmitted = false;
  9775. // Track if the current expression is the result of a dereference, and if the
  9776. // next checked expression is the result of a dereference.
  9777. bool IsDereference = false;
  9778. bool NextIsDereference = false;
  9779. // Loop to process MemberExpr chains.
  9780. while (true) {
  9781. IsDereference = NextIsDereference;
  9782. E = E->IgnoreImplicit()->IgnoreParenImpCasts();
  9783. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  9784. NextIsDereference = ME->isArrow();
  9785. const ValueDecl *VD = ME->getMemberDecl();
  9786. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  9787. // Mutable fields can be modified even if the class is const.
  9788. if (Field->isMutable()) {
  9789. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  9790. break;
  9791. }
  9792. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  9793. if (!DiagnosticEmitted) {
  9794. S.Diag(Loc, diag::err_typecheck_assign_const)
  9795. << ExprRange << ConstMember << false /*static*/ << Field
  9796. << Field->getType();
  9797. DiagnosticEmitted = true;
  9798. }
  9799. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9800. << ConstMember << false /*static*/ << Field << Field->getType()
  9801. << Field->getSourceRange();
  9802. }
  9803. E = ME->getBase();
  9804. continue;
  9805. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  9806. if (VDecl->getType().isConstQualified()) {
  9807. if (!DiagnosticEmitted) {
  9808. S.Diag(Loc, diag::err_typecheck_assign_const)
  9809. << ExprRange << ConstMember << true /*static*/ << VDecl
  9810. << VDecl->getType();
  9811. DiagnosticEmitted = true;
  9812. }
  9813. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9814. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  9815. << VDecl->getSourceRange();
  9816. }
  9817. // Static fields do not inherit constness from parents.
  9818. break;
  9819. }
  9820. break; // End MemberExpr
  9821. } else if (const ArraySubscriptExpr *ASE =
  9822. dyn_cast<ArraySubscriptExpr>(E)) {
  9823. E = ASE->getBase()->IgnoreParenImpCasts();
  9824. continue;
  9825. } else if (const ExtVectorElementExpr *EVE =
  9826. dyn_cast<ExtVectorElementExpr>(E)) {
  9827. E = EVE->getBase()->IgnoreParenImpCasts();
  9828. continue;
  9829. }
  9830. break;
  9831. }
  9832. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  9833. // Function calls
  9834. const FunctionDecl *FD = CE->getDirectCallee();
  9835. if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  9836. if (!DiagnosticEmitted) {
  9837. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  9838. << ConstFunction << FD;
  9839. DiagnosticEmitted = true;
  9840. }
  9841. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  9842. diag::note_typecheck_assign_const)
  9843. << ConstFunction << FD << FD->getReturnType()
  9844. << FD->getReturnTypeSourceRange();
  9845. }
  9846. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9847. // Point to variable declaration.
  9848. if (const ValueDecl *VD = DRE->getDecl()) {
  9849. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  9850. if (!DiagnosticEmitted) {
  9851. S.Diag(Loc, diag::err_typecheck_assign_const)
  9852. << ExprRange << ConstVariable << VD << VD->getType();
  9853. DiagnosticEmitted = true;
  9854. }
  9855. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9856. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  9857. }
  9858. }
  9859. } else if (isa<CXXThisExpr>(E)) {
  9860. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  9861. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  9862. if (MD->isConst()) {
  9863. if (!DiagnosticEmitted) {
  9864. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  9865. << ConstMethod << MD;
  9866. DiagnosticEmitted = true;
  9867. }
  9868. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  9869. << ConstMethod << MD << MD->getSourceRange();
  9870. }
  9871. }
  9872. }
  9873. }
  9874. if (DiagnosticEmitted)
  9875. return;
  9876. // Can't determine a more specific message, so display the generic error.
  9877. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  9878. }
  9879. enum OriginalExprKind {
  9880. OEK_Variable,
  9881. OEK_Member,
  9882. OEK_LValue
  9883. };
  9884. static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
  9885. const RecordType *Ty,
  9886. SourceLocation Loc, SourceRange Range,
  9887. OriginalExprKind OEK,
  9888. bool &DiagnosticEmitted) {
  9889. std::vector<const RecordType *> RecordTypeList;
  9890. RecordTypeList.push_back(Ty);
  9891. unsigned NextToCheckIndex = 0;
  9892. // We walk the record hierarchy breadth-first to ensure that we print
  9893. // diagnostics in field nesting order.
  9894. while (RecordTypeList.size() > NextToCheckIndex) {
  9895. bool IsNested = NextToCheckIndex > 0;
  9896. for (const FieldDecl *Field :
  9897. RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
  9898. // First, check every field for constness.
  9899. QualType FieldTy = Field->getType();
  9900. if (FieldTy.isConstQualified()) {
  9901. if (!DiagnosticEmitted) {
  9902. S.Diag(Loc, diag::err_typecheck_assign_const)
  9903. << Range << NestedConstMember << OEK << VD
  9904. << IsNested << Field;
  9905. DiagnosticEmitted = true;
  9906. }
  9907. S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
  9908. << NestedConstMember << IsNested << Field
  9909. << FieldTy << Field->getSourceRange();
  9910. }
  9911. // Then we append it to the list to check next in order.
  9912. FieldTy = FieldTy.getCanonicalType();
  9913. if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
  9914. if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
  9915. RecordTypeList.push_back(FieldRecTy);
  9916. }
  9917. }
  9918. ++NextToCheckIndex;
  9919. }
  9920. }
  9921. /// Emit an error for the case where a record we are trying to assign to has a
  9922. /// const-qualified field somewhere in its hierarchy.
  9923. static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
  9924. SourceLocation Loc) {
  9925. QualType Ty = E->getType();
  9926. assert(Ty->isRecordType() && "lvalue was not record?");
  9927. SourceRange Range = E->getSourceRange();
  9928. const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
  9929. bool DiagEmitted = false;
  9930. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  9931. DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
  9932. Range, OEK_Member, DiagEmitted);
  9933. else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  9934. DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
  9935. Range, OEK_Variable, DiagEmitted);
  9936. else
  9937. DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
  9938. Range, OEK_LValue, DiagEmitted);
  9939. if (!DiagEmitted)
  9940. DiagnoseConstAssignment(S, E, Loc);
  9941. }
  9942. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  9943. /// emit an error and return true. If so, return false.
  9944. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  9945. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  9946. S.CheckShadowingDeclModification(E, Loc);
  9947. SourceLocation OrigLoc = Loc;
  9948. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  9949. &Loc);
  9950. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  9951. IsLV = Expr::MLV_InvalidMessageExpression;
  9952. if (IsLV == Expr::MLV_Valid)
  9953. return false;
  9954. unsigned DiagID = 0;
  9955. bool NeedType = false;
  9956. switch (IsLV) { // C99 6.5.16p2
  9957. case Expr::MLV_ConstQualified:
  9958. // Use a specialized diagnostic when we're assigning to an object
  9959. // from an enclosing function or block.
  9960. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  9961. if (NCCK == NCCK_Block)
  9962. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  9963. else
  9964. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  9965. break;
  9966. }
  9967. // In ARC, use some specialized diagnostics for occasions where we
  9968. // infer 'const'. These are always pseudo-strong variables.
  9969. if (S.getLangOpts().ObjCAutoRefCount) {
  9970. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  9971. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  9972. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  9973. // Use the normal diagnostic if it's pseudo-__strong but the
  9974. // user actually wrote 'const'.
  9975. if (var->isARCPseudoStrong() &&
  9976. (!var->getTypeSourceInfo() ||
  9977. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  9978. // There are three pseudo-strong cases:
  9979. // - self
  9980. ObjCMethodDecl *method = S.getCurMethodDecl();
  9981. if (method && var == method->getSelfDecl()) {
  9982. DiagID = method->isClassMethod()
  9983. ? diag::err_typecheck_arc_assign_self_class_method
  9984. : diag::err_typecheck_arc_assign_self;
  9985. // - Objective-C externally_retained attribute.
  9986. } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
  9987. isa<ParmVarDecl>(var)) {
  9988. DiagID = diag::err_typecheck_arc_assign_externally_retained;
  9989. // - fast enumeration variables
  9990. } else {
  9991. DiagID = diag::err_typecheck_arr_assign_enumeration;
  9992. }
  9993. SourceRange Assign;
  9994. if (Loc != OrigLoc)
  9995. Assign = SourceRange(OrigLoc, OrigLoc);
  9996. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  9997. // We need to preserve the AST regardless, so migration tool
  9998. // can do its job.
  9999. return false;
  10000. }
  10001. }
  10002. }
  10003. // If none of the special cases above are triggered, then this is a
  10004. // simple const assignment.
  10005. if (DiagID == 0) {
  10006. DiagnoseConstAssignment(S, E, Loc);
  10007. return true;
  10008. }
  10009. break;
  10010. case Expr::MLV_ConstAddrSpace:
  10011. DiagnoseConstAssignment(S, E, Loc);
  10012. return true;
  10013. case Expr::MLV_ConstQualifiedField:
  10014. DiagnoseRecursiveConstFields(S, E, Loc);
  10015. return true;
  10016. case Expr::MLV_ArrayType:
  10017. case Expr::MLV_ArrayTemporary:
  10018. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  10019. NeedType = true;
  10020. break;
  10021. case Expr::MLV_NotObjectType:
  10022. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  10023. NeedType = true;
  10024. break;
  10025. case Expr::MLV_LValueCast:
  10026. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  10027. break;
  10028. case Expr::MLV_Valid:
  10029. llvm_unreachable("did not take early return for MLV_Valid");
  10030. case Expr::MLV_InvalidExpression:
  10031. case Expr::MLV_MemberFunction:
  10032. case Expr::MLV_ClassTemporary:
  10033. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  10034. break;
  10035. case Expr::MLV_IncompleteType:
  10036. case Expr::MLV_IncompleteVoidType:
  10037. return S.RequireCompleteType(Loc, E->getType(),
  10038. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  10039. case Expr::MLV_DuplicateVectorComponents:
  10040. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  10041. break;
  10042. case Expr::MLV_NoSetterProperty:
  10043. llvm_unreachable("readonly properties should be processed differently");
  10044. case Expr::MLV_InvalidMessageExpression:
  10045. DiagID = diag::err_readonly_message_assignment;
  10046. break;
  10047. case Expr::MLV_SubObjCPropertySetting:
  10048. DiagID = diag::err_no_subobject_property_setting;
  10049. break;
  10050. }
  10051. SourceRange Assign;
  10052. if (Loc != OrigLoc)
  10053. Assign = SourceRange(OrigLoc, OrigLoc);
  10054. if (NeedType)
  10055. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  10056. else
  10057. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  10058. return true;
  10059. }
  10060. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  10061. SourceLocation Loc,
  10062. Sema &Sema) {
  10063. if (Sema.inTemplateInstantiation())
  10064. return;
  10065. if (Sema.isUnevaluatedContext())
  10066. return;
  10067. if (Loc.isInvalid() || Loc.isMacroID())
  10068. return;
  10069. if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
  10070. return;
  10071. // C / C++ fields
  10072. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  10073. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  10074. if (ML && MR) {
  10075. if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
  10076. return;
  10077. const ValueDecl *LHSDecl =
  10078. cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
  10079. const ValueDecl *RHSDecl =
  10080. cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
  10081. if (LHSDecl != RHSDecl)
  10082. return;
  10083. if (LHSDecl->getType().isVolatileQualified())
  10084. return;
  10085. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  10086. if (RefTy->getPointeeType().isVolatileQualified())
  10087. return;
  10088. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  10089. }
  10090. // Objective-C instance variables
  10091. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  10092. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  10093. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  10094. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  10095. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  10096. if (RL && RR && RL->getDecl() == RR->getDecl())
  10097. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  10098. }
  10099. }
  10100. // C99 6.5.16.1
  10101. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  10102. SourceLocation Loc,
  10103. QualType CompoundType) {
  10104. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  10105. // Verify that LHS is a modifiable lvalue, and emit error if not.
  10106. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  10107. return QualType();
  10108. QualType LHSType = LHSExpr->getType();
  10109. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  10110. CompoundType;
  10111. // OpenCL v1.2 s6.1.1.1 p2:
  10112. // The half data type can only be used to declare a pointer to a buffer that
  10113. // contains half values
  10114. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  10115. LHSType->isHalfType()) {
  10116. Diag(Loc, diag::err_opencl_half_load_store) << 1
  10117. << LHSType.getUnqualifiedType();
  10118. return QualType();
  10119. }
  10120. AssignConvertType ConvTy;
  10121. if (CompoundType.isNull()) {
  10122. Expr *RHSCheck = RHS.get();
  10123. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  10124. QualType LHSTy(LHSType);
  10125. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  10126. if (RHS.isInvalid())
  10127. return QualType();
  10128. // Special case of NSObject attributes on c-style pointer types.
  10129. if (ConvTy == IncompatiblePointer &&
  10130. ((Context.isObjCNSObjectType(LHSType) &&
  10131. RHSType->isObjCObjectPointerType()) ||
  10132. (Context.isObjCNSObjectType(RHSType) &&
  10133. LHSType->isObjCObjectPointerType())))
  10134. ConvTy = Compatible;
  10135. if (ConvTy == Compatible &&
  10136. LHSType->isObjCObjectType())
  10137. Diag(Loc, diag::err_objc_object_assignment)
  10138. << LHSType;
  10139. // If the RHS is a unary plus or minus, check to see if they = and + are
  10140. // right next to each other. If so, the user may have typo'd "x =+ 4"
  10141. // instead of "x += 4".
  10142. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  10143. RHSCheck = ICE->getSubExpr();
  10144. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  10145. if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
  10146. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  10147. // Only if the two operators are exactly adjacent.
  10148. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  10149. // And there is a space or other character before the subexpr of the
  10150. // unary +/-. We don't want to warn on "x=-1".
  10151. Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
  10152. UO->getSubExpr()->getBeginLoc().isFileID()) {
  10153. Diag(Loc, diag::warn_not_compound_assign)
  10154. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  10155. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  10156. }
  10157. }
  10158. if (ConvTy == Compatible) {
  10159. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  10160. // Warn about retain cycles where a block captures the LHS, but
  10161. // not if the LHS is a simple variable into which the block is
  10162. // being stored...unless that variable can be captured by reference!
  10163. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  10164. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  10165. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  10166. checkRetainCycles(LHSExpr, RHS.get());
  10167. }
  10168. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  10169. LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
  10170. // It is safe to assign a weak reference into a strong variable.
  10171. // Although this code can still have problems:
  10172. // id x = self.weakProp;
  10173. // id y = self.weakProp;
  10174. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  10175. // paths through the function. This should be revisited if
  10176. // -Wrepeated-use-of-weak is made flow-sensitive.
  10177. // For ObjCWeak only, we do not warn if the assign is to a non-weak
  10178. // variable, which will be valid for the current autorelease scope.
  10179. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  10180. RHS.get()->getBeginLoc()))
  10181. getCurFunction()->markSafeWeakUse(RHS.get());
  10182. } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
  10183. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  10184. }
  10185. }
  10186. } else {
  10187. // Compound assignment "x += y"
  10188. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  10189. }
  10190. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  10191. RHS.get(), AA_Assigning))
  10192. return QualType();
  10193. CheckForNullPointerDereference(*this, LHSExpr);
  10194. // C99 6.5.16p3: The type of an assignment expression is the type of the
  10195. // left operand unless the left operand has qualified type, in which case
  10196. // it is the unqualified version of the type of the left operand.
  10197. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  10198. // is converted to the type of the assignment expression (above).
  10199. // C++ 5.17p1: the type of the assignment expression is that of its left
  10200. // operand.
  10201. return (getLangOpts().CPlusPlus
  10202. ? LHSType : LHSType.getUnqualifiedType());
  10203. }
  10204. // Only ignore explicit casts to void.
  10205. static bool IgnoreCommaOperand(const Expr *E) {
  10206. E = E->IgnoreParens();
  10207. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  10208. if (CE->getCastKind() == CK_ToVoid) {
  10209. return true;
  10210. }
  10211. // static_cast<void> on a dependent type will not show up as CK_ToVoid.
  10212. if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
  10213. CE->getSubExpr()->getType()->isDependentType()) {
  10214. return true;
  10215. }
  10216. }
  10217. return false;
  10218. }
  10219. // Look for instances where it is likely the comma operator is confused with
  10220. // another operator. There is a whitelist of acceptable expressions for the
  10221. // left hand side of the comma operator, otherwise emit a warning.
  10222. void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
  10223. // No warnings in macros
  10224. if (Loc.isMacroID())
  10225. return;
  10226. // Don't warn in template instantiations.
  10227. if (inTemplateInstantiation())
  10228. return;
  10229. // Scope isn't fine-grained enough to whitelist the specific cases, so
  10230. // instead, skip more than needed, then call back into here with the
  10231. // CommaVisitor in SemaStmt.cpp.
  10232. // The whitelisted locations are the initialization and increment portions
  10233. // of a for loop. The additional checks are on the condition of
  10234. // if statements, do/while loops, and for loops.
  10235. // Differences in scope flags for C89 mode requires the extra logic.
  10236. const unsigned ForIncrementFlags =
  10237. getLangOpts().C99 || getLangOpts().CPlusPlus
  10238. ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
  10239. : Scope::ContinueScope | Scope::BreakScope;
  10240. const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
  10241. const unsigned ScopeFlags = getCurScope()->getFlags();
  10242. if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
  10243. (ScopeFlags & ForInitFlags) == ForInitFlags)
  10244. return;
  10245. // If there are multiple comma operators used together, get the RHS of the
  10246. // of the comma operator as the LHS.
  10247. while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
  10248. if (BO->getOpcode() != BO_Comma)
  10249. break;
  10250. LHS = BO->getRHS();
  10251. }
  10252. // Only allow some expressions on LHS to not warn.
  10253. if (IgnoreCommaOperand(LHS))
  10254. return;
  10255. Diag(Loc, diag::warn_comma_operator);
  10256. Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
  10257. << LHS->getSourceRange()
  10258. << FixItHint::CreateInsertion(LHS->getBeginLoc(),
  10259. LangOpts.CPlusPlus ? "static_cast<void>("
  10260. : "(void)(")
  10261. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
  10262. ")");
  10263. }
  10264. // C99 6.5.17
  10265. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  10266. SourceLocation Loc) {
  10267. LHS = S.CheckPlaceholderExpr(LHS.get());
  10268. RHS = S.CheckPlaceholderExpr(RHS.get());
  10269. if (LHS.isInvalid() || RHS.isInvalid())
  10270. return QualType();
  10271. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  10272. // operands, but not unary promotions.
  10273. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  10274. // So we treat the LHS as a ignored value, and in C++ we allow the
  10275. // containing site to determine what should be done with the RHS.
  10276. LHS = S.IgnoredValueConversions(LHS.get());
  10277. if (LHS.isInvalid())
  10278. return QualType();
  10279. S.DiagnoseUnusedExprResult(LHS.get());
  10280. if (!S.getLangOpts().CPlusPlus) {
  10281. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  10282. if (RHS.isInvalid())
  10283. return QualType();
  10284. if (!RHS.get()->getType()->isVoidType())
  10285. S.RequireCompleteType(Loc, RHS.get()->getType(),
  10286. diag::err_incomplete_type);
  10287. }
  10288. if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
  10289. S.DiagnoseCommaOperator(LHS.get(), Loc);
  10290. return RHS.get()->getType();
  10291. }
  10292. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  10293. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  10294. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  10295. ExprValueKind &VK,
  10296. ExprObjectKind &OK,
  10297. SourceLocation OpLoc,
  10298. bool IsInc, bool IsPrefix) {
  10299. if (Op->isTypeDependent())
  10300. return S.Context.DependentTy;
  10301. QualType ResType = Op->getType();
  10302. // Atomic types can be used for increment / decrement where the non-atomic
  10303. // versions can, so ignore the _Atomic() specifier for the purpose of
  10304. // checking.
  10305. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  10306. ResType = ResAtomicType->getValueType();
  10307. assert(!ResType.isNull() && "no type for increment/decrement expression");
  10308. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  10309. // Decrement of bool is not allowed.
  10310. if (!IsInc) {
  10311. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  10312. return QualType();
  10313. }
  10314. // Increment of bool sets it to true, but is deprecated.
  10315. S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
  10316. : diag::warn_increment_bool)
  10317. << Op->getSourceRange();
  10318. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  10319. // Error on enum increments and decrements in C++ mode
  10320. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  10321. return QualType();
  10322. } else if (ResType->isRealType()) {
  10323. // OK!
  10324. } else if (ResType->isPointerType()) {
  10325. // C99 6.5.2.4p2, 6.5.6p2
  10326. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  10327. return QualType();
  10328. } else if (ResType->isObjCObjectPointerType()) {
  10329. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  10330. // Otherwise, we just need a complete type.
  10331. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  10332. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  10333. return QualType();
  10334. } else if (ResType->isAnyComplexType()) {
  10335. // C99 does not support ++/-- on complex types, we allow as an extension.
  10336. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  10337. << ResType << Op->getSourceRange();
  10338. } else if (ResType->isPlaceholderType()) {
  10339. ExprResult PR = S.CheckPlaceholderExpr(Op);
  10340. if (PR.isInvalid()) return QualType();
  10341. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  10342. IsInc, IsPrefix);
  10343. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  10344. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  10345. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  10346. (ResType->getAs<VectorType>()->getVectorKind() !=
  10347. VectorType::AltiVecBool)) {
  10348. // The z vector extensions allow ++ and -- for non-bool vectors.
  10349. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  10350. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  10351. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  10352. } else {
  10353. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  10354. << ResType << int(IsInc) << Op->getSourceRange();
  10355. return QualType();
  10356. }
  10357. // At this point, we know we have a real, complex or pointer type.
  10358. // Now make sure the operand is a modifiable lvalue.
  10359. if (CheckForModifiableLvalue(Op, OpLoc, S))
  10360. return QualType();
  10361. // In C++, a prefix increment is the same type as the operand. Otherwise
  10362. // (in C or with postfix), the increment is the unqualified type of the
  10363. // operand.
  10364. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  10365. VK = VK_LValue;
  10366. OK = Op->getObjectKind();
  10367. return ResType;
  10368. } else {
  10369. VK = VK_RValue;
  10370. return ResType.getUnqualifiedType();
  10371. }
  10372. }
  10373. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  10374. /// This routine allows us to typecheck complex/recursive expressions
  10375. /// where the declaration is needed for type checking. We only need to
  10376. /// handle cases when the expression references a function designator
  10377. /// or is an lvalue. Here are some examples:
  10378. /// - &(x) => x
  10379. /// - &*****f => f for f a function designator.
  10380. /// - &s.xx => s
  10381. /// - &s.zz[1].yy -> s, if zz is an array
  10382. /// - *(x + 1) -> x, if x is an array
  10383. /// - &"123"[2] -> 0
  10384. /// - & __real__ x -> x
  10385. static ValueDecl *getPrimaryDecl(Expr *E) {
  10386. switch (E->getStmtClass()) {
  10387. case Stmt::DeclRefExprClass:
  10388. return cast<DeclRefExpr>(E)->getDecl();
  10389. case Stmt::MemberExprClass:
  10390. // If this is an arrow operator, the address is an offset from
  10391. // the base's value, so the object the base refers to is
  10392. // irrelevant.
  10393. if (cast<MemberExpr>(E)->isArrow())
  10394. return nullptr;
  10395. // Otherwise, the expression refers to a part of the base
  10396. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  10397. case Stmt::ArraySubscriptExprClass: {
  10398. // FIXME: This code shouldn't be necessary! We should catch the implicit
  10399. // promotion of register arrays earlier.
  10400. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  10401. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  10402. if (ICE->getSubExpr()->getType()->isArrayType())
  10403. return getPrimaryDecl(ICE->getSubExpr());
  10404. }
  10405. return nullptr;
  10406. }
  10407. case Stmt::UnaryOperatorClass: {
  10408. UnaryOperator *UO = cast<UnaryOperator>(E);
  10409. switch(UO->getOpcode()) {
  10410. case UO_Real:
  10411. case UO_Imag:
  10412. case UO_Extension:
  10413. return getPrimaryDecl(UO->getSubExpr());
  10414. default:
  10415. return nullptr;
  10416. }
  10417. }
  10418. case Stmt::ParenExprClass:
  10419. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  10420. case Stmt::ImplicitCastExprClass:
  10421. // If the result of an implicit cast is an l-value, we care about
  10422. // the sub-expression; otherwise, the result here doesn't matter.
  10423. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  10424. default:
  10425. return nullptr;
  10426. }
  10427. }
  10428. namespace {
  10429. enum {
  10430. AO_Bit_Field = 0,
  10431. AO_Vector_Element = 1,
  10432. AO_Property_Expansion = 2,
  10433. AO_Register_Variable = 3,
  10434. AO_No_Error = 4
  10435. };
  10436. }
  10437. /// Diagnose invalid operand for address of operations.
  10438. ///
  10439. /// \param Type The type of operand which cannot have its address taken.
  10440. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  10441. Expr *E, unsigned Type) {
  10442. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  10443. }
  10444. /// CheckAddressOfOperand - The operand of & must be either a function
  10445. /// designator or an lvalue designating an object. If it is an lvalue, the
  10446. /// object cannot be declared with storage class register or be a bit field.
  10447. /// Note: The usual conversions are *not* applied to the operand of the &
  10448. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  10449. /// In C++, the operand might be an overloaded function name, in which case
  10450. /// we allow the '&' but retain the overloaded-function type.
  10451. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  10452. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  10453. if (PTy->getKind() == BuiltinType::Overload) {
  10454. Expr *E = OrigOp.get()->IgnoreParens();
  10455. if (!isa<OverloadExpr>(E)) {
  10456. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  10457. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  10458. << OrigOp.get()->getSourceRange();
  10459. return QualType();
  10460. }
  10461. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  10462. if (isa<UnresolvedMemberExpr>(Ovl))
  10463. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  10464. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10465. << OrigOp.get()->getSourceRange();
  10466. return QualType();
  10467. }
  10468. return Context.OverloadTy;
  10469. }
  10470. if (PTy->getKind() == BuiltinType::UnknownAny)
  10471. return Context.UnknownAnyTy;
  10472. if (PTy->getKind() == BuiltinType::BoundMember) {
  10473. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10474. << OrigOp.get()->getSourceRange();
  10475. return QualType();
  10476. }
  10477. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  10478. if (OrigOp.isInvalid()) return QualType();
  10479. }
  10480. if (OrigOp.get()->isTypeDependent())
  10481. return Context.DependentTy;
  10482. assert(!OrigOp.get()->getType()->isPlaceholderType());
  10483. // Make sure to ignore parentheses in subsequent checks
  10484. Expr *op = OrigOp.get()->IgnoreParens();
  10485. // In OpenCL captures for blocks called as lambda functions
  10486. // are located in the private address space. Blocks used in
  10487. // enqueue_kernel can be located in a different address space
  10488. // depending on a vendor implementation. Thus preventing
  10489. // taking an address of the capture to avoid invalid AS casts.
  10490. if (LangOpts.OpenCL) {
  10491. auto* VarRef = dyn_cast<DeclRefExpr>(op);
  10492. if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
  10493. Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
  10494. return QualType();
  10495. }
  10496. }
  10497. if (getLangOpts().C99) {
  10498. // Implement C99-only parts of addressof rules.
  10499. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  10500. if (uOp->getOpcode() == UO_Deref)
  10501. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  10502. // (assuming the deref expression is valid).
  10503. return uOp->getSubExpr()->getType();
  10504. }
  10505. // Technically, there should be a check for array subscript
  10506. // expressions here, but the result of one is always an lvalue anyway.
  10507. }
  10508. ValueDecl *dcl = getPrimaryDecl(op);
  10509. if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
  10510. if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  10511. op->getBeginLoc()))
  10512. return QualType();
  10513. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  10514. unsigned AddressOfError = AO_No_Error;
  10515. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  10516. bool sfinae = (bool)isSFINAEContext();
  10517. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  10518. : diag::ext_typecheck_addrof_temporary)
  10519. << op->getType() << op->getSourceRange();
  10520. if (sfinae)
  10521. return QualType();
  10522. // Materialize the temporary as an lvalue so that we can take its address.
  10523. OrigOp = op =
  10524. CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  10525. } else if (isa<ObjCSelectorExpr>(op)) {
  10526. return Context.getPointerType(op->getType());
  10527. } else if (lval == Expr::LV_MemberFunction) {
  10528. // If it's an instance method, make a member pointer.
  10529. // The expression must have exactly the form &A::foo.
  10530. // If the underlying expression isn't a decl ref, give up.
  10531. if (!isa<DeclRefExpr>(op)) {
  10532. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10533. << OrigOp.get()->getSourceRange();
  10534. return QualType();
  10535. }
  10536. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  10537. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  10538. // The id-expression was parenthesized.
  10539. if (OrigOp.get() != DRE) {
  10540. Diag(OpLoc, diag::err_parens_pointer_member_function)
  10541. << OrigOp.get()->getSourceRange();
  10542. // The method was named without a qualifier.
  10543. } else if (!DRE->getQualifier()) {
  10544. if (MD->getParent()->getName().empty())
  10545. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10546. << op->getSourceRange();
  10547. else {
  10548. SmallString<32> Str;
  10549. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  10550. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10551. << op->getSourceRange()
  10552. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  10553. }
  10554. }
  10555. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  10556. if (isa<CXXDestructorDecl>(MD))
  10557. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  10558. QualType MPTy = Context.getMemberPointerType(
  10559. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  10560. // Under the MS ABI, lock down the inheritance model now.
  10561. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10562. (void)isCompleteType(OpLoc, MPTy);
  10563. return MPTy;
  10564. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  10565. // C99 6.5.3.2p1
  10566. // The operand must be either an l-value or a function designator
  10567. if (!op->getType()->isFunctionType()) {
  10568. // Use a special diagnostic for loads from property references.
  10569. if (isa<PseudoObjectExpr>(op)) {
  10570. AddressOfError = AO_Property_Expansion;
  10571. } else {
  10572. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  10573. << op->getType() << op->getSourceRange();
  10574. return QualType();
  10575. }
  10576. }
  10577. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  10578. // The operand cannot be a bit-field
  10579. AddressOfError = AO_Bit_Field;
  10580. } else if (op->getObjectKind() == OK_VectorComponent) {
  10581. // The operand cannot be an element of a vector
  10582. AddressOfError = AO_Vector_Element;
  10583. } else if (dcl) { // C99 6.5.3.2p1
  10584. // We have an lvalue with a decl. Make sure the decl is not declared
  10585. // with the register storage-class specifier.
  10586. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  10587. // in C++ it is not error to take address of a register
  10588. // variable (c++03 7.1.1P3)
  10589. if (vd->getStorageClass() == SC_Register &&
  10590. !getLangOpts().CPlusPlus) {
  10591. AddressOfError = AO_Register_Variable;
  10592. }
  10593. } else if (isa<MSPropertyDecl>(dcl)) {
  10594. AddressOfError = AO_Property_Expansion;
  10595. } else if (isa<FunctionTemplateDecl>(dcl)) {
  10596. return Context.OverloadTy;
  10597. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  10598. // Okay: we can take the address of a field.
  10599. // Could be a pointer to member, though, if there is an explicit
  10600. // scope qualifier for the class.
  10601. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  10602. DeclContext *Ctx = dcl->getDeclContext();
  10603. if (Ctx && Ctx->isRecord()) {
  10604. if (dcl->getType()->isReferenceType()) {
  10605. Diag(OpLoc,
  10606. diag::err_cannot_form_pointer_to_member_of_reference_type)
  10607. << dcl->getDeclName() << dcl->getType();
  10608. return QualType();
  10609. }
  10610. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  10611. Ctx = Ctx->getParent();
  10612. QualType MPTy = Context.getMemberPointerType(
  10613. op->getType(),
  10614. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  10615. // Under the MS ABI, lock down the inheritance model now.
  10616. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10617. (void)isCompleteType(OpLoc, MPTy);
  10618. return MPTy;
  10619. }
  10620. }
  10621. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
  10622. !isa<BindingDecl>(dcl))
  10623. llvm_unreachable("Unknown/unexpected decl type");
  10624. }
  10625. if (AddressOfError != AO_No_Error) {
  10626. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  10627. return QualType();
  10628. }
  10629. if (lval == Expr::LV_IncompleteVoidType) {
  10630. // Taking the address of a void variable is technically illegal, but we
  10631. // allow it in cases which are otherwise valid.
  10632. // Example: "extern void x; void* y = &x;".
  10633. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  10634. }
  10635. // If the operand has type "type", the result has type "pointer to type".
  10636. if (op->getType()->isObjCObjectType())
  10637. return Context.getObjCObjectPointerType(op->getType());
  10638. CheckAddressOfPackedMember(op);
  10639. return Context.getPointerType(op->getType());
  10640. }
  10641. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  10642. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  10643. if (!DRE)
  10644. return;
  10645. const Decl *D = DRE->getDecl();
  10646. if (!D)
  10647. return;
  10648. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  10649. if (!Param)
  10650. return;
  10651. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  10652. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  10653. return;
  10654. if (FunctionScopeInfo *FD = S.getCurFunction())
  10655. if (!FD->ModifiedNonNullParams.count(Param))
  10656. FD->ModifiedNonNullParams.insert(Param);
  10657. }
  10658. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  10659. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  10660. SourceLocation OpLoc) {
  10661. if (Op->isTypeDependent())
  10662. return S.Context.DependentTy;
  10663. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  10664. if (ConvResult.isInvalid())
  10665. return QualType();
  10666. Op = ConvResult.get();
  10667. QualType OpTy = Op->getType();
  10668. QualType Result;
  10669. if (isa<CXXReinterpretCastExpr>(Op)) {
  10670. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  10671. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  10672. Op->getSourceRange());
  10673. }
  10674. if (const PointerType *PT = OpTy->getAs<PointerType>())
  10675. {
  10676. Result = PT->getPointeeType();
  10677. }
  10678. else if (const ObjCObjectPointerType *OPT =
  10679. OpTy->getAs<ObjCObjectPointerType>())
  10680. Result = OPT->getPointeeType();
  10681. else {
  10682. ExprResult PR = S.CheckPlaceholderExpr(Op);
  10683. if (PR.isInvalid()) return QualType();
  10684. if (PR.get() != Op)
  10685. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  10686. }
  10687. if (Result.isNull()) {
  10688. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  10689. << OpTy << Op->getSourceRange();
  10690. return QualType();
  10691. }
  10692. // Note that per both C89 and C99, indirection is always legal, even if Result
  10693. // is an incomplete type or void. It would be possible to warn about
  10694. // dereferencing a void pointer, but it's completely well-defined, and such a
  10695. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  10696. // for pointers to 'void' but is fine for any other pointer type:
  10697. //
  10698. // C++ [expr.unary.op]p1:
  10699. // [...] the expression to which [the unary * operator] is applied shall
  10700. // be a pointer to an object type, or a pointer to a function type
  10701. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  10702. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  10703. << OpTy << Op->getSourceRange();
  10704. // Dereferences are usually l-values...
  10705. VK = VK_LValue;
  10706. // ...except that certain expressions are never l-values in C.
  10707. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  10708. VK = VK_RValue;
  10709. return Result;
  10710. }
  10711. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  10712. BinaryOperatorKind Opc;
  10713. switch (Kind) {
  10714. default: llvm_unreachable("Unknown binop!");
  10715. case tok::periodstar: Opc = BO_PtrMemD; break;
  10716. case tok::arrowstar: Opc = BO_PtrMemI; break;
  10717. case tok::star: Opc = BO_Mul; break;
  10718. case tok::slash: Opc = BO_Div; break;
  10719. case tok::percent: Opc = BO_Rem; break;
  10720. case tok::plus: Opc = BO_Add; break;
  10721. case tok::minus: Opc = BO_Sub; break;
  10722. case tok::lessless: Opc = BO_Shl; break;
  10723. case tok::greatergreater: Opc = BO_Shr; break;
  10724. case tok::lessequal: Opc = BO_LE; break;
  10725. case tok::less: Opc = BO_LT; break;
  10726. case tok::greaterequal: Opc = BO_GE; break;
  10727. case tok::greater: Opc = BO_GT; break;
  10728. case tok::exclaimequal: Opc = BO_NE; break;
  10729. case tok::equalequal: Opc = BO_EQ; break;
  10730. case tok::spaceship: Opc = BO_Cmp; break;
  10731. case tok::amp: Opc = BO_And; break;
  10732. case tok::caret: Opc = BO_Xor; break;
  10733. case tok::pipe: Opc = BO_Or; break;
  10734. case tok::ampamp: Opc = BO_LAnd; break;
  10735. case tok::pipepipe: Opc = BO_LOr; break;
  10736. case tok::equal: Opc = BO_Assign; break;
  10737. case tok::starequal: Opc = BO_MulAssign; break;
  10738. case tok::slashequal: Opc = BO_DivAssign; break;
  10739. case tok::percentequal: Opc = BO_RemAssign; break;
  10740. case tok::plusequal: Opc = BO_AddAssign; break;
  10741. case tok::minusequal: Opc = BO_SubAssign; break;
  10742. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  10743. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  10744. case tok::ampequal: Opc = BO_AndAssign; break;
  10745. case tok::caretequal: Opc = BO_XorAssign; break;
  10746. case tok::pipeequal: Opc = BO_OrAssign; break;
  10747. case tok::comma: Opc = BO_Comma; break;
  10748. }
  10749. return Opc;
  10750. }
  10751. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  10752. tok::TokenKind Kind) {
  10753. UnaryOperatorKind Opc;
  10754. switch (Kind) {
  10755. default: llvm_unreachable("Unknown unary op!");
  10756. case tok::plusplus: Opc = UO_PreInc; break;
  10757. case tok::minusminus: Opc = UO_PreDec; break;
  10758. case tok::amp: Opc = UO_AddrOf; break;
  10759. case tok::star: Opc = UO_Deref; break;
  10760. case tok::plus: Opc = UO_Plus; break;
  10761. case tok::minus: Opc = UO_Minus; break;
  10762. case tok::tilde: Opc = UO_Not; break;
  10763. case tok::exclaim: Opc = UO_LNot; break;
  10764. case tok::kw___real: Opc = UO_Real; break;
  10765. case tok::kw___imag: Opc = UO_Imag; break;
  10766. case tok::kw___extension__: Opc = UO_Extension; break;
  10767. }
  10768. return Opc;
  10769. }
  10770. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  10771. /// This warning suppressed in the event of macro expansions.
  10772. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  10773. SourceLocation OpLoc, bool IsBuiltin) {
  10774. if (S.inTemplateInstantiation())
  10775. return;
  10776. if (S.isUnevaluatedContext())
  10777. return;
  10778. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  10779. return;
  10780. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  10781. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  10782. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  10783. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  10784. if (!LHSDeclRef || !RHSDeclRef ||
  10785. LHSDeclRef->getLocation().isMacroID() ||
  10786. RHSDeclRef->getLocation().isMacroID())
  10787. return;
  10788. const ValueDecl *LHSDecl =
  10789. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  10790. const ValueDecl *RHSDecl =
  10791. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  10792. if (LHSDecl != RHSDecl)
  10793. return;
  10794. if (LHSDecl->getType().isVolatileQualified())
  10795. return;
  10796. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  10797. if (RefTy->getPointeeType().isVolatileQualified())
  10798. return;
  10799. S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
  10800. : diag::warn_self_assignment_overloaded)
  10801. << LHSDeclRef->getType() << LHSExpr->getSourceRange()
  10802. << RHSExpr->getSourceRange();
  10803. }
  10804. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  10805. /// is usually indicative of introspection within the Objective-C pointer.
  10806. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  10807. SourceLocation OpLoc) {
  10808. if (!S.getLangOpts().ObjC)
  10809. return;
  10810. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  10811. const Expr *LHS = L.get();
  10812. const Expr *RHS = R.get();
  10813. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  10814. ObjCPointerExpr = LHS;
  10815. OtherExpr = RHS;
  10816. }
  10817. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  10818. ObjCPointerExpr = RHS;
  10819. OtherExpr = LHS;
  10820. }
  10821. // This warning is deliberately made very specific to reduce false
  10822. // positives with logic that uses '&' for hashing. This logic mainly
  10823. // looks for code trying to introspect into tagged pointers, which
  10824. // code should generally never do.
  10825. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  10826. unsigned Diag = diag::warn_objc_pointer_masking;
  10827. // Determine if we are introspecting the result of performSelectorXXX.
  10828. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  10829. // Special case messages to -performSelector and friends, which
  10830. // can return non-pointer values boxed in a pointer value.
  10831. // Some clients may wish to silence warnings in this subcase.
  10832. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  10833. Selector S = ME->getSelector();
  10834. StringRef SelArg0 = S.getNameForSlot(0);
  10835. if (SelArg0.startswith("performSelector"))
  10836. Diag = diag::warn_objc_pointer_masking_performSelector;
  10837. }
  10838. S.Diag(OpLoc, Diag)
  10839. << ObjCPointerExpr->getSourceRange();
  10840. }
  10841. }
  10842. static NamedDecl *getDeclFromExpr(Expr *E) {
  10843. if (!E)
  10844. return nullptr;
  10845. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  10846. return DRE->getDecl();
  10847. if (auto *ME = dyn_cast<MemberExpr>(E))
  10848. return ME->getMemberDecl();
  10849. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  10850. return IRE->getDecl();
  10851. return nullptr;
  10852. }
  10853. // This helper function promotes a binary operator's operands (which are of a
  10854. // half vector type) to a vector of floats and then truncates the result to
  10855. // a vector of either half or short.
  10856. static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
  10857. BinaryOperatorKind Opc, QualType ResultTy,
  10858. ExprValueKind VK, ExprObjectKind OK,
  10859. bool IsCompAssign, SourceLocation OpLoc,
  10860. FPOptions FPFeatures) {
  10861. auto &Context = S.getASTContext();
  10862. assert((isVector(ResultTy, Context.HalfTy) ||
  10863. isVector(ResultTy, Context.ShortTy)) &&
  10864. "Result must be a vector of half or short");
  10865. assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
  10866. isVector(RHS.get()->getType(), Context.HalfTy) &&
  10867. "both operands expected to be a half vector");
  10868. RHS = convertVector(RHS.get(), Context.FloatTy, S);
  10869. QualType BinOpResTy = RHS.get()->getType();
  10870. // If Opc is a comparison, ResultType is a vector of shorts. In that case,
  10871. // change BinOpResTy to a vector of ints.
  10872. if (isVector(ResultTy, Context.ShortTy))
  10873. BinOpResTy = S.GetSignedVectorType(BinOpResTy);
  10874. if (IsCompAssign)
  10875. return new (Context) CompoundAssignOperator(
  10876. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
  10877. OpLoc, FPFeatures);
  10878. LHS = convertVector(LHS.get(), Context.FloatTy, S);
  10879. auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
  10880. VK, OK, OpLoc, FPFeatures);
  10881. return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
  10882. }
  10883. static std::pair<ExprResult, ExprResult>
  10884. CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
  10885. Expr *RHSExpr) {
  10886. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  10887. if (!S.getLangOpts().CPlusPlus) {
  10888. // C cannot handle TypoExpr nodes on either side of a binop because it
  10889. // doesn't handle dependent types properly, so make sure any TypoExprs have
  10890. // been dealt with before checking the operands.
  10891. LHS = S.CorrectDelayedTyposInExpr(LHS);
  10892. RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
  10893. if (Opc != BO_Assign)
  10894. return ExprResult(E);
  10895. // Avoid correcting the RHS to the same Expr as the LHS.
  10896. Decl *D = getDeclFromExpr(E);
  10897. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  10898. });
  10899. }
  10900. return std::make_pair(LHS, RHS);
  10901. }
  10902. /// Returns true if conversion between vectors of halfs and vectors of floats
  10903. /// is needed.
  10904. static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
  10905. QualType SrcType) {
  10906. return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
  10907. !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
  10908. isVector(SrcType, Ctx.HalfTy);
  10909. }
  10910. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  10911. /// operator @p Opc at location @c TokLoc. This routine only supports
  10912. /// built-in operations; ActOnBinOp handles overloaded operators.
  10913. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  10914. BinaryOperatorKind Opc,
  10915. Expr *LHSExpr, Expr *RHSExpr) {
  10916. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  10917. // The syntax only allows initializer lists on the RHS of assignment,
  10918. // so we don't need to worry about accepting invalid code for
  10919. // non-assignment operators.
  10920. // C++11 5.17p9:
  10921. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  10922. // of x = {} is x = T().
  10923. InitializationKind Kind = InitializationKind::CreateDirectList(
  10924. RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  10925. InitializedEntity Entity =
  10926. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  10927. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  10928. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  10929. if (Init.isInvalid())
  10930. return Init;
  10931. RHSExpr = Init.get();
  10932. }
  10933. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  10934. QualType ResultTy; // Result type of the binary operator.
  10935. // The following two variables are used for compound assignment operators
  10936. QualType CompLHSTy; // Type of LHS after promotions for computation
  10937. QualType CompResultTy; // Type of computation result
  10938. ExprValueKind VK = VK_RValue;
  10939. ExprObjectKind OK = OK_Ordinary;
  10940. bool ConvertHalfVec = false;
  10941. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  10942. if (!LHS.isUsable() || !RHS.isUsable())
  10943. return ExprError();
  10944. if (getLangOpts().OpenCL) {
  10945. QualType LHSTy = LHSExpr->getType();
  10946. QualType RHSTy = RHSExpr->getType();
  10947. // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
  10948. // the ATOMIC_VAR_INIT macro.
  10949. if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
  10950. SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  10951. if (BO_Assign == Opc)
  10952. Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
  10953. else
  10954. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  10955. return ExprError();
  10956. }
  10957. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  10958. // only with a builtin functions and therefore should be disallowed here.
  10959. if (LHSTy->isImageType() || RHSTy->isImageType() ||
  10960. LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
  10961. LHSTy->isPipeType() || RHSTy->isPipeType() ||
  10962. LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
  10963. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  10964. return ExprError();
  10965. }
  10966. }
  10967. // Diagnose operations on the unsupported types for OpenMP device compilation.
  10968. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
  10969. if (Opc != BO_Assign && Opc != BO_Comma) {
  10970. checkOpenMPDeviceExpr(LHSExpr);
  10971. checkOpenMPDeviceExpr(RHSExpr);
  10972. }
  10973. }
  10974. switch (Opc) {
  10975. case BO_Assign:
  10976. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  10977. if (getLangOpts().CPlusPlus &&
  10978. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  10979. VK = LHS.get()->getValueKind();
  10980. OK = LHS.get()->getObjectKind();
  10981. }
  10982. if (!ResultTy.isNull()) {
  10983. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  10984. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  10985. // Avoid copying a block to the heap if the block is assigned to a local
  10986. // auto variable that is declared in the same scope as the block. This
  10987. // optimization is unsafe if the local variable is declared in an outer
  10988. // scope. For example:
  10989. //
  10990. // BlockTy b;
  10991. // {
  10992. // b = ^{...};
  10993. // }
  10994. // // It is unsafe to invoke the block here if it wasn't copied to the
  10995. // // heap.
  10996. // b();
  10997. if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
  10998. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
  10999. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  11000. if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
  11001. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  11002. }
  11003. RecordModifiableNonNullParam(*this, LHS.get());
  11004. break;
  11005. case BO_PtrMemD:
  11006. case BO_PtrMemI:
  11007. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  11008. Opc == BO_PtrMemI);
  11009. break;
  11010. case BO_Mul:
  11011. case BO_Div:
  11012. ConvertHalfVec = true;
  11013. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  11014. Opc == BO_Div);
  11015. break;
  11016. case BO_Rem:
  11017. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  11018. break;
  11019. case BO_Add:
  11020. ConvertHalfVec = true;
  11021. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  11022. break;
  11023. case BO_Sub:
  11024. ConvertHalfVec = true;
  11025. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  11026. break;
  11027. case BO_Shl:
  11028. case BO_Shr:
  11029. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  11030. break;
  11031. case BO_LE:
  11032. case BO_LT:
  11033. case BO_GE:
  11034. case BO_GT:
  11035. ConvertHalfVec = true;
  11036. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11037. break;
  11038. case BO_EQ:
  11039. case BO_NE:
  11040. ConvertHalfVec = true;
  11041. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11042. break;
  11043. case BO_Cmp:
  11044. ConvertHalfVec = true;
  11045. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11046. assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
  11047. break;
  11048. case BO_And:
  11049. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  11050. LLVM_FALLTHROUGH;
  11051. case BO_Xor:
  11052. case BO_Or:
  11053. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  11054. break;
  11055. case BO_LAnd:
  11056. case BO_LOr:
  11057. ConvertHalfVec = true;
  11058. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  11059. break;
  11060. case BO_MulAssign:
  11061. case BO_DivAssign:
  11062. ConvertHalfVec = true;
  11063. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  11064. Opc == BO_DivAssign);
  11065. CompLHSTy = CompResultTy;
  11066. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11067. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11068. break;
  11069. case BO_RemAssign:
  11070. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  11071. CompLHSTy = CompResultTy;
  11072. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11073. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11074. break;
  11075. case BO_AddAssign:
  11076. ConvertHalfVec = true;
  11077. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  11078. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11079. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11080. break;
  11081. case BO_SubAssign:
  11082. ConvertHalfVec = true;
  11083. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  11084. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11085. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11086. break;
  11087. case BO_ShlAssign:
  11088. case BO_ShrAssign:
  11089. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  11090. CompLHSTy = CompResultTy;
  11091. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11092. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11093. break;
  11094. case BO_AndAssign:
  11095. case BO_OrAssign: // fallthrough
  11096. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  11097. LLVM_FALLTHROUGH;
  11098. case BO_XorAssign:
  11099. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  11100. CompLHSTy = CompResultTy;
  11101. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11102. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11103. break;
  11104. case BO_Comma:
  11105. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  11106. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  11107. VK = RHS.get()->getValueKind();
  11108. OK = RHS.get()->getObjectKind();
  11109. }
  11110. break;
  11111. }
  11112. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  11113. return ExprError();
  11114. // Some of the binary operations require promoting operands of half vector to
  11115. // float vectors and truncating the result back to half vector. For now, we do
  11116. // this only when HalfArgsAndReturn is set (that is, when the target is arm or
  11117. // arm64).
  11118. assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
  11119. isVector(LHS.get()->getType(), Context.HalfTy) &&
  11120. "both sides are half vectors or neither sides are");
  11121. ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
  11122. LHS.get()->getType());
  11123. // Check for array bounds violations for both sides of the BinaryOperator
  11124. CheckArrayAccess(LHS.get());
  11125. CheckArrayAccess(RHS.get());
  11126. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  11127. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  11128. &Context.Idents.get("object_setClass"),
  11129. SourceLocation(), LookupOrdinaryName);
  11130. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  11131. SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
  11132. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
  11133. << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
  11134. "object_setClass(")
  11135. << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
  11136. ",")
  11137. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  11138. }
  11139. else
  11140. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  11141. }
  11142. else if (const ObjCIvarRefExpr *OIRE =
  11143. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  11144. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  11145. // Opc is not a compound assignment if CompResultTy is null.
  11146. if (CompResultTy.isNull()) {
  11147. if (ConvertHalfVec)
  11148. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
  11149. OpLoc, FPFeatures);
  11150. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  11151. OK, OpLoc, FPFeatures);
  11152. }
  11153. // Handle compound assignments.
  11154. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  11155. OK_ObjCProperty) {
  11156. VK = VK_LValue;
  11157. OK = LHS.get()->getObjectKind();
  11158. }
  11159. if (ConvertHalfVec)
  11160. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
  11161. OpLoc, FPFeatures);
  11162. return new (Context) CompoundAssignOperator(
  11163. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  11164. OpLoc, FPFeatures);
  11165. }
  11166. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  11167. /// operators are mixed in a way that suggests that the programmer forgot that
  11168. /// comparison operators have higher precedence. The most typical example of
  11169. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  11170. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  11171. SourceLocation OpLoc, Expr *LHSExpr,
  11172. Expr *RHSExpr) {
  11173. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  11174. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  11175. // Check that one of the sides is a comparison operator and the other isn't.
  11176. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  11177. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  11178. if (isLeftComp == isRightComp)
  11179. return;
  11180. // Bitwise operations are sometimes used as eager logical ops.
  11181. // Don't diagnose this.
  11182. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  11183. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  11184. if (isLeftBitwise || isRightBitwise)
  11185. return;
  11186. SourceRange DiagRange = isLeftComp
  11187. ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
  11188. : SourceRange(OpLoc, RHSExpr->getEndLoc());
  11189. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  11190. SourceRange ParensRange =
  11191. isLeftComp
  11192. ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
  11193. : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
  11194. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  11195. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  11196. SuggestParentheses(Self, OpLoc,
  11197. Self.PDiag(diag::note_precedence_silence) << OpStr,
  11198. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  11199. SuggestParentheses(Self, OpLoc,
  11200. Self.PDiag(diag::note_precedence_bitwise_first)
  11201. << BinaryOperator::getOpcodeStr(Opc),
  11202. ParensRange);
  11203. }
  11204. /// It accepts a '&&' expr that is inside a '||' one.
  11205. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  11206. /// in parentheses.
  11207. static void
  11208. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  11209. BinaryOperator *Bop) {
  11210. assert(Bop->getOpcode() == BO_LAnd);
  11211. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  11212. << Bop->getSourceRange() << OpLoc;
  11213. SuggestParentheses(Self, Bop->getOperatorLoc(),
  11214. Self.PDiag(diag::note_precedence_silence)
  11215. << Bop->getOpcodeStr(),
  11216. Bop->getSourceRange());
  11217. }
  11218. /// Returns true if the given expression can be evaluated as a constant
  11219. /// 'true'.
  11220. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  11221. bool Res;
  11222. return !E->isValueDependent() &&
  11223. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  11224. }
  11225. /// Returns true if the given expression can be evaluated as a constant
  11226. /// 'false'.
  11227. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  11228. bool Res;
  11229. return !E->isValueDependent() &&
  11230. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  11231. }
  11232. /// Look for '&&' in the left hand of a '||' expr.
  11233. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  11234. Expr *LHSExpr, Expr *RHSExpr) {
  11235. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  11236. if (Bop->getOpcode() == BO_LAnd) {
  11237. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  11238. if (EvaluatesAsFalse(S, RHSExpr))
  11239. return;
  11240. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  11241. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  11242. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  11243. } else if (Bop->getOpcode() == BO_LOr) {
  11244. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  11245. // If it's "a || b && 1 || c" we didn't warn earlier for
  11246. // "a || b && 1", but warn now.
  11247. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  11248. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  11249. }
  11250. }
  11251. }
  11252. }
  11253. /// Look for '&&' in the right hand of a '||' expr.
  11254. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  11255. Expr *LHSExpr, Expr *RHSExpr) {
  11256. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  11257. if (Bop->getOpcode() == BO_LAnd) {
  11258. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  11259. if (EvaluatesAsFalse(S, LHSExpr))
  11260. return;
  11261. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  11262. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  11263. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  11264. }
  11265. }
  11266. }
  11267. /// Look for bitwise op in the left or right hand of a bitwise op with
  11268. /// lower precedence and emit a diagnostic together with a fixit hint that wraps
  11269. /// the '&' expression in parentheses.
  11270. static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
  11271. SourceLocation OpLoc, Expr *SubExpr) {
  11272. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11273. if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
  11274. S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
  11275. << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
  11276. << Bop->getSourceRange() << OpLoc;
  11277. SuggestParentheses(S, Bop->getOperatorLoc(),
  11278. S.PDiag(diag::note_precedence_silence)
  11279. << Bop->getOpcodeStr(),
  11280. Bop->getSourceRange());
  11281. }
  11282. }
  11283. }
  11284. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  11285. Expr *SubExpr, StringRef Shift) {
  11286. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11287. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  11288. StringRef Op = Bop->getOpcodeStr();
  11289. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  11290. << Bop->getSourceRange() << OpLoc << Shift << Op;
  11291. SuggestParentheses(S, Bop->getOperatorLoc(),
  11292. S.PDiag(diag::note_precedence_silence) << Op,
  11293. Bop->getSourceRange());
  11294. }
  11295. }
  11296. }
  11297. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  11298. Expr *LHSExpr, Expr *RHSExpr) {
  11299. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  11300. if (!OCE)
  11301. return;
  11302. FunctionDecl *FD = OCE->getDirectCallee();
  11303. if (!FD || !FD->isOverloadedOperator())
  11304. return;
  11305. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  11306. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  11307. return;
  11308. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  11309. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  11310. << (Kind == OO_LessLess);
  11311. SuggestParentheses(S, OCE->getOperatorLoc(),
  11312. S.PDiag(diag::note_precedence_silence)
  11313. << (Kind == OO_LessLess ? "<<" : ">>"),
  11314. OCE->getSourceRange());
  11315. SuggestParentheses(
  11316. S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
  11317. SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
  11318. }
  11319. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  11320. /// precedence.
  11321. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  11322. SourceLocation OpLoc, Expr *LHSExpr,
  11323. Expr *RHSExpr){
  11324. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  11325. if (BinaryOperator::isBitwiseOp(Opc))
  11326. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  11327. // Diagnose "arg1 & arg2 | arg3"
  11328. if ((Opc == BO_Or || Opc == BO_Xor) &&
  11329. !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11330. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
  11331. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
  11332. }
  11333. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  11334. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  11335. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11336. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  11337. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  11338. }
  11339. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  11340. || Opc == BO_Shr) {
  11341. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  11342. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  11343. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  11344. }
  11345. // Warn on overloaded shift operators and comparisons, such as:
  11346. // cout << 5 == 4;
  11347. if (BinaryOperator::isComparisonOp(Opc))
  11348. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  11349. }
  11350. // Binary Operators. 'Tok' is the token for the operator.
  11351. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  11352. tok::TokenKind Kind,
  11353. Expr *LHSExpr, Expr *RHSExpr) {
  11354. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  11355. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  11356. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  11357. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  11358. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  11359. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  11360. }
  11361. /// Build an overloaded binary operator expression in the given scope.
  11362. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  11363. BinaryOperatorKind Opc,
  11364. Expr *LHS, Expr *RHS) {
  11365. switch (Opc) {
  11366. case BO_Assign:
  11367. case BO_DivAssign:
  11368. case BO_RemAssign:
  11369. case BO_SubAssign:
  11370. case BO_AndAssign:
  11371. case BO_OrAssign:
  11372. case BO_XorAssign:
  11373. DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
  11374. CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
  11375. break;
  11376. default:
  11377. break;
  11378. }
  11379. // Find all of the overloaded operators visible from this
  11380. // point. We perform both an operator-name lookup from the local
  11381. // scope and an argument-dependent lookup based on the types of
  11382. // the arguments.
  11383. UnresolvedSet<16> Functions;
  11384. OverloadedOperatorKind OverOp
  11385. = BinaryOperator::getOverloadedOperator(Opc);
  11386. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  11387. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  11388. RHS->getType(), Functions);
  11389. // Build the (potentially-overloaded, potentially-dependent)
  11390. // binary operation.
  11391. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  11392. }
  11393. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  11394. BinaryOperatorKind Opc,
  11395. Expr *LHSExpr, Expr *RHSExpr) {
  11396. ExprResult LHS, RHS;
  11397. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  11398. if (!LHS.isUsable() || !RHS.isUsable())
  11399. return ExprError();
  11400. LHSExpr = LHS.get();
  11401. RHSExpr = RHS.get();
  11402. // We want to end up calling one of checkPseudoObjectAssignment
  11403. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  11404. // both expressions are overloadable or either is type-dependent),
  11405. // or CreateBuiltinBinOp (in any other case). We also want to get
  11406. // any placeholder types out of the way.
  11407. // Handle pseudo-objects in the LHS.
  11408. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  11409. // Assignments with a pseudo-object l-value need special analysis.
  11410. if (pty->getKind() == BuiltinType::PseudoObject &&
  11411. BinaryOperator::isAssignmentOp(Opc))
  11412. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  11413. // Don't resolve overloads if the other type is overloadable.
  11414. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
  11415. // We can't actually test that if we still have a placeholder,
  11416. // though. Fortunately, none of the exceptions we see in that
  11417. // code below are valid when the LHS is an overload set. Note
  11418. // that an overload set can be dependently-typed, but it never
  11419. // instantiates to having an overloadable type.
  11420. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11421. if (resolvedRHS.isInvalid()) return ExprError();
  11422. RHSExpr = resolvedRHS.get();
  11423. if (RHSExpr->isTypeDependent() ||
  11424. RHSExpr->getType()->isOverloadableType())
  11425. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11426. }
  11427. // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
  11428. // template, diagnose the missing 'template' keyword instead of diagnosing
  11429. // an invalid use of a bound member function.
  11430. //
  11431. // Note that "A::x < b" might be valid if 'b' has an overloadable type due
  11432. // to C++1z [over.over]/1.4, but we already checked for that case above.
  11433. if (Opc == BO_LT && inTemplateInstantiation() &&
  11434. (pty->getKind() == BuiltinType::BoundMember ||
  11435. pty->getKind() == BuiltinType::Overload)) {
  11436. auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
  11437. if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
  11438. std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
  11439. return isa<FunctionTemplateDecl>(ND);
  11440. })) {
  11441. Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
  11442. : OE->getNameLoc(),
  11443. diag::err_template_kw_missing)
  11444. << OE->getName().getAsString() << "";
  11445. return ExprError();
  11446. }
  11447. }
  11448. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  11449. if (LHS.isInvalid()) return ExprError();
  11450. LHSExpr = LHS.get();
  11451. }
  11452. // Handle pseudo-objects in the RHS.
  11453. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  11454. // An overload in the RHS can potentially be resolved by the type
  11455. // being assigned to.
  11456. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  11457. if (getLangOpts().CPlusPlus &&
  11458. (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
  11459. LHSExpr->getType()->isOverloadableType()))
  11460. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11461. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11462. }
  11463. // Don't resolve overloads if the other type is overloadable.
  11464. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
  11465. LHSExpr->getType()->isOverloadableType())
  11466. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11467. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11468. if (!resolvedRHS.isUsable()) return ExprError();
  11469. RHSExpr = resolvedRHS.get();
  11470. }
  11471. if (getLangOpts().CPlusPlus) {
  11472. // If either expression is type-dependent, always build an
  11473. // overloaded op.
  11474. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  11475. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11476. // Otherwise, build an overloaded op if either expression has an
  11477. // overloadable type.
  11478. if (LHSExpr->getType()->isOverloadableType() ||
  11479. RHSExpr->getType()->isOverloadableType())
  11480. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11481. }
  11482. // Build a built-in binary operation.
  11483. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11484. }
  11485. static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
  11486. if (T.isNull() || T->isDependentType())
  11487. return false;
  11488. if (!T->isPromotableIntegerType())
  11489. return true;
  11490. return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
  11491. }
  11492. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  11493. UnaryOperatorKind Opc,
  11494. Expr *InputExpr) {
  11495. ExprResult Input = InputExpr;
  11496. ExprValueKind VK = VK_RValue;
  11497. ExprObjectKind OK = OK_Ordinary;
  11498. QualType resultType;
  11499. bool CanOverflow = false;
  11500. bool ConvertHalfVec = false;
  11501. if (getLangOpts().OpenCL) {
  11502. QualType Ty = InputExpr->getType();
  11503. // The only legal unary operation for atomics is '&'.
  11504. if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
  11505. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  11506. // only with a builtin functions and therefore should be disallowed here.
  11507. (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
  11508. || Ty->isBlockPointerType())) {
  11509. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11510. << InputExpr->getType()
  11511. << Input.get()->getSourceRange());
  11512. }
  11513. }
  11514. // Diagnose operations on the unsupported types for OpenMP device compilation.
  11515. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
  11516. if (UnaryOperator::isIncrementDecrementOp(Opc) ||
  11517. UnaryOperator::isArithmeticOp(Opc))
  11518. checkOpenMPDeviceExpr(InputExpr);
  11519. }
  11520. switch (Opc) {
  11521. case UO_PreInc:
  11522. case UO_PreDec:
  11523. case UO_PostInc:
  11524. case UO_PostDec:
  11525. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  11526. OpLoc,
  11527. Opc == UO_PreInc ||
  11528. Opc == UO_PostInc,
  11529. Opc == UO_PreInc ||
  11530. Opc == UO_PreDec);
  11531. CanOverflow = isOverflowingIntegerType(Context, resultType);
  11532. break;
  11533. case UO_AddrOf:
  11534. resultType = CheckAddressOfOperand(Input, OpLoc);
  11535. CheckAddressOfNoDeref(InputExpr);
  11536. RecordModifiableNonNullParam(*this, InputExpr);
  11537. break;
  11538. case UO_Deref: {
  11539. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11540. if (Input.isInvalid()) return ExprError();
  11541. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  11542. break;
  11543. }
  11544. case UO_Plus:
  11545. case UO_Minus:
  11546. CanOverflow = Opc == UO_Minus &&
  11547. isOverflowingIntegerType(Context, Input.get()->getType());
  11548. Input = UsualUnaryConversions(Input.get());
  11549. if (Input.isInvalid()) return ExprError();
  11550. // Unary plus and minus require promoting an operand of half vector to a
  11551. // float vector and truncating the result back to a half vector. For now, we
  11552. // do this only when HalfArgsAndReturns is set (that is, when the target is
  11553. // arm or arm64).
  11554. ConvertHalfVec =
  11555. needsConversionOfHalfVec(true, Context, Input.get()->getType());
  11556. // If the operand is a half vector, promote it to a float vector.
  11557. if (ConvertHalfVec)
  11558. Input = convertVector(Input.get(), Context.FloatTy, *this);
  11559. resultType = Input.get()->getType();
  11560. if (resultType->isDependentType())
  11561. break;
  11562. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  11563. break;
  11564. else if (resultType->isVectorType() &&
  11565. // The z vector extensions don't allow + or - with bool vectors.
  11566. (!Context.getLangOpts().ZVector ||
  11567. resultType->getAs<VectorType>()->getVectorKind() !=
  11568. VectorType::AltiVecBool))
  11569. break;
  11570. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  11571. Opc == UO_Plus &&
  11572. resultType->isPointerType())
  11573. break;
  11574. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11575. << resultType << Input.get()->getSourceRange());
  11576. case UO_Not: // bitwise complement
  11577. Input = UsualUnaryConversions(Input.get());
  11578. if (Input.isInvalid())
  11579. return ExprError();
  11580. resultType = Input.get()->getType();
  11581. if (resultType->isDependentType())
  11582. break;
  11583. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  11584. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  11585. // C99 does not support '~' for complex conjugation.
  11586. Diag(OpLoc, diag::ext_integer_complement_complex)
  11587. << resultType << Input.get()->getSourceRange();
  11588. else if (resultType->hasIntegerRepresentation())
  11589. break;
  11590. else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
  11591. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  11592. // on vector float types.
  11593. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  11594. if (!T->isIntegerType())
  11595. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11596. << resultType << Input.get()->getSourceRange());
  11597. } else {
  11598. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11599. << resultType << Input.get()->getSourceRange());
  11600. }
  11601. break;
  11602. case UO_LNot: // logical negation
  11603. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  11604. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11605. if (Input.isInvalid()) return ExprError();
  11606. resultType = Input.get()->getType();
  11607. // Though we still have to promote half FP to float...
  11608. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  11609. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  11610. resultType = Context.FloatTy;
  11611. }
  11612. if (resultType->isDependentType())
  11613. break;
  11614. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  11615. // C99 6.5.3.3p1: ok, fallthrough;
  11616. if (Context.getLangOpts().CPlusPlus) {
  11617. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  11618. // operand contextually converted to bool.
  11619. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  11620. ScalarTypeToBooleanCastKind(resultType));
  11621. } else if (Context.getLangOpts().OpenCL &&
  11622. Context.getLangOpts().OpenCLVersion < 120) {
  11623. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  11624. // operate on scalar float types.
  11625. if (!resultType->isIntegerType() && !resultType->isPointerType())
  11626. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11627. << resultType << Input.get()->getSourceRange());
  11628. }
  11629. } else if (resultType->isExtVectorType()) {
  11630. if (Context.getLangOpts().OpenCL &&
  11631. Context.getLangOpts().OpenCLVersion < 120 &&
  11632. !Context.getLangOpts().OpenCLCPlusPlus) {
  11633. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  11634. // operate on vector float types.
  11635. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  11636. if (!T->isIntegerType())
  11637. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11638. << resultType << Input.get()->getSourceRange());
  11639. }
  11640. // Vector logical not returns the signed variant of the operand type.
  11641. resultType = GetSignedVectorType(resultType);
  11642. break;
  11643. } else {
  11644. // FIXME: GCC's vector extension permits the usage of '!' with a vector
  11645. // type in C++. We should allow that here too.
  11646. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11647. << resultType << Input.get()->getSourceRange());
  11648. }
  11649. // LNot always has type int. C99 6.5.3.3p5.
  11650. // In C++, it's bool. C++ 5.3.1p8
  11651. resultType = Context.getLogicalOperationType();
  11652. break;
  11653. case UO_Real:
  11654. case UO_Imag:
  11655. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  11656. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  11657. // complex l-values to ordinary l-values and all other values to r-values.
  11658. if (Input.isInvalid()) return ExprError();
  11659. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  11660. if (Input.get()->getValueKind() != VK_RValue &&
  11661. Input.get()->getObjectKind() == OK_Ordinary)
  11662. VK = Input.get()->getValueKind();
  11663. } else if (!getLangOpts().CPlusPlus) {
  11664. // In C, a volatile scalar is read by __imag. In C++, it is not.
  11665. Input = DefaultLvalueConversion(Input.get());
  11666. }
  11667. break;
  11668. case UO_Extension:
  11669. resultType = Input.get()->getType();
  11670. VK = Input.get()->getValueKind();
  11671. OK = Input.get()->getObjectKind();
  11672. break;
  11673. case UO_Coawait:
  11674. // It's unnecessary to represent the pass-through operator co_await in the
  11675. // AST; just return the input expression instead.
  11676. assert(!Input.get()->getType()->isDependentType() &&
  11677. "the co_await expression must be non-dependant before "
  11678. "building operator co_await");
  11679. return Input;
  11680. }
  11681. if (resultType.isNull() || Input.isInvalid())
  11682. return ExprError();
  11683. // Check for array bounds violations in the operand of the UnaryOperator,
  11684. // except for the '*' and '&' operators that have to be handled specially
  11685. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  11686. // that are explicitly defined as valid by the standard).
  11687. if (Opc != UO_AddrOf && Opc != UO_Deref)
  11688. CheckArrayAccess(Input.get());
  11689. auto *UO = new (Context)
  11690. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
  11691. if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
  11692. !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
  11693. ExprEvalContexts.back().PossibleDerefs.insert(UO);
  11694. // Convert the result back to a half vector.
  11695. if (ConvertHalfVec)
  11696. return convertVector(UO, Context.HalfTy, *this);
  11697. return UO;
  11698. }
  11699. /// Determine whether the given expression is a qualified member
  11700. /// access expression, of a form that could be turned into a pointer to member
  11701. /// with the address-of operator.
  11702. bool Sema::isQualifiedMemberAccess(Expr *E) {
  11703. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  11704. if (!DRE->getQualifier())
  11705. return false;
  11706. ValueDecl *VD = DRE->getDecl();
  11707. if (!VD->isCXXClassMember())
  11708. return false;
  11709. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  11710. return true;
  11711. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  11712. return Method->isInstance();
  11713. return false;
  11714. }
  11715. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  11716. if (!ULE->getQualifier())
  11717. return false;
  11718. for (NamedDecl *D : ULE->decls()) {
  11719. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  11720. if (Method->isInstance())
  11721. return true;
  11722. } else {
  11723. // Overload set does not contain methods.
  11724. break;
  11725. }
  11726. }
  11727. return false;
  11728. }
  11729. return false;
  11730. }
  11731. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  11732. UnaryOperatorKind Opc, Expr *Input) {
  11733. // First things first: handle placeholders so that the
  11734. // overloaded-operator check considers the right type.
  11735. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  11736. // Increment and decrement of pseudo-object references.
  11737. if (pty->getKind() == BuiltinType::PseudoObject &&
  11738. UnaryOperator::isIncrementDecrementOp(Opc))
  11739. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  11740. // extension is always a builtin operator.
  11741. if (Opc == UO_Extension)
  11742. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11743. // & gets special logic for several kinds of placeholder.
  11744. // The builtin code knows what to do.
  11745. if (Opc == UO_AddrOf &&
  11746. (pty->getKind() == BuiltinType::Overload ||
  11747. pty->getKind() == BuiltinType::UnknownAny ||
  11748. pty->getKind() == BuiltinType::BoundMember))
  11749. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11750. // Anything else needs to be handled now.
  11751. ExprResult Result = CheckPlaceholderExpr(Input);
  11752. if (Result.isInvalid()) return ExprError();
  11753. Input = Result.get();
  11754. }
  11755. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  11756. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  11757. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  11758. // Find all of the overloaded operators visible from this
  11759. // point. We perform both an operator-name lookup from the local
  11760. // scope and an argument-dependent lookup based on the types of
  11761. // the arguments.
  11762. UnresolvedSet<16> Functions;
  11763. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  11764. if (S && OverOp != OO_None)
  11765. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  11766. Functions);
  11767. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  11768. }
  11769. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11770. }
  11771. // Unary Operators. 'Tok' is the token for the operator.
  11772. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  11773. tok::TokenKind Op, Expr *Input) {
  11774. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  11775. }
  11776. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  11777. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  11778. LabelDecl *TheDecl) {
  11779. TheDecl->markUsed(Context);
  11780. // Create the AST node. The address of a label always has type 'void*'.
  11781. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  11782. Context.getPointerType(Context.VoidTy));
  11783. }
  11784. void Sema::ActOnStartStmtExpr() {
  11785. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11786. }
  11787. void Sema::ActOnStmtExprError() {
  11788. // Note that function is also called by TreeTransform when leaving a
  11789. // StmtExpr scope without rebuilding anything.
  11790. DiscardCleanupsInEvaluationContext();
  11791. PopExpressionEvaluationContext();
  11792. }
  11793. ExprResult
  11794. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  11795. SourceLocation RPLoc) { // "({..})"
  11796. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  11797. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  11798. if (hasAnyUnrecoverableErrorsInThisFunction())
  11799. DiscardCleanupsInEvaluationContext();
  11800. assert(!Cleanup.exprNeedsCleanups() &&
  11801. "cleanups within StmtExpr not correctly bound!");
  11802. PopExpressionEvaluationContext();
  11803. // FIXME: there are a variety of strange constraints to enforce here, for
  11804. // example, it is not possible to goto into a stmt expression apparently.
  11805. // More semantic analysis is needed.
  11806. // If there are sub-stmts in the compound stmt, take the type of the last one
  11807. // as the type of the stmtexpr.
  11808. QualType Ty = Context.VoidTy;
  11809. bool StmtExprMayBindToTemp = false;
  11810. if (!Compound->body_empty()) {
  11811. if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
  11812. if (const Expr *Value = LastStmt->getExprStmt()) {
  11813. StmtExprMayBindToTemp = true;
  11814. Ty = Value->getType();
  11815. }
  11816. }
  11817. }
  11818. // FIXME: Check that expression type is complete/non-abstract; statement
  11819. // expressions are not lvalues.
  11820. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  11821. if (StmtExprMayBindToTemp)
  11822. return MaybeBindToTemporary(ResStmtExpr);
  11823. return ResStmtExpr;
  11824. }
  11825. ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
  11826. if (ER.isInvalid())
  11827. return ExprError();
  11828. // Do function/array conversion on the last expression, but not
  11829. // lvalue-to-rvalue. However, initialize an unqualified type.
  11830. ER = DefaultFunctionArrayConversion(ER.get());
  11831. if (ER.isInvalid())
  11832. return ExprError();
  11833. Expr *E = ER.get();
  11834. if (E->isTypeDependent())
  11835. return E;
  11836. // In ARC, if the final expression ends in a consume, splice
  11837. // the consume out and bind it later. In the alternate case
  11838. // (when dealing with a retainable type), the result
  11839. // initialization will create a produce. In both cases the
  11840. // result will be +1, and we'll need to balance that out with
  11841. // a bind.
  11842. auto *Cast = dyn_cast<ImplicitCastExpr>(E);
  11843. if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
  11844. return Cast->getSubExpr();
  11845. // FIXME: Provide a better location for the initialization.
  11846. return PerformCopyInitialization(
  11847. InitializedEntity::InitializeStmtExprResult(
  11848. E->getBeginLoc(), E->getType().getUnqualifiedType()),
  11849. SourceLocation(), E);
  11850. }
  11851. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  11852. TypeSourceInfo *TInfo,
  11853. ArrayRef<OffsetOfComponent> Components,
  11854. SourceLocation RParenLoc) {
  11855. QualType ArgTy = TInfo->getType();
  11856. bool Dependent = ArgTy->isDependentType();
  11857. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  11858. // We must have at least one component that refers to the type, and the first
  11859. // one is known to be a field designator. Verify that the ArgTy represents
  11860. // a struct/union/class.
  11861. if (!Dependent && !ArgTy->isRecordType())
  11862. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  11863. << ArgTy << TypeRange);
  11864. // Type must be complete per C99 7.17p3 because a declaring a variable
  11865. // with an incomplete type would be ill-formed.
  11866. if (!Dependent
  11867. && RequireCompleteType(BuiltinLoc, ArgTy,
  11868. diag::err_offsetof_incomplete_type, TypeRange))
  11869. return ExprError();
  11870. bool DidWarnAboutNonPOD = false;
  11871. QualType CurrentType = ArgTy;
  11872. SmallVector<OffsetOfNode, 4> Comps;
  11873. SmallVector<Expr*, 4> Exprs;
  11874. for (const OffsetOfComponent &OC : Components) {
  11875. if (OC.isBrackets) {
  11876. // Offset of an array sub-field. TODO: Should we allow vector elements?
  11877. if (!CurrentType->isDependentType()) {
  11878. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  11879. if(!AT)
  11880. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  11881. << CurrentType);
  11882. CurrentType = AT->getElementType();
  11883. } else
  11884. CurrentType = Context.DependentTy;
  11885. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  11886. if (IdxRval.isInvalid())
  11887. return ExprError();
  11888. Expr *Idx = IdxRval.get();
  11889. // The expression must be an integral expression.
  11890. // FIXME: An integral constant expression?
  11891. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  11892. !Idx->getType()->isIntegerType())
  11893. return ExprError(
  11894. Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
  11895. << Idx->getSourceRange());
  11896. // Record this array index.
  11897. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  11898. Exprs.push_back(Idx);
  11899. continue;
  11900. }
  11901. // Offset of a field.
  11902. if (CurrentType->isDependentType()) {
  11903. // We have the offset of a field, but we can't look into the dependent
  11904. // type. Just record the identifier of the field.
  11905. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  11906. CurrentType = Context.DependentTy;
  11907. continue;
  11908. }
  11909. // We need to have a complete type to look into.
  11910. if (RequireCompleteType(OC.LocStart, CurrentType,
  11911. diag::err_offsetof_incomplete_type))
  11912. return ExprError();
  11913. // Look for the designated field.
  11914. const RecordType *RC = CurrentType->getAs<RecordType>();
  11915. if (!RC)
  11916. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  11917. << CurrentType);
  11918. RecordDecl *RD = RC->getDecl();
  11919. // C++ [lib.support.types]p5:
  11920. // The macro offsetof accepts a restricted set of type arguments in this
  11921. // International Standard. type shall be a POD structure or a POD union
  11922. // (clause 9).
  11923. // C++11 [support.types]p4:
  11924. // If type is not a standard-layout class (Clause 9), the results are
  11925. // undefined.
  11926. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  11927. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  11928. unsigned DiagID =
  11929. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  11930. : diag::ext_offsetof_non_pod_type;
  11931. if (!IsSafe && !DidWarnAboutNonPOD &&
  11932. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  11933. PDiag(DiagID)
  11934. << SourceRange(Components[0].LocStart, OC.LocEnd)
  11935. << CurrentType))
  11936. DidWarnAboutNonPOD = true;
  11937. }
  11938. // Look for the field.
  11939. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  11940. LookupQualifiedName(R, RD);
  11941. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  11942. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  11943. if (!MemberDecl) {
  11944. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  11945. MemberDecl = IndirectMemberDecl->getAnonField();
  11946. }
  11947. if (!MemberDecl)
  11948. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  11949. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  11950. OC.LocEnd));
  11951. // C99 7.17p3:
  11952. // (If the specified member is a bit-field, the behavior is undefined.)
  11953. //
  11954. // We diagnose this as an error.
  11955. if (MemberDecl->isBitField()) {
  11956. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  11957. << MemberDecl->getDeclName()
  11958. << SourceRange(BuiltinLoc, RParenLoc);
  11959. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  11960. return ExprError();
  11961. }
  11962. RecordDecl *Parent = MemberDecl->getParent();
  11963. if (IndirectMemberDecl)
  11964. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  11965. // If the member was found in a base class, introduce OffsetOfNodes for
  11966. // the base class indirections.
  11967. CXXBasePaths Paths;
  11968. if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
  11969. Paths)) {
  11970. if (Paths.getDetectedVirtual()) {
  11971. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  11972. << MemberDecl->getDeclName()
  11973. << SourceRange(BuiltinLoc, RParenLoc);
  11974. return ExprError();
  11975. }
  11976. CXXBasePath &Path = Paths.front();
  11977. for (const CXXBasePathElement &B : Path)
  11978. Comps.push_back(OffsetOfNode(B.Base));
  11979. }
  11980. if (IndirectMemberDecl) {
  11981. for (auto *FI : IndirectMemberDecl->chain()) {
  11982. assert(isa<FieldDecl>(FI));
  11983. Comps.push_back(OffsetOfNode(OC.LocStart,
  11984. cast<FieldDecl>(FI), OC.LocEnd));
  11985. }
  11986. } else
  11987. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  11988. CurrentType = MemberDecl->getType().getNonReferenceType();
  11989. }
  11990. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  11991. Comps, Exprs, RParenLoc);
  11992. }
  11993. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  11994. SourceLocation BuiltinLoc,
  11995. SourceLocation TypeLoc,
  11996. ParsedType ParsedArgTy,
  11997. ArrayRef<OffsetOfComponent> Components,
  11998. SourceLocation RParenLoc) {
  11999. TypeSourceInfo *ArgTInfo;
  12000. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  12001. if (ArgTy.isNull())
  12002. return ExprError();
  12003. if (!ArgTInfo)
  12004. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  12005. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
  12006. }
  12007. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  12008. Expr *CondExpr,
  12009. Expr *LHSExpr, Expr *RHSExpr,
  12010. SourceLocation RPLoc) {
  12011. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  12012. ExprValueKind VK = VK_RValue;
  12013. ExprObjectKind OK = OK_Ordinary;
  12014. QualType resType;
  12015. bool ValueDependent = false;
  12016. bool CondIsTrue = false;
  12017. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  12018. resType = Context.DependentTy;
  12019. ValueDependent = true;
  12020. } else {
  12021. // The conditional expression is required to be a constant expression.
  12022. llvm::APSInt condEval(32);
  12023. ExprResult CondICE
  12024. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  12025. diag::err_typecheck_choose_expr_requires_constant, false);
  12026. if (CondICE.isInvalid())
  12027. return ExprError();
  12028. CondExpr = CondICE.get();
  12029. CondIsTrue = condEval.getZExtValue();
  12030. // If the condition is > zero, then the AST type is the same as the LHSExpr.
  12031. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  12032. resType = ActiveExpr->getType();
  12033. ValueDependent = ActiveExpr->isValueDependent();
  12034. VK = ActiveExpr->getValueKind();
  12035. OK = ActiveExpr->getObjectKind();
  12036. }
  12037. return new (Context)
  12038. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  12039. CondIsTrue, resType->isDependentType(), ValueDependent);
  12040. }
  12041. //===----------------------------------------------------------------------===//
  12042. // Clang Extensions.
  12043. //===----------------------------------------------------------------------===//
  12044. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  12045. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  12046. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  12047. if (LangOpts.CPlusPlus) {
  12048. Decl *ManglingContextDecl;
  12049. if (MangleNumberingContext *MCtx =
  12050. getCurrentMangleNumberContext(Block->getDeclContext(),
  12051. ManglingContextDecl)) {
  12052. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  12053. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  12054. }
  12055. }
  12056. PushBlockScope(CurScope, Block);
  12057. CurContext->addDecl(Block);
  12058. if (CurScope)
  12059. PushDeclContext(CurScope, Block);
  12060. else
  12061. CurContext = Block;
  12062. getCurBlock()->HasImplicitReturnType = true;
  12063. // Enter a new evaluation context to insulate the block from any
  12064. // cleanups from the enclosing full-expression.
  12065. PushExpressionEvaluationContext(
  12066. ExpressionEvaluationContext::PotentiallyEvaluated);
  12067. }
  12068. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  12069. Scope *CurScope) {
  12070. assert(ParamInfo.getIdentifier() == nullptr &&
  12071. "block-id should have no identifier!");
  12072. assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
  12073. BlockScopeInfo *CurBlock = getCurBlock();
  12074. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  12075. QualType T = Sig->getType();
  12076. // FIXME: We should allow unexpanded parameter packs here, but that would,
  12077. // in turn, make the block expression contain unexpanded parameter packs.
  12078. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  12079. // Drop the parameters.
  12080. FunctionProtoType::ExtProtoInfo EPI;
  12081. EPI.HasTrailingReturn = false;
  12082. EPI.TypeQuals.addConst();
  12083. T = Context.getFunctionType(Context.DependentTy, None, EPI);
  12084. Sig = Context.getTrivialTypeSourceInfo(T);
  12085. }
  12086. // GetTypeForDeclarator always produces a function type for a block
  12087. // literal signature. Furthermore, it is always a FunctionProtoType
  12088. // unless the function was written with a typedef.
  12089. assert(T->isFunctionType() &&
  12090. "GetTypeForDeclarator made a non-function block signature");
  12091. // Look for an explicit signature in that function type.
  12092. FunctionProtoTypeLoc ExplicitSignature;
  12093. if ((ExplicitSignature = Sig->getTypeLoc()
  12094. .getAsAdjusted<FunctionProtoTypeLoc>())) {
  12095. // Check whether that explicit signature was synthesized by
  12096. // GetTypeForDeclarator. If so, don't save that as part of the
  12097. // written signature.
  12098. if (ExplicitSignature.getLocalRangeBegin() ==
  12099. ExplicitSignature.getLocalRangeEnd()) {
  12100. // This would be much cheaper if we stored TypeLocs instead of
  12101. // TypeSourceInfos.
  12102. TypeLoc Result = ExplicitSignature.getReturnLoc();
  12103. unsigned Size = Result.getFullDataSize();
  12104. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  12105. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  12106. ExplicitSignature = FunctionProtoTypeLoc();
  12107. }
  12108. }
  12109. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  12110. CurBlock->FunctionType = T;
  12111. const FunctionType *Fn = T->getAs<FunctionType>();
  12112. QualType RetTy = Fn->getReturnType();
  12113. bool isVariadic =
  12114. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  12115. CurBlock->TheDecl->setIsVariadic(isVariadic);
  12116. // Context.DependentTy is used as a placeholder for a missing block
  12117. // return type. TODO: what should we do with declarators like:
  12118. // ^ * { ... }
  12119. // If the answer is "apply template argument deduction"....
  12120. if (RetTy != Context.DependentTy) {
  12121. CurBlock->ReturnType = RetTy;
  12122. CurBlock->TheDecl->setBlockMissingReturnType(false);
  12123. CurBlock->HasImplicitReturnType = false;
  12124. }
  12125. // Push block parameters from the declarator if we had them.
  12126. SmallVector<ParmVarDecl*, 8> Params;
  12127. if (ExplicitSignature) {
  12128. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  12129. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  12130. if (Param->getIdentifier() == nullptr &&
  12131. !Param->isImplicit() &&
  12132. !Param->isInvalidDecl() &&
  12133. !getLangOpts().CPlusPlus)
  12134. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  12135. Params.push_back(Param);
  12136. }
  12137. // Fake up parameter variables if we have a typedef, like
  12138. // ^ fntype { ... }
  12139. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  12140. for (const auto &I : Fn->param_types()) {
  12141. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  12142. CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
  12143. Params.push_back(Param);
  12144. }
  12145. }
  12146. // Set the parameters on the block decl.
  12147. if (!Params.empty()) {
  12148. CurBlock->TheDecl->setParams(Params);
  12149. CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
  12150. /*CheckParameterNames=*/false);
  12151. }
  12152. // Finally we can process decl attributes.
  12153. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  12154. // Put the parameter variables in scope.
  12155. for (auto AI : CurBlock->TheDecl->parameters()) {
  12156. AI->setOwningFunction(CurBlock->TheDecl);
  12157. // If this has an identifier, add it to the scope stack.
  12158. if (AI->getIdentifier()) {
  12159. CheckShadow(CurBlock->TheScope, AI);
  12160. PushOnScopeChains(AI, CurBlock->TheScope);
  12161. }
  12162. }
  12163. }
  12164. /// ActOnBlockError - If there is an error parsing a block, this callback
  12165. /// is invoked to pop the information about the block from the action impl.
  12166. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  12167. // Leave the expression-evaluation context.
  12168. DiscardCleanupsInEvaluationContext();
  12169. PopExpressionEvaluationContext();
  12170. // Pop off CurBlock, handle nested blocks.
  12171. PopDeclContext();
  12172. PopFunctionScopeInfo();
  12173. }
  12174. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  12175. /// literal was successfully completed. ^(int x){...}
  12176. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  12177. Stmt *Body, Scope *CurScope) {
  12178. // If blocks are disabled, emit an error.
  12179. if (!LangOpts.Blocks)
  12180. Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
  12181. // Leave the expression-evaluation context.
  12182. if (hasAnyUnrecoverableErrorsInThisFunction())
  12183. DiscardCleanupsInEvaluationContext();
  12184. assert(!Cleanup.exprNeedsCleanups() &&
  12185. "cleanups within block not correctly bound!");
  12186. PopExpressionEvaluationContext();
  12187. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  12188. BlockDecl *BD = BSI->TheDecl;
  12189. if (BSI->HasImplicitReturnType)
  12190. deduceClosureReturnType(*BSI);
  12191. QualType RetTy = Context.VoidTy;
  12192. if (!BSI->ReturnType.isNull())
  12193. RetTy = BSI->ReturnType;
  12194. bool NoReturn = BD->hasAttr<NoReturnAttr>();
  12195. QualType BlockTy;
  12196. // If the user wrote a function type in some form, try to use that.
  12197. if (!BSI->FunctionType.isNull()) {
  12198. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  12199. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  12200. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  12201. // Turn protoless block types into nullary block types.
  12202. if (isa<FunctionNoProtoType>(FTy)) {
  12203. FunctionProtoType::ExtProtoInfo EPI;
  12204. EPI.ExtInfo = Ext;
  12205. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  12206. // Otherwise, if we don't need to change anything about the function type,
  12207. // preserve its sugar structure.
  12208. } else if (FTy->getReturnType() == RetTy &&
  12209. (!NoReturn || FTy->getNoReturnAttr())) {
  12210. BlockTy = BSI->FunctionType;
  12211. // Otherwise, make the minimal modifications to the function type.
  12212. } else {
  12213. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  12214. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  12215. EPI.TypeQuals = Qualifiers();
  12216. EPI.ExtInfo = Ext;
  12217. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  12218. }
  12219. // If we don't have a function type, just build one from nothing.
  12220. } else {
  12221. FunctionProtoType::ExtProtoInfo EPI;
  12222. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  12223. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  12224. }
  12225. DiagnoseUnusedParameters(BD->parameters());
  12226. BlockTy = Context.getBlockPointerType(BlockTy);
  12227. // If needed, diagnose invalid gotos and switches in the block.
  12228. if (getCurFunction()->NeedsScopeChecking() &&
  12229. !PP.isCodeCompletionEnabled())
  12230. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  12231. BD->setBody(cast<CompoundStmt>(Body));
  12232. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  12233. DiagnoseUnguardedAvailabilityViolations(BD);
  12234. // Try to apply the named return value optimization. We have to check again
  12235. // if we can do this, though, because blocks keep return statements around
  12236. // to deduce an implicit return type.
  12237. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  12238. !BD->isDependentContext())
  12239. computeNRVO(Body, BSI);
  12240. PopDeclContext();
  12241. // Pop the block scope now but keep it alive to the end of this function.
  12242. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  12243. PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
  12244. // Set the captured variables on the block.
  12245. SmallVector<BlockDecl::Capture, 4> Captures;
  12246. for (Capture &Cap : BSI->Captures) {
  12247. if (Cap.isInvalid() || Cap.isThisCapture())
  12248. continue;
  12249. VarDecl *Var = Cap.getVariable();
  12250. Expr *CopyExpr = nullptr;
  12251. if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
  12252. if (const RecordType *Record =
  12253. Cap.getCaptureType()->getAs<RecordType>()) {
  12254. // The capture logic needs the destructor, so make sure we mark it.
  12255. // Usually this is unnecessary because most local variables have
  12256. // their destructors marked at declaration time, but parameters are
  12257. // an exception because it's technically only the call site that
  12258. // actually requires the destructor.
  12259. if (isa<ParmVarDecl>(Var))
  12260. FinalizeVarWithDestructor(Var, Record);
  12261. // Enter a separate potentially-evaluated context while building block
  12262. // initializers to isolate their cleanups from those of the block
  12263. // itself.
  12264. // FIXME: Is this appropriate even when the block itself occurs in an
  12265. // unevaluated operand?
  12266. EnterExpressionEvaluationContext EvalContext(
  12267. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  12268. SourceLocation Loc = Cap.getLocation();
  12269. ExprResult Result = BuildDeclarationNameExpr(
  12270. CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
  12271. // According to the blocks spec, the capture of a variable from
  12272. // the stack requires a const copy constructor. This is not true
  12273. // of the copy/move done to move a __block variable to the heap.
  12274. if (!Result.isInvalid() &&
  12275. !Result.get()->getType().isConstQualified()) {
  12276. Result = ImpCastExprToType(Result.get(),
  12277. Result.get()->getType().withConst(),
  12278. CK_NoOp, VK_LValue);
  12279. }
  12280. if (!Result.isInvalid()) {
  12281. Result = PerformCopyInitialization(
  12282. InitializedEntity::InitializeBlock(Var->getLocation(),
  12283. Cap.getCaptureType(), false),
  12284. Loc, Result.get());
  12285. }
  12286. // Build a full-expression copy expression if initialization
  12287. // succeeded and used a non-trivial constructor. Recover from
  12288. // errors by pretending that the copy isn't necessary.
  12289. if (!Result.isInvalid() &&
  12290. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  12291. ->isTrivial()) {
  12292. Result = MaybeCreateExprWithCleanups(Result);
  12293. CopyExpr = Result.get();
  12294. }
  12295. }
  12296. }
  12297. BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
  12298. CopyExpr);
  12299. Captures.push_back(NewCap);
  12300. }
  12301. BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
  12302. BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
  12303. // If the block isn't obviously global, i.e. it captures anything at
  12304. // all, then we need to do a few things in the surrounding context:
  12305. if (Result->getBlockDecl()->hasCaptures()) {
  12306. // First, this expression has a new cleanup object.
  12307. ExprCleanupObjects.push_back(Result->getBlockDecl());
  12308. Cleanup.setExprNeedsCleanups(true);
  12309. // It also gets a branch-protected scope if any of the captured
  12310. // variables needs destruction.
  12311. for (const auto &CI : Result->getBlockDecl()->captures()) {
  12312. const VarDecl *var = CI.getVariable();
  12313. if (var->getType().isDestructedType() != QualType::DK_none) {
  12314. setFunctionHasBranchProtectedScope();
  12315. break;
  12316. }
  12317. }
  12318. }
  12319. if (getCurFunction())
  12320. getCurFunction()->addBlock(BD);
  12321. return Result;
  12322. }
  12323. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
  12324. SourceLocation RPLoc) {
  12325. TypeSourceInfo *TInfo;
  12326. GetTypeFromParser(Ty, &TInfo);
  12327. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  12328. }
  12329. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  12330. Expr *E, TypeSourceInfo *TInfo,
  12331. SourceLocation RPLoc) {
  12332. Expr *OrigExpr = E;
  12333. bool IsMS = false;
  12334. // CUDA device code does not support varargs.
  12335. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  12336. if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
  12337. CUDAFunctionTarget T = IdentifyCUDATarget(F);
  12338. if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
  12339. return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
  12340. }
  12341. }
  12342. // NVPTX does not support va_arg expression.
  12343. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  12344. Context.getTargetInfo().getTriple().isNVPTX())
  12345. targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
  12346. // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
  12347. // as Microsoft ABI on an actual Microsoft platform, where
  12348. // __builtin_ms_va_list and __builtin_va_list are the same.)
  12349. if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
  12350. Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
  12351. QualType MSVaListType = Context.getBuiltinMSVaListType();
  12352. if (Context.hasSameType(MSVaListType, E->getType())) {
  12353. if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12354. return ExprError();
  12355. IsMS = true;
  12356. }
  12357. }
  12358. // Get the va_list type
  12359. QualType VaListType = Context.getBuiltinVaListType();
  12360. if (!IsMS) {
  12361. if (VaListType->isArrayType()) {
  12362. // Deal with implicit array decay; for example, on x86-64,
  12363. // va_list is an array, but it's supposed to decay to
  12364. // a pointer for va_arg.
  12365. VaListType = Context.getArrayDecayedType(VaListType);
  12366. // Make sure the input expression also decays appropriately.
  12367. ExprResult Result = UsualUnaryConversions(E);
  12368. if (Result.isInvalid())
  12369. return ExprError();
  12370. E = Result.get();
  12371. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  12372. // If va_list is a record type and we are compiling in C++ mode,
  12373. // check the argument using reference binding.
  12374. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  12375. Context, Context.getLValueReferenceType(VaListType), false);
  12376. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  12377. if (Init.isInvalid())
  12378. return ExprError();
  12379. E = Init.getAs<Expr>();
  12380. } else {
  12381. // Otherwise, the va_list argument must be an l-value because
  12382. // it is modified by va_arg.
  12383. if (!E->isTypeDependent() &&
  12384. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12385. return ExprError();
  12386. }
  12387. }
  12388. if (!IsMS && !E->isTypeDependent() &&
  12389. !Context.hasSameType(VaListType, E->getType()))
  12390. return ExprError(
  12391. Diag(E->getBeginLoc(),
  12392. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  12393. << OrigExpr->getType() << E->getSourceRange());
  12394. if (!TInfo->getType()->isDependentType()) {
  12395. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  12396. diag::err_second_parameter_to_va_arg_incomplete,
  12397. TInfo->getTypeLoc()))
  12398. return ExprError();
  12399. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  12400. TInfo->getType(),
  12401. diag::err_second_parameter_to_va_arg_abstract,
  12402. TInfo->getTypeLoc()))
  12403. return ExprError();
  12404. if (!TInfo->getType().isPODType(Context)) {
  12405. Diag(TInfo->getTypeLoc().getBeginLoc(),
  12406. TInfo->getType()->isObjCLifetimeType()
  12407. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  12408. : diag::warn_second_parameter_to_va_arg_not_pod)
  12409. << TInfo->getType()
  12410. << TInfo->getTypeLoc().getSourceRange();
  12411. }
  12412. // Check for va_arg where arguments of the given type will be promoted
  12413. // (i.e. this va_arg is guaranteed to have undefined behavior).
  12414. QualType PromoteType;
  12415. if (TInfo->getType()->isPromotableIntegerType()) {
  12416. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  12417. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  12418. PromoteType = QualType();
  12419. }
  12420. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  12421. PromoteType = Context.DoubleTy;
  12422. if (!PromoteType.isNull())
  12423. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  12424. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  12425. << TInfo->getType()
  12426. << PromoteType
  12427. << TInfo->getTypeLoc().getSourceRange());
  12428. }
  12429. QualType T = TInfo->getType().getNonLValueExprType(Context);
  12430. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
  12431. }
  12432. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  12433. // The type of __null will be int or long, depending on the size of
  12434. // pointers on the target.
  12435. QualType Ty;
  12436. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  12437. if (pw == Context.getTargetInfo().getIntWidth())
  12438. Ty = Context.IntTy;
  12439. else if (pw == Context.getTargetInfo().getLongWidth())
  12440. Ty = Context.LongTy;
  12441. else if (pw == Context.getTargetInfo().getLongLongWidth())
  12442. Ty = Context.LongLongTy;
  12443. else {
  12444. llvm_unreachable("I don't know size of pointer!");
  12445. }
  12446. return new (Context) GNUNullExpr(Ty, TokenLoc);
  12447. }
  12448. ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
  12449. SourceLocation BuiltinLoc,
  12450. SourceLocation RPLoc) {
  12451. return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
  12452. }
  12453. ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
  12454. SourceLocation BuiltinLoc,
  12455. SourceLocation RPLoc,
  12456. DeclContext *ParentContext) {
  12457. return new (Context)
  12458. SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
  12459. }
  12460. bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
  12461. bool Diagnose) {
  12462. if (!getLangOpts().ObjC)
  12463. return false;
  12464. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  12465. if (!PT)
  12466. return false;
  12467. if (!PT->isObjCIdType()) {
  12468. // Check if the destination is the 'NSString' interface.
  12469. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  12470. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  12471. return false;
  12472. }
  12473. // Ignore any parens, implicit casts (should only be
  12474. // array-to-pointer decays), and not-so-opaque values. The last is
  12475. // important for making this trigger for property assignments.
  12476. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  12477. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  12478. if (OV->getSourceExpr())
  12479. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  12480. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  12481. if (!SL || !SL->isAscii())
  12482. return false;
  12483. if (Diagnose) {
  12484. Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
  12485. << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
  12486. Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
  12487. }
  12488. return true;
  12489. }
  12490. static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
  12491. const Expr *SrcExpr) {
  12492. if (!DstType->isFunctionPointerType() ||
  12493. !SrcExpr->getType()->isFunctionType())
  12494. return false;
  12495. auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
  12496. if (!DRE)
  12497. return false;
  12498. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  12499. if (!FD)
  12500. return false;
  12501. return !S.checkAddressOfFunctionIsAvailable(FD,
  12502. /*Complain=*/true,
  12503. SrcExpr->getBeginLoc());
  12504. }
  12505. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  12506. SourceLocation Loc,
  12507. QualType DstType, QualType SrcType,
  12508. Expr *SrcExpr, AssignmentAction Action,
  12509. bool *Complained) {
  12510. if (Complained)
  12511. *Complained = false;
  12512. // Decode the result (notice that AST's are still created for extensions).
  12513. bool CheckInferredResultType = false;
  12514. bool isInvalid = false;
  12515. unsigned DiagKind = 0;
  12516. FixItHint Hint;
  12517. ConversionFixItGenerator ConvHints;
  12518. bool MayHaveConvFixit = false;
  12519. bool MayHaveFunctionDiff = false;
  12520. const ObjCInterfaceDecl *IFace = nullptr;
  12521. const ObjCProtocolDecl *PDecl = nullptr;
  12522. switch (ConvTy) {
  12523. case Compatible:
  12524. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  12525. return false;
  12526. case PointerToInt:
  12527. DiagKind = diag::ext_typecheck_convert_pointer_int;
  12528. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12529. MayHaveConvFixit = true;
  12530. break;
  12531. case IntToPointer:
  12532. DiagKind = diag::ext_typecheck_convert_int_pointer;
  12533. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12534. MayHaveConvFixit = true;
  12535. break;
  12536. case IncompatiblePointer:
  12537. if (Action == AA_Passing_CFAudited)
  12538. DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
  12539. else if (SrcType->isFunctionPointerType() &&
  12540. DstType->isFunctionPointerType())
  12541. DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
  12542. else
  12543. DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
  12544. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  12545. SrcType->isObjCObjectPointerType();
  12546. if (Hint.isNull() && !CheckInferredResultType) {
  12547. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12548. }
  12549. else if (CheckInferredResultType) {
  12550. SrcType = SrcType.getUnqualifiedType();
  12551. DstType = DstType.getUnqualifiedType();
  12552. }
  12553. MayHaveConvFixit = true;
  12554. break;
  12555. case IncompatiblePointerSign:
  12556. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  12557. break;
  12558. case FunctionVoidPointer:
  12559. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  12560. break;
  12561. case IncompatiblePointerDiscardsQualifiers: {
  12562. // Perform array-to-pointer decay if necessary.
  12563. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  12564. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  12565. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  12566. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  12567. DiagKind = diag::err_typecheck_incompatible_address_space;
  12568. break;
  12569. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  12570. DiagKind = diag::err_typecheck_incompatible_ownership;
  12571. break;
  12572. }
  12573. llvm_unreachable("unknown error case for discarding qualifiers!");
  12574. // fallthrough
  12575. }
  12576. case CompatiblePointerDiscardsQualifiers:
  12577. // If the qualifiers lost were because we were applying the
  12578. // (deprecated) C++ conversion from a string literal to a char*
  12579. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  12580. // Ideally, this check would be performed in
  12581. // checkPointerTypesForAssignment. However, that would require a
  12582. // bit of refactoring (so that the second argument is an
  12583. // expression, rather than a type), which should be done as part
  12584. // of a larger effort to fix checkPointerTypesForAssignment for
  12585. // C++ semantics.
  12586. if (getLangOpts().CPlusPlus &&
  12587. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  12588. return false;
  12589. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  12590. break;
  12591. case IncompatibleNestedPointerQualifiers:
  12592. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  12593. break;
  12594. case IncompatibleNestedPointerAddressSpaceMismatch:
  12595. DiagKind = diag::err_typecheck_incompatible_nested_address_space;
  12596. break;
  12597. case IntToBlockPointer:
  12598. DiagKind = diag::err_int_to_block_pointer;
  12599. break;
  12600. case IncompatibleBlockPointer:
  12601. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  12602. break;
  12603. case IncompatibleObjCQualifiedId: {
  12604. if (SrcType->isObjCQualifiedIdType()) {
  12605. const ObjCObjectPointerType *srcOPT =
  12606. SrcType->getAs<ObjCObjectPointerType>();
  12607. for (auto *srcProto : srcOPT->quals()) {
  12608. PDecl = srcProto;
  12609. break;
  12610. }
  12611. if (const ObjCInterfaceType *IFaceT =
  12612. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  12613. IFace = IFaceT->getDecl();
  12614. }
  12615. else if (DstType->isObjCQualifiedIdType()) {
  12616. const ObjCObjectPointerType *dstOPT =
  12617. DstType->getAs<ObjCObjectPointerType>();
  12618. for (auto *dstProto : dstOPT->quals()) {
  12619. PDecl = dstProto;
  12620. break;
  12621. }
  12622. if (const ObjCInterfaceType *IFaceT =
  12623. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  12624. IFace = IFaceT->getDecl();
  12625. }
  12626. DiagKind = diag::warn_incompatible_qualified_id;
  12627. break;
  12628. }
  12629. case IncompatibleVectors:
  12630. DiagKind = diag::warn_incompatible_vectors;
  12631. break;
  12632. case IncompatibleObjCWeakRef:
  12633. DiagKind = diag::err_arc_weak_unavailable_assign;
  12634. break;
  12635. case Incompatible:
  12636. if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
  12637. if (Complained)
  12638. *Complained = true;
  12639. return true;
  12640. }
  12641. DiagKind = diag::err_typecheck_convert_incompatible;
  12642. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12643. MayHaveConvFixit = true;
  12644. isInvalid = true;
  12645. MayHaveFunctionDiff = true;
  12646. break;
  12647. }
  12648. QualType FirstType, SecondType;
  12649. switch (Action) {
  12650. case AA_Assigning:
  12651. case AA_Initializing:
  12652. // The destination type comes first.
  12653. FirstType = DstType;
  12654. SecondType = SrcType;
  12655. break;
  12656. case AA_Returning:
  12657. case AA_Passing:
  12658. case AA_Passing_CFAudited:
  12659. case AA_Converting:
  12660. case AA_Sending:
  12661. case AA_Casting:
  12662. // The source type comes first.
  12663. FirstType = SrcType;
  12664. SecondType = DstType;
  12665. break;
  12666. }
  12667. PartialDiagnostic FDiag = PDiag(DiagKind);
  12668. if (Action == AA_Passing_CFAudited)
  12669. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  12670. else
  12671. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  12672. // If we can fix the conversion, suggest the FixIts.
  12673. assert(ConvHints.isNull() || Hint.isNull());
  12674. if (!ConvHints.isNull()) {
  12675. for (FixItHint &H : ConvHints.Hints)
  12676. FDiag << H;
  12677. } else {
  12678. FDiag << Hint;
  12679. }
  12680. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  12681. if (MayHaveFunctionDiff)
  12682. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  12683. Diag(Loc, FDiag);
  12684. if (DiagKind == diag::warn_incompatible_qualified_id &&
  12685. PDecl && IFace && !IFace->hasDefinition())
  12686. Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
  12687. << IFace << PDecl;
  12688. if (SecondType == Context.OverloadTy)
  12689. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  12690. FirstType, /*TakingAddress=*/true);
  12691. if (CheckInferredResultType)
  12692. EmitRelatedResultTypeNote(SrcExpr);
  12693. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  12694. EmitRelatedResultTypeNoteForReturn(DstType);
  12695. if (Complained)
  12696. *Complained = true;
  12697. return isInvalid;
  12698. }
  12699. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  12700. llvm::APSInt *Result) {
  12701. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  12702. public:
  12703. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  12704. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  12705. }
  12706. } Diagnoser;
  12707. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  12708. }
  12709. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  12710. llvm::APSInt *Result,
  12711. unsigned DiagID,
  12712. bool AllowFold) {
  12713. class IDDiagnoser : public VerifyICEDiagnoser {
  12714. unsigned DiagID;
  12715. public:
  12716. IDDiagnoser(unsigned DiagID)
  12717. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  12718. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  12719. S.Diag(Loc, DiagID) << SR;
  12720. }
  12721. } Diagnoser(DiagID);
  12722. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  12723. }
  12724. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  12725. SourceRange SR) {
  12726. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  12727. }
  12728. ExprResult
  12729. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  12730. VerifyICEDiagnoser &Diagnoser,
  12731. bool AllowFold) {
  12732. SourceLocation DiagLoc = E->getBeginLoc();
  12733. if (getLangOpts().CPlusPlus11) {
  12734. // C++11 [expr.const]p5:
  12735. // If an expression of literal class type is used in a context where an
  12736. // integral constant expression is required, then that class type shall
  12737. // have a single non-explicit conversion function to an integral or
  12738. // unscoped enumeration type
  12739. ExprResult Converted;
  12740. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  12741. public:
  12742. CXX11ConvertDiagnoser(bool Silent)
  12743. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  12744. Silent, true) {}
  12745. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  12746. QualType T) override {
  12747. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  12748. }
  12749. SemaDiagnosticBuilder diagnoseIncomplete(
  12750. Sema &S, SourceLocation Loc, QualType T) override {
  12751. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  12752. }
  12753. SemaDiagnosticBuilder diagnoseExplicitConv(
  12754. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  12755. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  12756. }
  12757. SemaDiagnosticBuilder noteExplicitConv(
  12758. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  12759. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  12760. << ConvTy->isEnumeralType() << ConvTy;
  12761. }
  12762. SemaDiagnosticBuilder diagnoseAmbiguous(
  12763. Sema &S, SourceLocation Loc, QualType T) override {
  12764. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  12765. }
  12766. SemaDiagnosticBuilder noteAmbiguous(
  12767. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  12768. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  12769. << ConvTy->isEnumeralType() << ConvTy;
  12770. }
  12771. SemaDiagnosticBuilder diagnoseConversion(
  12772. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  12773. llvm_unreachable("conversion functions are permitted");
  12774. }
  12775. } ConvertDiagnoser(Diagnoser.Suppress);
  12776. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  12777. ConvertDiagnoser);
  12778. if (Converted.isInvalid())
  12779. return Converted;
  12780. E = Converted.get();
  12781. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  12782. return ExprError();
  12783. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  12784. // An ICE must be of integral or unscoped enumeration type.
  12785. if (!Diagnoser.Suppress)
  12786. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  12787. return ExprError();
  12788. }
  12789. if (!isa<ConstantExpr>(E))
  12790. E = ConstantExpr::Create(Context, E);
  12791. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  12792. // in the non-ICE case.
  12793. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  12794. if (Result)
  12795. *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
  12796. return E;
  12797. }
  12798. Expr::EvalResult EvalResult;
  12799. SmallVector<PartialDiagnosticAt, 8> Notes;
  12800. EvalResult.Diag = &Notes;
  12801. // Try to evaluate the expression, and produce diagnostics explaining why it's
  12802. // not a constant expression as a side-effect.
  12803. bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
  12804. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  12805. // In C++11, we can rely on diagnostics being produced for any expression
  12806. // which is not a constant expression. If no diagnostics were produced, then
  12807. // this is a constant expression.
  12808. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  12809. if (Result)
  12810. *Result = EvalResult.Val.getInt();
  12811. return E;
  12812. }
  12813. // If our only note is the usual "invalid subexpression" note, just point
  12814. // the caret at its location rather than producing an essentially
  12815. // redundant note.
  12816. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  12817. diag::note_invalid_subexpr_in_const_expr) {
  12818. DiagLoc = Notes[0].first;
  12819. Notes.clear();
  12820. }
  12821. if (!Folded || !AllowFold) {
  12822. if (!Diagnoser.Suppress) {
  12823. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  12824. for (const PartialDiagnosticAt &Note : Notes)
  12825. Diag(Note.first, Note.second);
  12826. }
  12827. return ExprError();
  12828. }
  12829. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  12830. for (const PartialDiagnosticAt &Note : Notes)
  12831. Diag(Note.first, Note.second);
  12832. if (Result)
  12833. *Result = EvalResult.Val.getInt();
  12834. return E;
  12835. }
  12836. namespace {
  12837. // Handle the case where we conclude a expression which we speculatively
  12838. // considered to be unevaluated is actually evaluated.
  12839. class TransformToPE : public TreeTransform<TransformToPE> {
  12840. typedef TreeTransform<TransformToPE> BaseTransform;
  12841. public:
  12842. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  12843. // Make sure we redo semantic analysis
  12844. bool AlwaysRebuild() { return true; }
  12845. bool ReplacingOriginal() { return true; }
  12846. // We need to special-case DeclRefExprs referring to FieldDecls which
  12847. // are not part of a member pointer formation; normal TreeTransforming
  12848. // doesn't catch this case because of the way we represent them in the AST.
  12849. // FIXME: This is a bit ugly; is it really the best way to handle this
  12850. // case?
  12851. //
  12852. // Error on DeclRefExprs referring to FieldDecls.
  12853. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  12854. if (isa<FieldDecl>(E->getDecl()) &&
  12855. !SemaRef.isUnevaluatedContext())
  12856. return SemaRef.Diag(E->getLocation(),
  12857. diag::err_invalid_non_static_member_use)
  12858. << E->getDecl() << E->getSourceRange();
  12859. return BaseTransform::TransformDeclRefExpr(E);
  12860. }
  12861. // Exception: filter out member pointer formation
  12862. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  12863. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  12864. return E;
  12865. return BaseTransform::TransformUnaryOperator(E);
  12866. }
  12867. // The body of a lambda-expression is in a separate expression evaluation
  12868. // context so never needs to be transformed.
  12869. // FIXME: Ideally we wouldn't transform the closure type either, and would
  12870. // just recreate the capture expressions and lambda expression.
  12871. StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
  12872. return SkipLambdaBody(E, Body);
  12873. }
  12874. };
  12875. }
  12876. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  12877. assert(isUnevaluatedContext() &&
  12878. "Should only transform unevaluated expressions");
  12879. ExprEvalContexts.back().Context =
  12880. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  12881. if (isUnevaluatedContext())
  12882. return E;
  12883. return TransformToPE(*this).TransformExpr(E);
  12884. }
  12885. void
  12886. Sema::PushExpressionEvaluationContext(
  12887. ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
  12888. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  12889. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
  12890. LambdaContextDecl, ExprContext);
  12891. Cleanup.reset();
  12892. if (!MaybeODRUseExprs.empty())
  12893. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  12894. }
  12895. void
  12896. Sema::PushExpressionEvaluationContext(
  12897. ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
  12898. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  12899. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  12900. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
  12901. }
  12902. namespace {
  12903. const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
  12904. PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
  12905. if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
  12906. if (E->getOpcode() == UO_Deref)
  12907. return CheckPossibleDeref(S, E->getSubExpr());
  12908. } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
  12909. return CheckPossibleDeref(S, E->getBase());
  12910. } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
  12911. return CheckPossibleDeref(S, E->getBase());
  12912. } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
  12913. QualType Inner;
  12914. QualType Ty = E->getType();
  12915. if (const auto *Ptr = Ty->getAs<PointerType>())
  12916. Inner = Ptr->getPointeeType();
  12917. else if (const auto *Arr = S.Context.getAsArrayType(Ty))
  12918. Inner = Arr->getElementType();
  12919. else
  12920. return nullptr;
  12921. if (Inner->hasAttr(attr::NoDeref))
  12922. return E;
  12923. }
  12924. return nullptr;
  12925. }
  12926. } // namespace
  12927. void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
  12928. for (const Expr *E : Rec.PossibleDerefs) {
  12929. const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
  12930. if (DeclRef) {
  12931. const ValueDecl *Decl = DeclRef->getDecl();
  12932. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
  12933. << Decl->getName() << E->getSourceRange();
  12934. Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
  12935. } else {
  12936. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
  12937. << E->getSourceRange();
  12938. }
  12939. }
  12940. Rec.PossibleDerefs.clear();
  12941. }
  12942. void Sema::PopExpressionEvaluationContext() {
  12943. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  12944. unsigned NumTypos = Rec.NumTypos;
  12945. if (!Rec.Lambdas.empty()) {
  12946. using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
  12947. if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
  12948. (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
  12949. unsigned D;
  12950. if (Rec.isUnevaluated()) {
  12951. // C++11 [expr.prim.lambda]p2:
  12952. // A lambda-expression shall not appear in an unevaluated operand
  12953. // (Clause 5).
  12954. D = diag::err_lambda_unevaluated_operand;
  12955. } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
  12956. // C++1y [expr.const]p2:
  12957. // A conditional-expression e is a core constant expression unless the
  12958. // evaluation of e, following the rules of the abstract machine, would
  12959. // evaluate [...] a lambda-expression.
  12960. D = diag::err_lambda_in_constant_expression;
  12961. } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
  12962. // C++17 [expr.prim.lamda]p2:
  12963. // A lambda-expression shall not appear [...] in a template-argument.
  12964. D = diag::err_lambda_in_invalid_context;
  12965. } else
  12966. llvm_unreachable("Couldn't infer lambda error message.");
  12967. for (const auto *L : Rec.Lambdas)
  12968. Diag(L->getBeginLoc(), D);
  12969. }
  12970. }
  12971. WarnOnPendingNoDerefs(Rec);
  12972. // When are coming out of an unevaluated context, clear out any
  12973. // temporaries that we may have created as part of the evaluation of
  12974. // the expression in that context: they aren't relevant because they
  12975. // will never be constructed.
  12976. if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
  12977. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  12978. ExprCleanupObjects.end());
  12979. Cleanup = Rec.ParentCleanup;
  12980. CleanupVarDeclMarking();
  12981. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  12982. // Otherwise, merge the contexts together.
  12983. } else {
  12984. Cleanup.mergeFrom(Rec.ParentCleanup);
  12985. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  12986. Rec.SavedMaybeODRUseExprs.end());
  12987. }
  12988. // Pop the current expression evaluation context off the stack.
  12989. ExprEvalContexts.pop_back();
  12990. // The global expression evaluation context record is never popped.
  12991. ExprEvalContexts.back().NumTypos += NumTypos;
  12992. }
  12993. void Sema::DiscardCleanupsInEvaluationContext() {
  12994. ExprCleanupObjects.erase(
  12995. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  12996. ExprCleanupObjects.end());
  12997. Cleanup.reset();
  12998. MaybeODRUseExprs.clear();
  12999. }
  13000. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  13001. ExprResult Result = CheckPlaceholderExpr(E);
  13002. if (Result.isInvalid())
  13003. return ExprError();
  13004. E = Result.get();
  13005. if (!E->getType()->isVariablyModifiedType())
  13006. return E;
  13007. return TransformToPotentiallyEvaluated(E);
  13008. }
  13009. /// Are we in a context that is potentially constant evaluated per C++20
  13010. /// [expr.const]p12?
  13011. static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
  13012. /// C++2a [expr.const]p12:
  13013. // An expression or conversion is potentially constant evaluated if it is
  13014. switch (SemaRef.ExprEvalContexts.back().Context) {
  13015. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  13016. // -- a manifestly constant-evaluated expression,
  13017. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  13018. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13019. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  13020. // -- a potentially-evaluated expression,
  13021. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  13022. // -- an immediate subexpression of a braced-init-list,
  13023. // -- [FIXME] an expression of the form & cast-expression that occurs
  13024. // within a templated entity
  13025. // -- a subexpression of one of the above that is not a subexpression of
  13026. // a nested unevaluated operand.
  13027. return true;
  13028. case Sema::ExpressionEvaluationContext::Unevaluated:
  13029. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  13030. // Expressions in this context are never evaluated.
  13031. return false;
  13032. }
  13033. llvm_unreachable("Invalid context");
  13034. }
  13035. namespace {
  13036. enum class OdrUseContext {
  13037. /// Declarations in this context are not odr-used.
  13038. None,
  13039. /// Declarations in this context are formally odr-used, but this is a
  13040. /// dependent context.
  13041. Dependent,
  13042. /// Declarations in this context are odr-used but not actually used (yet).
  13043. FormallyOdrUsed,
  13044. /// Declarations in this context are used.
  13045. Used
  13046. };
  13047. }
  13048. /// Are we within a context in which references to resolved functions or to
  13049. /// variables result in odr-use?
  13050. static OdrUseContext isOdrUseContext(Sema &SemaRef) {
  13051. OdrUseContext Result;
  13052. switch (SemaRef.ExprEvalContexts.back().Context) {
  13053. case Sema::ExpressionEvaluationContext::Unevaluated:
  13054. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  13055. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  13056. return OdrUseContext::None;
  13057. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  13058. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  13059. Result = OdrUseContext::Used;
  13060. break;
  13061. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  13062. Result = OdrUseContext::FormallyOdrUsed;
  13063. break;
  13064. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13065. // A default argument formally results in odr-use, but doesn't actually
  13066. // result in a use in any real sense until it itself is used.
  13067. Result = OdrUseContext::FormallyOdrUsed;
  13068. break;
  13069. }
  13070. if (SemaRef.CurContext->isDependentContext())
  13071. return OdrUseContext::Dependent;
  13072. return Result;
  13073. }
  13074. static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
  13075. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  13076. return Func->isConstexpr() &&
  13077. (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
  13078. }
  13079. /// Mark a function referenced, and check whether it is odr-used
  13080. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  13081. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  13082. bool MightBeOdrUse) {
  13083. assert(Func && "No function?");
  13084. Func->setReferenced();
  13085. // Recursive functions aren't really used until they're used from some other
  13086. // context.
  13087. bool IsRecursiveCall = CurContext == Func;
  13088. // C++11 [basic.def.odr]p3:
  13089. // A function whose name appears as a potentially-evaluated expression is
  13090. // odr-used if it is the unique lookup result or the selected member of a
  13091. // set of overloaded functions [...].
  13092. //
  13093. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  13094. // can just check that here.
  13095. OdrUseContext OdrUse =
  13096. MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
  13097. if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
  13098. OdrUse = OdrUseContext::FormallyOdrUsed;
  13099. // C++20 [expr.const]p12:
  13100. // A function [...] is needed for constant evaluation if it is [...] a
  13101. // constexpr function that is named by an expression that is potentially
  13102. // constant evaluated
  13103. bool NeededForConstantEvaluation =
  13104. isPotentiallyConstantEvaluatedContext(*this) &&
  13105. isImplicitlyDefinableConstexprFunction(Func);
  13106. // Determine whether we require a function definition to exist, per
  13107. // C++11 [temp.inst]p3:
  13108. // Unless a function template specialization has been explicitly
  13109. // instantiated or explicitly specialized, the function template
  13110. // specialization is implicitly instantiated when the specialization is
  13111. // referenced in a context that requires a function definition to exist.
  13112. // C++20 [temp.inst]p7:
  13113. // The existence of a definition of a [...] function is considered to
  13114. // affect the semantics of the program if the [...] function is needed for
  13115. // constant evaluation by an expression
  13116. // C++20 [basic.def.odr]p10:
  13117. // Every program shall contain exactly one definition of every non-inline
  13118. // function or variable that is odr-used in that program outside of a
  13119. // discarded statement
  13120. // C++20 [special]p1:
  13121. // The implementation will implicitly define [defaulted special members]
  13122. // if they are odr-used or needed for constant evaluation.
  13123. //
  13124. // Note that we skip the implicit instantiation of templates that are only
  13125. // used in unused default arguments or by recursive calls to themselves.
  13126. // This is formally non-conforming, but seems reasonable in practice.
  13127. bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
  13128. NeededForConstantEvaluation);
  13129. // C++14 [temp.expl.spec]p6:
  13130. // If a template [...] is explicitly specialized then that specialization
  13131. // shall be declared before the first use of that specialization that would
  13132. // cause an implicit instantiation to take place, in every translation unit
  13133. // in which such a use occurs
  13134. if (NeedDefinition &&
  13135. (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
  13136. Func->getMemberSpecializationInfo()))
  13137. checkSpecializationVisibility(Loc, Func);
  13138. // C++14 [except.spec]p17:
  13139. // An exception-specification is considered to be needed when:
  13140. // - the function is odr-used or, if it appears in an unevaluated operand,
  13141. // would be odr-used if the expression were potentially-evaluated;
  13142. //
  13143. // Note, we do this even if MightBeOdrUse is false. That indicates that the
  13144. // function is a pure virtual function we're calling, and in that case the
  13145. // function was selected by overload resolution and we need to resolve its
  13146. // exception specification for a different reason.
  13147. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  13148. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  13149. ResolveExceptionSpec(Loc, FPT);
  13150. if (getLangOpts().CUDA)
  13151. CheckCUDACall(Loc, Func);
  13152. // If we need a definition, try to create one.
  13153. if (NeedDefinition && !Func->getBody()) {
  13154. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  13155. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  13156. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  13157. if (Constructor->isDefaultConstructor()) {
  13158. if (Constructor->isTrivial() &&
  13159. !Constructor->hasAttr<DLLExportAttr>())
  13160. return;
  13161. DefineImplicitDefaultConstructor(Loc, Constructor);
  13162. } else if (Constructor->isCopyConstructor()) {
  13163. DefineImplicitCopyConstructor(Loc, Constructor);
  13164. } else if (Constructor->isMoveConstructor()) {
  13165. DefineImplicitMoveConstructor(Loc, Constructor);
  13166. }
  13167. } else if (Constructor->getInheritedConstructor()) {
  13168. DefineInheritingConstructor(Loc, Constructor);
  13169. }
  13170. } else if (CXXDestructorDecl *Destructor =
  13171. dyn_cast<CXXDestructorDecl>(Func)) {
  13172. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  13173. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  13174. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  13175. return;
  13176. DefineImplicitDestructor(Loc, Destructor);
  13177. }
  13178. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  13179. MarkVTableUsed(Loc, Destructor->getParent());
  13180. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  13181. if (MethodDecl->isOverloadedOperator() &&
  13182. MethodDecl->getOverloadedOperator() == OO_Equal) {
  13183. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  13184. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  13185. if (MethodDecl->isCopyAssignmentOperator())
  13186. DefineImplicitCopyAssignment(Loc, MethodDecl);
  13187. else if (MethodDecl->isMoveAssignmentOperator())
  13188. DefineImplicitMoveAssignment(Loc, MethodDecl);
  13189. }
  13190. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  13191. MethodDecl->getParent()->isLambda()) {
  13192. CXXConversionDecl *Conversion =
  13193. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  13194. if (Conversion->isLambdaToBlockPointerConversion())
  13195. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  13196. else
  13197. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  13198. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  13199. MarkVTableUsed(Loc, MethodDecl->getParent());
  13200. }
  13201. // Implicit instantiation of function templates and member functions of
  13202. // class templates.
  13203. if (Func->isImplicitlyInstantiable()) {
  13204. TemplateSpecializationKind TSK =
  13205. Func->getTemplateSpecializationKindForInstantiation();
  13206. SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
  13207. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  13208. if (FirstInstantiation) {
  13209. PointOfInstantiation = Loc;
  13210. Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  13211. } else if (TSK != TSK_ImplicitInstantiation) {
  13212. // Use the point of use as the point of instantiation, instead of the
  13213. // point of explicit instantiation (which we track as the actual point
  13214. // of instantiation). This gives better backtraces in diagnostics.
  13215. PointOfInstantiation = Loc;
  13216. }
  13217. if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
  13218. Func->isConstexpr()) {
  13219. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  13220. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  13221. CodeSynthesisContexts.size())
  13222. PendingLocalImplicitInstantiations.push_back(
  13223. std::make_pair(Func, PointOfInstantiation));
  13224. else if (Func->isConstexpr())
  13225. // Do not defer instantiations of constexpr functions, to avoid the
  13226. // expression evaluator needing to call back into Sema if it sees a
  13227. // call to such a function.
  13228. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  13229. else {
  13230. Func->setInstantiationIsPending(true);
  13231. PendingInstantiations.push_back(
  13232. std::make_pair(Func, PointOfInstantiation));
  13233. // Notify the consumer that a function was implicitly instantiated.
  13234. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  13235. }
  13236. }
  13237. } else {
  13238. // Walk redefinitions, as some of them may be instantiable.
  13239. for (auto i : Func->redecls()) {
  13240. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  13241. MarkFunctionReferenced(Loc, i, MightBeOdrUse);
  13242. }
  13243. }
  13244. }
  13245. // If this is the first "real" use, act on that.
  13246. if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
  13247. // Keep track of used but undefined functions.
  13248. if (!Func->isDefined()) {
  13249. if (mightHaveNonExternalLinkage(Func))
  13250. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13251. else if (Func->getMostRecentDecl()->isInlined() &&
  13252. !LangOpts.GNUInline &&
  13253. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  13254. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13255. else if (isExternalWithNoLinkageType(Func))
  13256. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13257. }
  13258. Func->markUsed(Context);
  13259. if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)
  13260. checkOpenMPDeviceFunction(Loc, Func);
  13261. }
  13262. }
  13263. /// Directly mark a variable odr-used. Given a choice, prefer to use
  13264. /// MarkVariableReferenced since it does additional checks and then
  13265. /// calls MarkVarDeclODRUsed.
  13266. /// If the variable must be captured:
  13267. /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
  13268. /// - else capture it in the DeclContext that maps to the
  13269. /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
  13270. static void
  13271. MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
  13272. const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
  13273. // Keep track of used but undefined variables.
  13274. // FIXME: We shouldn't suppress this warning for static data members.
  13275. if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
  13276. (!Var->isExternallyVisible() || Var->isInline() ||
  13277. SemaRef.isExternalWithNoLinkageType(Var)) &&
  13278. !(Var->isStaticDataMember() && Var->hasInit())) {
  13279. SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
  13280. if (old.isInvalid())
  13281. old = Loc;
  13282. }
  13283. QualType CaptureType, DeclRefType;
  13284. SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
  13285. /*EllipsisLoc*/ SourceLocation(),
  13286. /*BuildAndDiagnose*/ true,
  13287. CaptureType, DeclRefType,
  13288. FunctionScopeIndexToStopAt);
  13289. Var->markUsed(SemaRef.Context);
  13290. }
  13291. void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
  13292. SourceLocation Loc,
  13293. unsigned CapturingScopeIndex) {
  13294. MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
  13295. }
  13296. static void
  13297. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  13298. ValueDecl *var, DeclContext *DC) {
  13299. DeclContext *VarDC = var->getDeclContext();
  13300. // If the parameter still belongs to the translation unit, then
  13301. // we're actually just using one parameter in the declaration of
  13302. // the next.
  13303. if (isa<ParmVarDecl>(var) &&
  13304. isa<TranslationUnitDecl>(VarDC))
  13305. return;
  13306. // For C code, don't diagnose about capture if we're not actually in code
  13307. // right now; it's impossible to write a non-constant expression outside of
  13308. // function context, so we'll get other (more useful) diagnostics later.
  13309. //
  13310. // For C++, things get a bit more nasty... it would be nice to suppress this
  13311. // diagnostic for certain cases like using a local variable in an array bound
  13312. // for a member of a local class, but the correct predicate is not obvious.
  13313. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  13314. return;
  13315. unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
  13316. unsigned ContextKind = 3; // unknown
  13317. if (isa<CXXMethodDecl>(VarDC) &&
  13318. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  13319. ContextKind = 2;
  13320. } else if (isa<FunctionDecl>(VarDC)) {
  13321. ContextKind = 0;
  13322. } else if (isa<BlockDecl>(VarDC)) {
  13323. ContextKind = 1;
  13324. }
  13325. S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
  13326. << var << ValueKind << ContextKind << VarDC;
  13327. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  13328. << var;
  13329. // FIXME: Add additional diagnostic info about class etc. which prevents
  13330. // capture.
  13331. }
  13332. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  13333. bool &SubCapturesAreNested,
  13334. QualType &CaptureType,
  13335. QualType &DeclRefType) {
  13336. // Check whether we've already captured it.
  13337. if (CSI->CaptureMap.count(Var)) {
  13338. // If we found a capture, any subcaptures are nested.
  13339. SubCapturesAreNested = true;
  13340. // Retrieve the capture type for this variable.
  13341. CaptureType = CSI->getCapture(Var).getCaptureType();
  13342. // Compute the type of an expression that refers to this variable.
  13343. DeclRefType = CaptureType.getNonReferenceType();
  13344. // Similarly to mutable captures in lambda, all the OpenMP captures by copy
  13345. // are mutable in the sense that user can change their value - they are
  13346. // private instances of the captured declarations.
  13347. const Capture &Cap = CSI->getCapture(Var);
  13348. if (Cap.isCopyCapture() &&
  13349. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
  13350. !(isa<CapturedRegionScopeInfo>(CSI) &&
  13351. cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
  13352. DeclRefType.addConst();
  13353. return true;
  13354. }
  13355. return false;
  13356. }
  13357. // Only block literals, captured statements, and lambda expressions can
  13358. // capture; other scopes don't work.
  13359. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  13360. SourceLocation Loc,
  13361. const bool Diagnose, Sema &S) {
  13362. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  13363. return getLambdaAwareParentOfDeclContext(DC);
  13364. else if (Var->hasLocalStorage()) {
  13365. if (Diagnose)
  13366. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  13367. }
  13368. return nullptr;
  13369. }
  13370. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  13371. // certain types of variables (unnamed, variably modified types etc.)
  13372. // so check for eligibility.
  13373. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  13374. SourceLocation Loc,
  13375. const bool Diagnose, Sema &S) {
  13376. bool IsBlock = isa<BlockScopeInfo>(CSI);
  13377. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  13378. // Lambdas are not allowed to capture unnamed variables
  13379. // (e.g. anonymous unions).
  13380. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  13381. // assuming that's the intent.
  13382. if (IsLambda && !Var->getDeclName()) {
  13383. if (Diagnose) {
  13384. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  13385. S.Diag(Var->getLocation(), diag::note_declared_at);
  13386. }
  13387. return false;
  13388. }
  13389. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  13390. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  13391. if (Diagnose) {
  13392. S.Diag(Loc, diag::err_ref_vm_type);
  13393. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13394. << Var->getDeclName();
  13395. }
  13396. return false;
  13397. }
  13398. // Prohibit structs with flexible array members too.
  13399. // We cannot capture what is in the tail end of the struct.
  13400. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  13401. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  13402. if (Diagnose) {
  13403. if (IsBlock)
  13404. S.Diag(Loc, diag::err_ref_flexarray_type);
  13405. else
  13406. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  13407. << Var->getDeclName();
  13408. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13409. << Var->getDeclName();
  13410. }
  13411. return false;
  13412. }
  13413. }
  13414. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  13415. // Lambdas and captured statements are not allowed to capture __block
  13416. // variables; they don't support the expected semantics.
  13417. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  13418. if (Diagnose) {
  13419. S.Diag(Loc, diag::err_capture_block_variable)
  13420. << Var->getDeclName() << !IsLambda;
  13421. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13422. << Var->getDeclName();
  13423. }
  13424. return false;
  13425. }
  13426. // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
  13427. if (S.getLangOpts().OpenCL && IsBlock &&
  13428. Var->getType()->isBlockPointerType()) {
  13429. if (Diagnose)
  13430. S.Diag(Loc, diag::err_opencl_block_ref_block);
  13431. return false;
  13432. }
  13433. return true;
  13434. }
  13435. // Returns true if the capture by block was successful.
  13436. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  13437. SourceLocation Loc,
  13438. const bool BuildAndDiagnose,
  13439. QualType &CaptureType,
  13440. QualType &DeclRefType,
  13441. const bool Nested,
  13442. Sema &S, bool Invalid) {
  13443. bool ByRef = false;
  13444. // Blocks are not allowed to capture arrays, excepting OpenCL.
  13445. // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
  13446. // (decayed to pointers).
  13447. if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
  13448. if (BuildAndDiagnose) {
  13449. S.Diag(Loc, diag::err_ref_array_type);
  13450. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13451. << Var->getDeclName();
  13452. Invalid = true;
  13453. } else {
  13454. return false;
  13455. }
  13456. }
  13457. // Forbid the block-capture of autoreleasing variables.
  13458. if (!Invalid &&
  13459. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  13460. if (BuildAndDiagnose) {
  13461. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  13462. << /*block*/ 0;
  13463. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13464. << Var->getDeclName();
  13465. Invalid = true;
  13466. } else {
  13467. return false;
  13468. }
  13469. }
  13470. // Warn about implicitly autoreleasing indirect parameters captured by blocks.
  13471. if (const auto *PT = CaptureType->getAs<PointerType>()) {
  13472. // This function finds out whether there is an AttributedType of kind
  13473. // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
  13474. // attr::ObjCOwnership implies __autoreleasing was explicitly specified
  13475. // rather than being added implicitly by the compiler.
  13476. auto IsObjCOwnershipAttributedType = [](QualType Ty) {
  13477. while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
  13478. if (AttrTy->getAttrKind() == attr::ObjCOwnership)
  13479. return true;
  13480. // Peel off AttributedTypes that are not of kind ObjCOwnership.
  13481. Ty = AttrTy->getModifiedType();
  13482. }
  13483. return false;
  13484. };
  13485. QualType PointeeTy = PT->getPointeeType();
  13486. if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
  13487. PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
  13488. !IsObjCOwnershipAttributedType(PointeeTy)) {
  13489. if (BuildAndDiagnose) {
  13490. SourceLocation VarLoc = Var->getLocation();
  13491. S.Diag(Loc, diag::warn_block_capture_autoreleasing);
  13492. S.Diag(VarLoc, diag::note_declare_parameter_strong);
  13493. }
  13494. }
  13495. }
  13496. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  13497. if (HasBlocksAttr || CaptureType->isReferenceType() ||
  13498. (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
  13499. // Block capture by reference does not change the capture or
  13500. // declaration reference types.
  13501. ByRef = true;
  13502. } else {
  13503. // Block capture by copy introduces 'const'.
  13504. CaptureType = CaptureType.getNonReferenceType().withConst();
  13505. DeclRefType = CaptureType;
  13506. }
  13507. // Actually capture the variable.
  13508. if (BuildAndDiagnose)
  13509. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
  13510. CaptureType, Invalid);
  13511. return !Invalid;
  13512. }
  13513. /// Capture the given variable in the captured region.
  13514. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  13515. VarDecl *Var,
  13516. SourceLocation Loc,
  13517. const bool BuildAndDiagnose,
  13518. QualType &CaptureType,
  13519. QualType &DeclRefType,
  13520. const bool RefersToCapturedVariable,
  13521. Sema &S, bool Invalid) {
  13522. // By default, capture variables by reference.
  13523. bool ByRef = true;
  13524. // Using an LValue reference type is consistent with Lambdas (see below).
  13525. if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
  13526. if (S.isOpenMPCapturedDecl(Var)) {
  13527. bool HasConst = DeclRefType.isConstQualified();
  13528. DeclRefType = DeclRefType.getUnqualifiedType();
  13529. // Don't lose diagnostics about assignments to const.
  13530. if (HasConst)
  13531. DeclRefType.addConst();
  13532. }
  13533. ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
  13534. }
  13535. if (ByRef)
  13536. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  13537. else
  13538. CaptureType = DeclRefType;
  13539. // Actually capture the variable.
  13540. if (BuildAndDiagnose)
  13541. RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
  13542. Loc, SourceLocation(), CaptureType, Invalid);
  13543. return !Invalid;
  13544. }
  13545. /// Capture the given variable in the lambda.
  13546. static bool captureInLambda(LambdaScopeInfo *LSI,
  13547. VarDecl *Var,
  13548. SourceLocation Loc,
  13549. const bool BuildAndDiagnose,
  13550. QualType &CaptureType,
  13551. QualType &DeclRefType,
  13552. const bool RefersToCapturedVariable,
  13553. const Sema::TryCaptureKind Kind,
  13554. SourceLocation EllipsisLoc,
  13555. const bool IsTopScope,
  13556. Sema &S, bool Invalid) {
  13557. // Determine whether we are capturing by reference or by value.
  13558. bool ByRef = false;
  13559. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  13560. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  13561. } else {
  13562. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  13563. }
  13564. // Compute the type of the field that will capture this variable.
  13565. if (ByRef) {
  13566. // C++11 [expr.prim.lambda]p15:
  13567. // An entity is captured by reference if it is implicitly or
  13568. // explicitly captured but not captured by copy. It is
  13569. // unspecified whether additional unnamed non-static data
  13570. // members are declared in the closure type for entities
  13571. // captured by reference.
  13572. //
  13573. // FIXME: It is not clear whether we want to build an lvalue reference
  13574. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  13575. // to do the former, while EDG does the latter. Core issue 1249 will
  13576. // clarify, but for now we follow GCC because it's a more permissive and
  13577. // easily defensible position.
  13578. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  13579. } else {
  13580. // C++11 [expr.prim.lambda]p14:
  13581. // For each entity captured by copy, an unnamed non-static
  13582. // data member is declared in the closure type. The
  13583. // declaration order of these members is unspecified. The type
  13584. // of such a data member is the type of the corresponding
  13585. // captured entity if the entity is not a reference to an
  13586. // object, or the referenced type otherwise. [Note: If the
  13587. // captured entity is a reference to a function, the
  13588. // corresponding data member is also a reference to a
  13589. // function. - end note ]
  13590. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  13591. if (!RefType->getPointeeType()->isFunctionType())
  13592. CaptureType = RefType->getPointeeType();
  13593. }
  13594. // Forbid the lambda copy-capture of autoreleasing variables.
  13595. if (!Invalid &&
  13596. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  13597. if (BuildAndDiagnose) {
  13598. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  13599. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13600. << Var->getDeclName();
  13601. Invalid = true;
  13602. } else {
  13603. return false;
  13604. }
  13605. }
  13606. // Make sure that by-copy captures are of a complete and non-abstract type.
  13607. if (!Invalid && BuildAndDiagnose) {
  13608. if (!CaptureType->isDependentType() &&
  13609. S.RequireCompleteType(Loc, CaptureType,
  13610. diag::err_capture_of_incomplete_type,
  13611. Var->getDeclName()))
  13612. Invalid = true;
  13613. else if (S.RequireNonAbstractType(Loc, CaptureType,
  13614. diag::err_capture_of_abstract_type))
  13615. Invalid = true;
  13616. }
  13617. }
  13618. // Compute the type of a reference to this captured variable.
  13619. if (ByRef)
  13620. DeclRefType = CaptureType.getNonReferenceType();
  13621. else {
  13622. // C++ [expr.prim.lambda]p5:
  13623. // The closure type for a lambda-expression has a public inline
  13624. // function call operator [...]. This function call operator is
  13625. // declared const (9.3.1) if and only if the lambda-expression's
  13626. // parameter-declaration-clause is not followed by mutable.
  13627. DeclRefType = CaptureType.getNonReferenceType();
  13628. if (!LSI->Mutable && !CaptureType->isReferenceType())
  13629. DeclRefType.addConst();
  13630. }
  13631. // Add the capture.
  13632. if (BuildAndDiagnose)
  13633. LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
  13634. Loc, EllipsisLoc, CaptureType, Invalid);
  13635. return !Invalid;
  13636. }
  13637. bool Sema::tryCaptureVariable(
  13638. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  13639. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  13640. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  13641. // An init-capture is notionally from the context surrounding its
  13642. // declaration, but its parent DC is the lambda class.
  13643. DeclContext *VarDC = Var->getDeclContext();
  13644. if (Var->isInitCapture())
  13645. VarDC = VarDC->getParent();
  13646. DeclContext *DC = CurContext;
  13647. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  13648. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  13649. // We need to sync up the Declaration Context with the
  13650. // FunctionScopeIndexToStopAt
  13651. if (FunctionScopeIndexToStopAt) {
  13652. unsigned FSIndex = FunctionScopes.size() - 1;
  13653. while (FSIndex != MaxFunctionScopesIndex) {
  13654. DC = getLambdaAwareParentOfDeclContext(DC);
  13655. --FSIndex;
  13656. }
  13657. }
  13658. // If the variable is declared in the current context, there is no need to
  13659. // capture it.
  13660. if (VarDC == DC) return true;
  13661. // Capture global variables if it is required to use private copy of this
  13662. // variable.
  13663. bool IsGlobal = !Var->hasLocalStorage();
  13664. if (IsGlobal &&
  13665. !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
  13666. MaxFunctionScopesIndex)))
  13667. return true;
  13668. Var = Var->getCanonicalDecl();
  13669. // Walk up the stack to determine whether we can capture the variable,
  13670. // performing the "simple" checks that don't depend on type. We stop when
  13671. // we've either hit the declared scope of the variable or find an existing
  13672. // capture of that variable. We start from the innermost capturing-entity
  13673. // (the DC) and ensure that all intervening capturing-entities
  13674. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  13675. // declcontext can either capture the variable or have already captured
  13676. // the variable.
  13677. CaptureType = Var->getType();
  13678. DeclRefType = CaptureType.getNonReferenceType();
  13679. bool Nested = false;
  13680. bool Explicit = (Kind != TryCapture_Implicit);
  13681. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  13682. do {
  13683. // Only block literals, captured statements, and lambda expressions can
  13684. // capture; other scopes don't work.
  13685. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  13686. ExprLoc,
  13687. BuildAndDiagnose,
  13688. *this);
  13689. // We need to check for the parent *first* because, if we *have*
  13690. // private-captured a global variable, we need to recursively capture it in
  13691. // intermediate blocks, lambdas, etc.
  13692. if (!ParentDC) {
  13693. if (IsGlobal) {
  13694. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  13695. break;
  13696. }
  13697. return true;
  13698. }
  13699. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  13700. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  13701. // Check whether we've already captured it.
  13702. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  13703. DeclRefType)) {
  13704. CSI->getCapture(Var).markUsed(BuildAndDiagnose);
  13705. break;
  13706. }
  13707. // If we are instantiating a generic lambda call operator body,
  13708. // we do not want to capture new variables. What was captured
  13709. // during either a lambdas transformation or initial parsing
  13710. // should be used.
  13711. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  13712. if (BuildAndDiagnose) {
  13713. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  13714. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  13715. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  13716. Diag(Var->getLocation(), diag::note_previous_decl)
  13717. << Var->getDeclName();
  13718. Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
  13719. } else
  13720. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  13721. }
  13722. return true;
  13723. }
  13724. // Try to capture variable-length arrays types.
  13725. if (Var->getType()->isVariablyModifiedType()) {
  13726. // We're going to walk down into the type and look for VLA
  13727. // expressions.
  13728. QualType QTy = Var->getType();
  13729. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  13730. QTy = PVD->getOriginalType();
  13731. captureVariablyModifiedType(Context, QTy, CSI);
  13732. }
  13733. if (getLangOpts().OpenMP) {
  13734. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  13735. // OpenMP private variables should not be captured in outer scope, so
  13736. // just break here. Similarly, global variables that are captured in a
  13737. // target region should not be captured outside the scope of the region.
  13738. if (RSI->CapRegionKind == CR_OpenMP) {
  13739. bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
  13740. auto IsTargetCap = !IsOpenMPPrivateDecl &&
  13741. isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
  13742. // When we detect target captures we are looking from inside the
  13743. // target region, therefore we need to propagate the capture from the
  13744. // enclosing region. Therefore, the capture is not initially nested.
  13745. if (IsTargetCap)
  13746. adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
  13747. if (IsTargetCap || IsOpenMPPrivateDecl) {
  13748. Nested = !IsTargetCap;
  13749. DeclRefType = DeclRefType.getUnqualifiedType();
  13750. CaptureType = Context.getLValueReferenceType(DeclRefType);
  13751. break;
  13752. }
  13753. }
  13754. }
  13755. }
  13756. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  13757. // No capture-default, and this is not an explicit capture
  13758. // so cannot capture this variable.
  13759. if (BuildAndDiagnose) {
  13760. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  13761. Diag(Var->getLocation(), diag::note_previous_decl)
  13762. << Var->getDeclName();
  13763. if (cast<LambdaScopeInfo>(CSI)->Lambda)
  13764. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
  13765. diag::note_lambda_decl);
  13766. // FIXME: If we error out because an outer lambda can not implicitly
  13767. // capture a variable that an inner lambda explicitly captures, we
  13768. // should have the inner lambda do the explicit capture - because
  13769. // it makes for cleaner diagnostics later. This would purely be done
  13770. // so that the diagnostic does not misleadingly claim that a variable
  13771. // can not be captured by a lambda implicitly even though it is captured
  13772. // explicitly. Suggestion:
  13773. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  13774. // at the function head
  13775. // - cache the StartingDeclContext - this must be a lambda
  13776. // - captureInLambda in the innermost lambda the variable.
  13777. }
  13778. return true;
  13779. }
  13780. FunctionScopesIndex--;
  13781. DC = ParentDC;
  13782. Explicit = false;
  13783. } while (!VarDC->Equals(DC));
  13784. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  13785. // computing the type of the capture at each step, checking type-specific
  13786. // requirements, and adding captures if requested.
  13787. // If the variable had already been captured previously, we start capturing
  13788. // at the lambda nested within that one.
  13789. bool Invalid = false;
  13790. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  13791. ++I) {
  13792. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  13793. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  13794. // certain types of variables (unnamed, variably modified types etc.)
  13795. // so check for eligibility.
  13796. if (!Invalid)
  13797. Invalid =
  13798. !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
  13799. // After encountering an error, if we're actually supposed to capture, keep
  13800. // capturing in nested contexts to suppress any follow-on diagnostics.
  13801. if (Invalid && !BuildAndDiagnose)
  13802. return true;
  13803. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  13804. Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  13805. DeclRefType, Nested, *this, Invalid);
  13806. Nested = true;
  13807. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  13808. Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
  13809. CaptureType, DeclRefType, Nested,
  13810. *this, Invalid);
  13811. Nested = true;
  13812. } else {
  13813. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  13814. Invalid =
  13815. !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  13816. DeclRefType, Nested, Kind, EllipsisLoc,
  13817. /*IsTopScope*/ I == N - 1, *this, Invalid);
  13818. Nested = true;
  13819. }
  13820. if (Invalid && !BuildAndDiagnose)
  13821. return true;
  13822. }
  13823. return Invalid;
  13824. }
  13825. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  13826. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  13827. QualType CaptureType;
  13828. QualType DeclRefType;
  13829. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  13830. /*BuildAndDiagnose=*/true, CaptureType,
  13831. DeclRefType, nullptr);
  13832. }
  13833. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  13834. QualType CaptureType;
  13835. QualType DeclRefType;
  13836. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  13837. /*BuildAndDiagnose=*/false, CaptureType,
  13838. DeclRefType, nullptr);
  13839. }
  13840. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  13841. QualType CaptureType;
  13842. QualType DeclRefType;
  13843. // Determine whether we can capture this variable.
  13844. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  13845. /*BuildAndDiagnose=*/false, CaptureType,
  13846. DeclRefType, nullptr))
  13847. return QualType();
  13848. return DeclRefType;
  13849. }
  13850. // If either the type of the variable or the initializer is dependent,
  13851. // return false. Otherwise, determine whether the variable is a constant
  13852. // expression. Use this if you need to know if a variable that might or
  13853. // might not be dependent is truly a constant expression.
  13854. static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
  13855. ASTContext &Context) {
  13856. if (Var->getType()->isDependentType())
  13857. return false;
  13858. const VarDecl *DefVD = nullptr;
  13859. Var->getAnyInitializer(DefVD);
  13860. if (!DefVD)
  13861. return false;
  13862. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  13863. Expr *Init = cast<Expr>(Eval->Value);
  13864. if (Init->isValueDependent())
  13865. return false;
  13866. return IsVariableAConstantExpression(Var, Context);
  13867. }
  13868. void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
  13869. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  13870. // an object that satisfies the requirements for appearing in a
  13871. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  13872. // is immediately applied." This function handles the lvalue-to-rvalue
  13873. // conversion part.
  13874. MaybeODRUseExprs.erase(E->IgnoreParens());
  13875. // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
  13876. // to a variable that is a constant expression, and if so, identify it as
  13877. // a reference to a variable that does not involve an odr-use of that
  13878. // variable.
  13879. if (LambdaScopeInfo *LSI = getCurLambda()) {
  13880. Expr *SansParensExpr = E->IgnoreParens();
  13881. VarDecl *Var;
  13882. ArrayRef<VarDecl *> Vars(&Var, &Var + 1);
  13883. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
  13884. Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
  13885. else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
  13886. Var = dyn_cast<VarDecl>(ME->getMemberDecl());
  13887. else if (auto *FPPE = dyn_cast<FunctionParmPackExpr>(SansParensExpr))
  13888. Vars = llvm::makeArrayRef(FPPE->begin(), FPPE->end());
  13889. else
  13890. Vars = None;
  13891. for (VarDecl *VD : Vars) {
  13892. if (VD && IsVariableNonDependentAndAConstantExpression(VD, Context))
  13893. LSI->markVariableExprAsNonODRUsed(SansParensExpr);
  13894. }
  13895. }
  13896. }
  13897. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  13898. Res = CorrectDelayedTyposInExpr(Res);
  13899. if (!Res.isUsable())
  13900. return Res;
  13901. // If a constant-expression is a reference to a variable where we delay
  13902. // deciding whether it is an odr-use, just assume we will apply the
  13903. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  13904. // (a non-type template argument), we have special handling anyway.
  13905. UpdateMarkingForLValueToRValue(Res.get());
  13906. return Res;
  13907. }
  13908. void Sema::CleanupVarDeclMarking() {
  13909. // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
  13910. // call.
  13911. MaybeODRUseExprSet LocalMaybeODRUseExprs;
  13912. std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
  13913. for (Expr *E : LocalMaybeODRUseExprs) {
  13914. if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  13915. MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
  13916. DRE->getLocation(), *this);
  13917. } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
  13918. MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
  13919. *this);
  13920. } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
  13921. for (VarDecl *VD : *FP)
  13922. MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
  13923. } else {
  13924. llvm_unreachable("Unexpected expression");
  13925. }
  13926. }
  13927. assert(MaybeODRUseExprs.empty() &&
  13928. "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
  13929. }
  13930. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  13931. VarDecl *Var, Expr *E) {
  13932. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
  13933. isa<FunctionParmPackExpr>(E)) &&
  13934. "Invalid Expr argument to DoMarkVarDeclReferenced");
  13935. Var->setReferenced();
  13936. if (Var->isInvalidDecl())
  13937. return;
  13938. auto *MSI = Var->getMemberSpecializationInfo();
  13939. TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
  13940. : Var->getTemplateSpecializationKind();
  13941. OdrUseContext OdrUse = isOdrUseContext(SemaRef);
  13942. bool UsableInConstantExpr =
  13943. Var->isUsableInConstantExpressions(SemaRef.Context);
  13944. // C++20 [expr.const]p12:
  13945. // A variable [...] is needed for constant evaluation if it is [...] a
  13946. // variable whose name appears as a potentially constant evaluated
  13947. // expression that is either a contexpr variable or is of non-volatile
  13948. // const-qualified integral type or of reference type
  13949. bool NeededForConstantEvaluation =
  13950. isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
  13951. bool NeedDefinition =
  13952. OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
  13953. VarTemplateSpecializationDecl *VarSpec =
  13954. dyn_cast<VarTemplateSpecializationDecl>(Var);
  13955. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  13956. "Can't instantiate a partial template specialization.");
  13957. // If this might be a member specialization of a static data member, check
  13958. // the specialization is visible. We already did the checks for variable
  13959. // template specializations when we created them.
  13960. if (NeedDefinition && TSK != TSK_Undeclared &&
  13961. !isa<VarTemplateSpecializationDecl>(Var))
  13962. SemaRef.checkSpecializationVisibility(Loc, Var);
  13963. // Perform implicit instantiation of static data members, static data member
  13964. // templates of class templates, and variable template specializations. Delay
  13965. // instantiations of variable templates, except for those that could be used
  13966. // in a constant expression.
  13967. if (NeedDefinition && isTemplateInstantiation(TSK)) {
  13968. // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
  13969. // instantiation declaration if a variable is usable in a constant
  13970. // expression (among other cases).
  13971. bool TryInstantiating =
  13972. TSK == TSK_ImplicitInstantiation ||
  13973. (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
  13974. if (TryInstantiating) {
  13975. SourceLocation PointOfInstantiation =
  13976. MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
  13977. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  13978. if (FirstInstantiation) {
  13979. PointOfInstantiation = Loc;
  13980. if (MSI)
  13981. MSI->setPointOfInstantiation(PointOfInstantiation);
  13982. else
  13983. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  13984. }
  13985. bool InstantiationDependent = false;
  13986. bool IsNonDependent =
  13987. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  13988. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  13989. : true;
  13990. // Do not instantiate specializations that are still type-dependent.
  13991. if (IsNonDependent) {
  13992. if (UsableInConstantExpr) {
  13993. // Do not defer instantiations of variables that could be used in a
  13994. // constant expression.
  13995. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  13996. } else if (FirstInstantiation ||
  13997. isa<VarTemplateSpecializationDecl>(Var)) {
  13998. // FIXME: For a specialization of a variable template, we don't
  13999. // distinguish between "declaration and type implicitly instantiated"
  14000. // and "implicit instantiation of definition requested", so we have
  14001. // no direct way to avoid enqueueing the pending instantiation
  14002. // multiple times.
  14003. SemaRef.PendingInstantiations
  14004. .push_back(std::make_pair(Var, PointOfInstantiation));
  14005. }
  14006. }
  14007. }
  14008. }
  14009. // C++20 [basic.def.odr]p4:
  14010. // A variable x whose name appears as a potentially-evaluated expression e
  14011. // is odr-used by e unless
  14012. // -- x is a reference that is usable in constant expressions
  14013. // -- x is a variable of non-reference type that is usable in constant
  14014. // expressions and has no mutable subobjects [FIXME], and e is an
  14015. // element of the set of potential results of an expression of
  14016. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  14017. // conversion is applied
  14018. // -- x is a variable of non-reference type, and e is an element of the set
  14019. // of potential results of a discarded-value expression to which the
  14020. // lvalue-to-rvalue conversion is not applied [FIXME]
  14021. //
  14022. // We check the first part of the second bullet here, and
  14023. // Sema::UpdateMarkingForLValueToRValue deals with the second part.
  14024. // FIXME: To get the third bullet right, we need to delay this even for
  14025. // variables that are not usable in constant expressions.
  14026. switch (OdrUse) {
  14027. case OdrUseContext::None:
  14028. break;
  14029. case OdrUseContext::FormallyOdrUsed:
  14030. // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
  14031. // behavior.
  14032. break;
  14033. case OdrUseContext::Used:
  14034. if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
  14035. // A reference initialized by a constant expression can never be
  14036. // odr-used, so simply ignore it.
  14037. if (!Var->getType()->isReferenceType() ||
  14038. (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
  14039. SemaRef.MaybeODRUseExprs.insert(E);
  14040. } else {
  14041. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  14042. /*MaxFunctionScopeIndex ptr*/ nullptr);
  14043. }
  14044. break;
  14045. case OdrUseContext::Dependent:
  14046. // If this is a dependent context, we don't need to mark variables as
  14047. // odr-used, but we may still need to track them for lambda capture.
  14048. // FIXME: Do we also need to do this inside dependent typeid expressions
  14049. // (which are modeled as unevaluated at this point)?
  14050. const bool RefersToEnclosingScope =
  14051. (SemaRef.CurContext != Var->getDeclContext() &&
  14052. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  14053. if (RefersToEnclosingScope) {
  14054. LambdaScopeInfo *const LSI =
  14055. SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
  14056. if (LSI && (!LSI->CallOperator ||
  14057. !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
  14058. // If a variable could potentially be odr-used, defer marking it so
  14059. // until we finish analyzing the full expression for any
  14060. // lvalue-to-rvalue
  14061. // or discarded value conversions that would obviate odr-use.
  14062. // Add it to the list of potential captures that will be analyzed
  14063. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  14064. // unless the variable is a reference that was initialized by a constant
  14065. // expression (this will never need to be captured or odr-used).
  14066. //
  14067. // FIXME: We can simplify this a lot after implementing P0588R1.
  14068. assert(E && "Capture variable should be used in an expression.");
  14069. if (!Var->getType()->isReferenceType() ||
  14070. !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
  14071. LSI->addPotentialCapture(E->IgnoreParens());
  14072. }
  14073. }
  14074. break;
  14075. }
  14076. }
  14077. /// Mark a variable referenced, and check whether it is odr-used
  14078. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  14079. /// used directly for normal expressions referring to VarDecl.
  14080. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  14081. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  14082. }
  14083. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  14084. Decl *D, Expr *E, bool MightBeOdrUse) {
  14085. if (SemaRef.isInOpenMPDeclareTargetContext())
  14086. SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
  14087. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  14088. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  14089. return;
  14090. }
  14091. SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
  14092. // If this is a call to a method via a cast, also mark the method in the
  14093. // derived class used in case codegen can devirtualize the call.
  14094. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  14095. if (!ME)
  14096. return;
  14097. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  14098. if (!MD)
  14099. return;
  14100. // Only attempt to devirtualize if this is truly a virtual call.
  14101. bool IsVirtualCall = MD->isVirtual() &&
  14102. ME->performsVirtualDispatch(SemaRef.getLangOpts());
  14103. if (!IsVirtualCall)
  14104. return;
  14105. // If it's possible to devirtualize the call, mark the called function
  14106. // referenced.
  14107. CXXMethodDecl *DM = MD->getDevirtualizedMethod(
  14108. ME->getBase(), SemaRef.getLangOpts().AppleKext);
  14109. if (DM)
  14110. SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
  14111. }
  14112. /// Perform reference-marking and odr-use handling for a DeclRefExpr.
  14113. void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
  14114. // TODO: update this with DR# once a defect report is filed.
  14115. // C++11 defect. The address of a pure member should not be an ODR use, even
  14116. // if it's a qualified reference.
  14117. bool OdrUse = true;
  14118. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  14119. if (Method->isVirtual() &&
  14120. !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
  14121. OdrUse = false;
  14122. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  14123. }
  14124. /// Perform reference-marking and odr-use handling for a MemberExpr.
  14125. void Sema::MarkMemberReferenced(MemberExpr *E) {
  14126. // C++11 [basic.def.odr]p2:
  14127. // A non-overloaded function whose name appears as a potentially-evaluated
  14128. // expression or a member of a set of candidate functions, if selected by
  14129. // overload resolution when referred to from a potentially-evaluated
  14130. // expression, is odr-used, unless it is a pure virtual function and its
  14131. // name is not explicitly qualified.
  14132. bool MightBeOdrUse = true;
  14133. if (E->performsVirtualDispatch(getLangOpts())) {
  14134. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  14135. if (Method->isPure())
  14136. MightBeOdrUse = false;
  14137. }
  14138. SourceLocation Loc =
  14139. E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
  14140. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
  14141. }
  14142. /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
  14143. void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
  14144. for (VarDecl *VD : *E)
  14145. MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
  14146. }
  14147. /// Perform marking for a reference to an arbitrary declaration. It
  14148. /// marks the declaration referenced, and performs odr-use checking for
  14149. /// functions and variables. This method should not be used when building a
  14150. /// normal expression which refers to a variable.
  14151. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
  14152. bool MightBeOdrUse) {
  14153. if (MightBeOdrUse) {
  14154. if (auto *VD = dyn_cast<VarDecl>(D)) {
  14155. MarkVariableReferenced(Loc, VD);
  14156. return;
  14157. }
  14158. }
  14159. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  14160. MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
  14161. return;
  14162. }
  14163. D->setReferenced();
  14164. }
  14165. namespace {
  14166. // Mark all of the declarations used by a type as referenced.
  14167. // FIXME: Not fully implemented yet! We need to have a better understanding
  14168. // of when we're entering a context we should not recurse into.
  14169. // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
  14170. // TreeTransforms rebuilding the type in a new context. Rather than
  14171. // duplicating the TreeTransform logic, we should consider reusing it here.
  14172. // Currently that causes problems when rebuilding LambdaExprs.
  14173. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  14174. Sema &S;
  14175. SourceLocation Loc;
  14176. public:
  14177. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  14178. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  14179. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  14180. };
  14181. }
  14182. bool MarkReferencedDecls::TraverseTemplateArgument(
  14183. const TemplateArgument &Arg) {
  14184. {
  14185. // A non-type template argument is a constant-evaluated context.
  14186. EnterExpressionEvaluationContext Evaluated(
  14187. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  14188. if (Arg.getKind() == TemplateArgument::Declaration) {
  14189. if (Decl *D = Arg.getAsDecl())
  14190. S.MarkAnyDeclReferenced(Loc, D, true);
  14191. } else if (Arg.getKind() == TemplateArgument::Expression) {
  14192. S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
  14193. }
  14194. }
  14195. return Inherited::TraverseTemplateArgument(Arg);
  14196. }
  14197. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  14198. MarkReferencedDecls Marker(*this, Loc);
  14199. Marker.TraverseType(T);
  14200. }
  14201. namespace {
  14202. /// Helper class that marks all of the declarations referenced by
  14203. /// potentially-evaluated subexpressions as "referenced".
  14204. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  14205. Sema &S;
  14206. bool SkipLocalVariables;
  14207. public:
  14208. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  14209. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  14210. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  14211. void VisitDeclRefExpr(DeclRefExpr *E) {
  14212. // If we were asked not to visit local variables, don't.
  14213. if (SkipLocalVariables) {
  14214. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  14215. if (VD->hasLocalStorage())
  14216. return;
  14217. }
  14218. S.MarkDeclRefReferenced(E);
  14219. }
  14220. void VisitMemberExpr(MemberExpr *E) {
  14221. S.MarkMemberReferenced(E);
  14222. Inherited::VisitMemberExpr(E);
  14223. }
  14224. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  14225. S.MarkFunctionReferenced(
  14226. E->getBeginLoc(),
  14227. const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
  14228. Visit(E->getSubExpr());
  14229. }
  14230. void VisitCXXNewExpr(CXXNewExpr *E) {
  14231. if (E->getOperatorNew())
  14232. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
  14233. if (E->getOperatorDelete())
  14234. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  14235. Inherited::VisitCXXNewExpr(E);
  14236. }
  14237. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  14238. if (E->getOperatorDelete())
  14239. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  14240. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  14241. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  14242. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  14243. S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
  14244. }
  14245. Inherited::VisitCXXDeleteExpr(E);
  14246. }
  14247. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  14248. S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
  14249. Inherited::VisitCXXConstructExpr(E);
  14250. }
  14251. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  14252. Visit(E->getExpr());
  14253. }
  14254. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  14255. Inherited::VisitImplicitCastExpr(E);
  14256. if (E->getCastKind() == CK_LValueToRValue)
  14257. S.UpdateMarkingForLValueToRValue(E->getSubExpr());
  14258. }
  14259. };
  14260. }
  14261. /// Mark any declarations that appear within this expression or any
  14262. /// potentially-evaluated subexpressions as "referenced".
  14263. ///
  14264. /// \param SkipLocalVariables If true, don't mark local variables as
  14265. /// 'referenced'.
  14266. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  14267. bool SkipLocalVariables) {
  14268. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  14269. }
  14270. /// Emit a diagnostic that describes an effect on the run-time behavior
  14271. /// of the program being compiled.
  14272. ///
  14273. /// This routine emits the given diagnostic when the code currently being
  14274. /// type-checked is "potentially evaluated", meaning that there is a
  14275. /// possibility that the code will actually be executable. Code in sizeof()
  14276. /// expressions, code used only during overload resolution, etc., are not
  14277. /// potentially evaluated. This routine will suppress such diagnostics or,
  14278. /// in the absolutely nutty case of potentially potentially evaluated
  14279. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  14280. /// later.
  14281. ///
  14282. /// This routine should be used for all diagnostics that describe the run-time
  14283. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  14284. /// Failure to do so will likely result in spurious diagnostics or failures
  14285. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  14286. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
  14287. const PartialDiagnostic &PD) {
  14288. switch (ExprEvalContexts.back().Context) {
  14289. case ExpressionEvaluationContext::Unevaluated:
  14290. case ExpressionEvaluationContext::UnevaluatedList:
  14291. case ExpressionEvaluationContext::UnevaluatedAbstract:
  14292. case ExpressionEvaluationContext::DiscardedStatement:
  14293. // The argument will never be evaluated, so don't complain.
  14294. break;
  14295. case ExpressionEvaluationContext::ConstantEvaluated:
  14296. // Relevant diagnostics should be produced by constant evaluation.
  14297. break;
  14298. case ExpressionEvaluationContext::PotentiallyEvaluated:
  14299. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  14300. if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
  14301. FunctionScopes.back()->PossiblyUnreachableDiags.
  14302. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
  14303. return true;
  14304. }
  14305. // The initializer of a constexpr variable or of the first declaration of a
  14306. // static data member is not syntactically a constant evaluated constant,
  14307. // but nonetheless is always required to be a constant expression, so we
  14308. // can skip diagnosing.
  14309. // FIXME: Using the mangling context here is a hack.
  14310. if (auto *VD = dyn_cast_or_null<VarDecl>(
  14311. ExprEvalContexts.back().ManglingContextDecl)) {
  14312. if (VD->isConstexpr() ||
  14313. (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
  14314. break;
  14315. // FIXME: For any other kind of variable, we should build a CFG for its
  14316. // initializer and check whether the context in question is reachable.
  14317. }
  14318. Diag(Loc, PD);
  14319. return true;
  14320. }
  14321. return false;
  14322. }
  14323. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  14324. const PartialDiagnostic &PD) {
  14325. return DiagRuntimeBehavior(
  14326. Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
  14327. }
  14328. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  14329. CallExpr *CE, FunctionDecl *FD) {
  14330. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  14331. return false;
  14332. // If we're inside a decltype's expression, don't check for a valid return
  14333. // type or construct temporaries until we know whether this is the last call.
  14334. if (ExprEvalContexts.back().ExprContext ==
  14335. ExpressionEvaluationContextRecord::EK_Decltype) {
  14336. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  14337. return false;
  14338. }
  14339. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  14340. FunctionDecl *FD;
  14341. CallExpr *CE;
  14342. public:
  14343. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  14344. : FD(FD), CE(CE) { }
  14345. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  14346. if (!FD) {
  14347. S.Diag(Loc, diag::err_call_incomplete_return)
  14348. << T << CE->getSourceRange();
  14349. return;
  14350. }
  14351. S.Diag(Loc, diag::err_call_function_incomplete_return)
  14352. << CE->getSourceRange() << FD->getDeclName() << T;
  14353. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  14354. << FD->getDeclName();
  14355. }
  14356. } Diagnoser(FD, CE);
  14357. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  14358. return true;
  14359. return false;
  14360. }
  14361. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  14362. // will prevent this condition from triggering, which is what we want.
  14363. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  14364. SourceLocation Loc;
  14365. unsigned diagnostic = diag::warn_condition_is_assignment;
  14366. bool IsOrAssign = false;
  14367. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  14368. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  14369. return;
  14370. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  14371. // Greylist some idioms by putting them into a warning subcategory.
  14372. if (ObjCMessageExpr *ME
  14373. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  14374. Selector Sel = ME->getSelector();
  14375. // self = [<foo> init...]
  14376. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  14377. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  14378. // <foo> = [<bar> nextObject]
  14379. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  14380. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  14381. }
  14382. Loc = Op->getOperatorLoc();
  14383. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  14384. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  14385. return;
  14386. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  14387. Loc = Op->getOperatorLoc();
  14388. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  14389. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  14390. else {
  14391. // Not an assignment.
  14392. return;
  14393. }
  14394. Diag(Loc, diagnostic) << E->getSourceRange();
  14395. SourceLocation Open = E->getBeginLoc();
  14396. SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
  14397. Diag(Loc, diag::note_condition_assign_silence)
  14398. << FixItHint::CreateInsertion(Open, "(")
  14399. << FixItHint::CreateInsertion(Close, ")");
  14400. if (IsOrAssign)
  14401. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  14402. << FixItHint::CreateReplacement(Loc, "!=");
  14403. else
  14404. Diag(Loc, diag::note_condition_assign_to_comparison)
  14405. << FixItHint::CreateReplacement(Loc, "==");
  14406. }
  14407. /// Redundant parentheses over an equality comparison can indicate
  14408. /// that the user intended an assignment used as condition.
  14409. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  14410. // Don't warn if the parens came from a macro.
  14411. SourceLocation parenLoc = ParenE->getBeginLoc();
  14412. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  14413. return;
  14414. // Don't warn for dependent expressions.
  14415. if (ParenE->isTypeDependent())
  14416. return;
  14417. Expr *E = ParenE->IgnoreParens();
  14418. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  14419. if (opE->getOpcode() == BO_EQ &&
  14420. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  14421. == Expr::MLV_Valid) {
  14422. SourceLocation Loc = opE->getOperatorLoc();
  14423. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  14424. SourceRange ParenERange = ParenE->getSourceRange();
  14425. Diag(Loc, diag::note_equality_comparison_silence)
  14426. << FixItHint::CreateRemoval(ParenERange.getBegin())
  14427. << FixItHint::CreateRemoval(ParenERange.getEnd());
  14428. Diag(Loc, diag::note_equality_comparison_to_assign)
  14429. << FixItHint::CreateReplacement(Loc, "=");
  14430. }
  14431. }
  14432. ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
  14433. bool IsConstexpr) {
  14434. DiagnoseAssignmentAsCondition(E);
  14435. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  14436. DiagnoseEqualityWithExtraParens(parenE);
  14437. ExprResult result = CheckPlaceholderExpr(E);
  14438. if (result.isInvalid()) return ExprError();
  14439. E = result.get();
  14440. if (!E->isTypeDependent()) {
  14441. if (getLangOpts().CPlusPlus)
  14442. return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
  14443. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  14444. if (ERes.isInvalid())
  14445. return ExprError();
  14446. E = ERes.get();
  14447. QualType T = E->getType();
  14448. if (!T->isScalarType()) { // C99 6.8.4.1p1
  14449. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  14450. << T << E->getSourceRange();
  14451. return ExprError();
  14452. }
  14453. CheckBoolLikeConversion(E, Loc);
  14454. }
  14455. return E;
  14456. }
  14457. Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
  14458. Expr *SubExpr, ConditionKind CK) {
  14459. // Empty conditions are valid in for-statements.
  14460. if (!SubExpr)
  14461. return ConditionResult();
  14462. ExprResult Cond;
  14463. switch (CK) {
  14464. case ConditionKind::Boolean:
  14465. Cond = CheckBooleanCondition(Loc, SubExpr);
  14466. break;
  14467. case ConditionKind::ConstexprIf:
  14468. Cond = CheckBooleanCondition(Loc, SubExpr, true);
  14469. break;
  14470. case ConditionKind::Switch:
  14471. Cond = CheckSwitchCondition(Loc, SubExpr);
  14472. break;
  14473. }
  14474. if (Cond.isInvalid())
  14475. return ConditionError();
  14476. // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
  14477. FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
  14478. if (!FullExpr.get())
  14479. return ConditionError();
  14480. return ConditionResult(*this, nullptr, FullExpr,
  14481. CK == ConditionKind::ConstexprIf);
  14482. }
  14483. namespace {
  14484. /// A visitor for rebuilding a call to an __unknown_any expression
  14485. /// to have an appropriate type.
  14486. struct RebuildUnknownAnyFunction
  14487. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  14488. Sema &S;
  14489. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  14490. ExprResult VisitStmt(Stmt *S) {
  14491. llvm_unreachable("unexpected statement!");
  14492. }
  14493. ExprResult VisitExpr(Expr *E) {
  14494. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  14495. << E->getSourceRange();
  14496. return ExprError();
  14497. }
  14498. /// Rebuild an expression which simply semantically wraps another
  14499. /// expression which it shares the type and value kind of.
  14500. template <class T> ExprResult rebuildSugarExpr(T *E) {
  14501. ExprResult SubResult = Visit(E->getSubExpr());
  14502. if (SubResult.isInvalid()) return ExprError();
  14503. Expr *SubExpr = SubResult.get();
  14504. E->setSubExpr(SubExpr);
  14505. E->setType(SubExpr->getType());
  14506. E->setValueKind(SubExpr->getValueKind());
  14507. assert(E->getObjectKind() == OK_Ordinary);
  14508. return E;
  14509. }
  14510. ExprResult VisitParenExpr(ParenExpr *E) {
  14511. return rebuildSugarExpr(E);
  14512. }
  14513. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  14514. return rebuildSugarExpr(E);
  14515. }
  14516. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  14517. ExprResult SubResult = Visit(E->getSubExpr());
  14518. if (SubResult.isInvalid()) return ExprError();
  14519. Expr *SubExpr = SubResult.get();
  14520. E->setSubExpr(SubExpr);
  14521. E->setType(S.Context.getPointerType(SubExpr->getType()));
  14522. assert(E->getValueKind() == VK_RValue);
  14523. assert(E->getObjectKind() == OK_Ordinary);
  14524. return E;
  14525. }
  14526. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  14527. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  14528. E->setType(VD->getType());
  14529. assert(E->getValueKind() == VK_RValue);
  14530. if (S.getLangOpts().CPlusPlus &&
  14531. !(isa<CXXMethodDecl>(VD) &&
  14532. cast<CXXMethodDecl>(VD)->isInstance()))
  14533. E->setValueKind(VK_LValue);
  14534. return E;
  14535. }
  14536. ExprResult VisitMemberExpr(MemberExpr *E) {
  14537. return resolveDecl(E, E->getMemberDecl());
  14538. }
  14539. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  14540. return resolveDecl(E, E->getDecl());
  14541. }
  14542. };
  14543. }
  14544. /// Given a function expression of unknown-any type, try to rebuild it
  14545. /// to have a function type.
  14546. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  14547. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  14548. if (Result.isInvalid()) return ExprError();
  14549. return S.DefaultFunctionArrayConversion(Result.get());
  14550. }
  14551. namespace {
  14552. /// A visitor for rebuilding an expression of type __unknown_anytype
  14553. /// into one which resolves the type directly on the referring
  14554. /// expression. Strict preservation of the original source
  14555. /// structure is not a goal.
  14556. struct RebuildUnknownAnyExpr
  14557. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  14558. Sema &S;
  14559. /// The current destination type.
  14560. QualType DestType;
  14561. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  14562. : S(S), DestType(CastType) {}
  14563. ExprResult VisitStmt(Stmt *S) {
  14564. llvm_unreachable("unexpected statement!");
  14565. }
  14566. ExprResult VisitExpr(Expr *E) {
  14567. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  14568. << E->getSourceRange();
  14569. return ExprError();
  14570. }
  14571. ExprResult VisitCallExpr(CallExpr *E);
  14572. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  14573. /// Rebuild an expression which simply semantically wraps another
  14574. /// expression which it shares the type and value kind of.
  14575. template <class T> ExprResult rebuildSugarExpr(T *E) {
  14576. ExprResult SubResult = Visit(E->getSubExpr());
  14577. if (SubResult.isInvalid()) return ExprError();
  14578. Expr *SubExpr = SubResult.get();
  14579. E->setSubExpr(SubExpr);
  14580. E->setType(SubExpr->getType());
  14581. E->setValueKind(SubExpr->getValueKind());
  14582. assert(E->getObjectKind() == OK_Ordinary);
  14583. return E;
  14584. }
  14585. ExprResult VisitParenExpr(ParenExpr *E) {
  14586. return rebuildSugarExpr(E);
  14587. }
  14588. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  14589. return rebuildSugarExpr(E);
  14590. }
  14591. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  14592. const PointerType *Ptr = DestType->getAs<PointerType>();
  14593. if (!Ptr) {
  14594. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  14595. << E->getSourceRange();
  14596. return ExprError();
  14597. }
  14598. if (isa<CallExpr>(E->getSubExpr())) {
  14599. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
  14600. << E->getSourceRange();
  14601. return ExprError();
  14602. }
  14603. assert(E->getValueKind() == VK_RValue);
  14604. assert(E->getObjectKind() == OK_Ordinary);
  14605. E->setType(DestType);
  14606. // Build the sub-expression as if it were an object of the pointee type.
  14607. DestType = Ptr->getPointeeType();
  14608. ExprResult SubResult = Visit(E->getSubExpr());
  14609. if (SubResult.isInvalid()) return ExprError();
  14610. E->setSubExpr(SubResult.get());
  14611. return E;
  14612. }
  14613. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  14614. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  14615. ExprResult VisitMemberExpr(MemberExpr *E) {
  14616. return resolveDecl(E, E->getMemberDecl());
  14617. }
  14618. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  14619. return resolveDecl(E, E->getDecl());
  14620. }
  14621. };
  14622. }
  14623. /// Rebuilds a call expression which yielded __unknown_anytype.
  14624. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  14625. Expr *CalleeExpr = E->getCallee();
  14626. enum FnKind {
  14627. FK_MemberFunction,
  14628. FK_FunctionPointer,
  14629. FK_BlockPointer
  14630. };
  14631. FnKind Kind;
  14632. QualType CalleeType = CalleeExpr->getType();
  14633. if (CalleeType == S.Context.BoundMemberTy) {
  14634. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  14635. Kind = FK_MemberFunction;
  14636. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  14637. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  14638. CalleeType = Ptr->getPointeeType();
  14639. Kind = FK_FunctionPointer;
  14640. } else {
  14641. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  14642. Kind = FK_BlockPointer;
  14643. }
  14644. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  14645. // Verify that this is a legal result type of a function.
  14646. if (DestType->isArrayType() || DestType->isFunctionType()) {
  14647. unsigned diagID = diag::err_func_returning_array_function;
  14648. if (Kind == FK_BlockPointer)
  14649. diagID = diag::err_block_returning_array_function;
  14650. S.Diag(E->getExprLoc(), diagID)
  14651. << DestType->isFunctionType() << DestType;
  14652. return ExprError();
  14653. }
  14654. // Otherwise, go ahead and set DestType as the call's result.
  14655. E->setType(DestType.getNonLValueExprType(S.Context));
  14656. E->setValueKind(Expr::getValueKindForType(DestType));
  14657. assert(E->getObjectKind() == OK_Ordinary);
  14658. // Rebuild the function type, replacing the result type with DestType.
  14659. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  14660. if (Proto) {
  14661. // __unknown_anytype(...) is a special case used by the debugger when
  14662. // it has no idea what a function's signature is.
  14663. //
  14664. // We want to build this call essentially under the K&R
  14665. // unprototyped rules, but making a FunctionNoProtoType in C++
  14666. // would foul up all sorts of assumptions. However, we cannot
  14667. // simply pass all arguments as variadic arguments, nor can we
  14668. // portably just call the function under a non-variadic type; see
  14669. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  14670. // However, it turns out that in practice it is generally safe to
  14671. // call a function declared as "A foo(B,C,D);" under the prototype
  14672. // "A foo(B,C,D,...);". The only known exception is with the
  14673. // Windows ABI, where any variadic function is implicitly cdecl
  14674. // regardless of its normal CC. Therefore we change the parameter
  14675. // types to match the types of the arguments.
  14676. //
  14677. // This is a hack, but it is far superior to moving the
  14678. // corresponding target-specific code from IR-gen to Sema/AST.
  14679. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  14680. SmallVector<QualType, 8> ArgTypes;
  14681. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  14682. ArgTypes.reserve(E->getNumArgs());
  14683. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  14684. Expr *Arg = E->getArg(i);
  14685. QualType ArgType = Arg->getType();
  14686. if (E->isLValue()) {
  14687. ArgType = S.Context.getLValueReferenceType(ArgType);
  14688. } else if (E->isXValue()) {
  14689. ArgType = S.Context.getRValueReferenceType(ArgType);
  14690. }
  14691. ArgTypes.push_back(ArgType);
  14692. }
  14693. ParamTypes = ArgTypes;
  14694. }
  14695. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  14696. Proto->getExtProtoInfo());
  14697. } else {
  14698. DestType = S.Context.getFunctionNoProtoType(DestType,
  14699. FnType->getExtInfo());
  14700. }
  14701. // Rebuild the appropriate pointer-to-function type.
  14702. switch (Kind) {
  14703. case FK_MemberFunction:
  14704. // Nothing to do.
  14705. break;
  14706. case FK_FunctionPointer:
  14707. DestType = S.Context.getPointerType(DestType);
  14708. break;
  14709. case FK_BlockPointer:
  14710. DestType = S.Context.getBlockPointerType(DestType);
  14711. break;
  14712. }
  14713. // Finally, we can recurse.
  14714. ExprResult CalleeResult = Visit(CalleeExpr);
  14715. if (!CalleeResult.isUsable()) return ExprError();
  14716. E->setCallee(CalleeResult.get());
  14717. // Bind a temporary if necessary.
  14718. return S.MaybeBindToTemporary(E);
  14719. }
  14720. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  14721. // Verify that this is a legal result type of a call.
  14722. if (DestType->isArrayType() || DestType->isFunctionType()) {
  14723. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  14724. << DestType->isFunctionType() << DestType;
  14725. return ExprError();
  14726. }
  14727. // Rewrite the method result type if available.
  14728. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  14729. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  14730. Method->setReturnType(DestType);
  14731. }
  14732. // Change the type of the message.
  14733. E->setType(DestType.getNonReferenceType());
  14734. E->setValueKind(Expr::getValueKindForType(DestType));
  14735. return S.MaybeBindToTemporary(E);
  14736. }
  14737. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  14738. // The only case we should ever see here is a function-to-pointer decay.
  14739. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  14740. assert(E->getValueKind() == VK_RValue);
  14741. assert(E->getObjectKind() == OK_Ordinary);
  14742. E->setType(DestType);
  14743. // Rebuild the sub-expression as the pointee (function) type.
  14744. DestType = DestType->castAs<PointerType>()->getPointeeType();
  14745. ExprResult Result = Visit(E->getSubExpr());
  14746. if (!Result.isUsable()) return ExprError();
  14747. E->setSubExpr(Result.get());
  14748. return E;
  14749. } else if (E->getCastKind() == CK_LValueToRValue) {
  14750. assert(E->getValueKind() == VK_RValue);
  14751. assert(E->getObjectKind() == OK_Ordinary);
  14752. assert(isa<BlockPointerType>(E->getType()));
  14753. E->setType(DestType);
  14754. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  14755. DestType = S.Context.getLValueReferenceType(DestType);
  14756. ExprResult Result = Visit(E->getSubExpr());
  14757. if (!Result.isUsable()) return ExprError();
  14758. E->setSubExpr(Result.get());
  14759. return E;
  14760. } else {
  14761. llvm_unreachable("Unhandled cast type!");
  14762. }
  14763. }
  14764. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  14765. ExprValueKind ValueKind = VK_LValue;
  14766. QualType Type = DestType;
  14767. // We know how to make this work for certain kinds of decls:
  14768. // - functions
  14769. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  14770. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  14771. DestType = Ptr->getPointeeType();
  14772. ExprResult Result = resolveDecl(E, VD);
  14773. if (Result.isInvalid()) return ExprError();
  14774. return S.ImpCastExprToType(Result.get(), Type,
  14775. CK_FunctionToPointerDecay, VK_RValue);
  14776. }
  14777. if (!Type->isFunctionType()) {
  14778. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  14779. << VD << E->getSourceRange();
  14780. return ExprError();
  14781. }
  14782. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  14783. // We must match the FunctionDecl's type to the hack introduced in
  14784. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  14785. // type. See the lengthy commentary in that routine.
  14786. QualType FDT = FD->getType();
  14787. const FunctionType *FnType = FDT->castAs<FunctionType>();
  14788. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  14789. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  14790. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  14791. SourceLocation Loc = FD->getLocation();
  14792. FunctionDecl *NewFD = FunctionDecl::Create(S.Context,
  14793. FD->getDeclContext(),
  14794. Loc, Loc, FD->getNameInfo().getName(),
  14795. DestType, FD->getTypeSourceInfo(),
  14796. SC_None, false/*isInlineSpecified*/,
  14797. FD->hasPrototype(),
  14798. false/*isConstexprSpecified*/);
  14799. if (FD->getQualifier())
  14800. NewFD->setQualifierInfo(FD->getQualifierLoc());
  14801. SmallVector<ParmVarDecl*, 16> Params;
  14802. for (const auto &AI : FT->param_types()) {
  14803. ParmVarDecl *Param =
  14804. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  14805. Param->setScopeInfo(0, Params.size());
  14806. Params.push_back(Param);
  14807. }
  14808. NewFD->setParams(Params);
  14809. DRE->setDecl(NewFD);
  14810. VD = DRE->getDecl();
  14811. }
  14812. }
  14813. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  14814. if (MD->isInstance()) {
  14815. ValueKind = VK_RValue;
  14816. Type = S.Context.BoundMemberTy;
  14817. }
  14818. // Function references aren't l-values in C.
  14819. if (!S.getLangOpts().CPlusPlus)
  14820. ValueKind = VK_RValue;
  14821. // - variables
  14822. } else if (isa<VarDecl>(VD)) {
  14823. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  14824. Type = RefTy->getPointeeType();
  14825. } else if (Type->isFunctionType()) {
  14826. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  14827. << VD << E->getSourceRange();
  14828. return ExprError();
  14829. }
  14830. // - nothing else
  14831. } else {
  14832. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  14833. << VD << E->getSourceRange();
  14834. return ExprError();
  14835. }
  14836. // Modifying the declaration like this is friendly to IR-gen but
  14837. // also really dangerous.
  14838. VD->setType(DestType);
  14839. E->setType(Type);
  14840. E->setValueKind(ValueKind);
  14841. return E;
  14842. }
  14843. /// Check a cast of an unknown-any type. We intentionally only
  14844. /// trigger this for C-style casts.
  14845. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  14846. Expr *CastExpr, CastKind &CastKind,
  14847. ExprValueKind &VK, CXXCastPath &Path) {
  14848. // The type we're casting to must be either void or complete.
  14849. if (!CastType->isVoidType() &&
  14850. RequireCompleteType(TypeRange.getBegin(), CastType,
  14851. diag::err_typecheck_cast_to_incomplete))
  14852. return ExprError();
  14853. // Rewrite the casted expression from scratch.
  14854. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  14855. if (!result.isUsable()) return ExprError();
  14856. CastExpr = result.get();
  14857. VK = CastExpr->getValueKind();
  14858. CastKind = CK_NoOp;
  14859. return CastExpr;
  14860. }
  14861. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  14862. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  14863. }
  14864. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  14865. Expr *arg, QualType &paramType) {
  14866. // If the syntactic form of the argument is not an explicit cast of
  14867. // any sort, just do default argument promotion.
  14868. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  14869. if (!castArg) {
  14870. ExprResult result = DefaultArgumentPromotion(arg);
  14871. if (result.isInvalid()) return ExprError();
  14872. paramType = result.get()->getType();
  14873. return result;
  14874. }
  14875. // Otherwise, use the type that was written in the explicit cast.
  14876. assert(!arg->hasPlaceholderType());
  14877. paramType = castArg->getTypeAsWritten();
  14878. // Copy-initialize a parameter of that type.
  14879. InitializedEntity entity =
  14880. InitializedEntity::InitializeParameter(Context, paramType,
  14881. /*consumed*/ false);
  14882. return PerformCopyInitialization(entity, callLoc, arg);
  14883. }
  14884. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  14885. Expr *orig = E;
  14886. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  14887. while (true) {
  14888. E = E->IgnoreParenImpCasts();
  14889. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  14890. E = call->getCallee();
  14891. diagID = diag::err_uncasted_call_of_unknown_any;
  14892. } else {
  14893. break;
  14894. }
  14895. }
  14896. SourceLocation loc;
  14897. NamedDecl *d;
  14898. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  14899. loc = ref->getLocation();
  14900. d = ref->getDecl();
  14901. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  14902. loc = mem->getMemberLoc();
  14903. d = mem->getMemberDecl();
  14904. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  14905. diagID = diag::err_uncasted_call_of_unknown_any;
  14906. loc = msg->getSelectorStartLoc();
  14907. d = msg->getMethodDecl();
  14908. if (!d) {
  14909. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  14910. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  14911. << orig->getSourceRange();
  14912. return ExprError();
  14913. }
  14914. } else {
  14915. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  14916. << E->getSourceRange();
  14917. return ExprError();
  14918. }
  14919. S.Diag(loc, diagID) << d << orig->getSourceRange();
  14920. // Never recoverable.
  14921. return ExprError();
  14922. }
  14923. /// Check for operands with placeholder types and complain if found.
  14924. /// Returns ExprError() if there was an error and no recovery was possible.
  14925. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  14926. if (!getLangOpts().CPlusPlus) {
  14927. // C cannot handle TypoExpr nodes on either side of a binop because it
  14928. // doesn't handle dependent types properly, so make sure any TypoExprs have
  14929. // been dealt with before checking the operands.
  14930. ExprResult Result = CorrectDelayedTyposInExpr(E);
  14931. if (!Result.isUsable()) return ExprError();
  14932. E = Result.get();
  14933. }
  14934. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  14935. if (!placeholderType) return E;
  14936. switch (placeholderType->getKind()) {
  14937. // Overloaded expressions.
  14938. case BuiltinType::Overload: {
  14939. // Try to resolve a single function template specialization.
  14940. // This is obligatory.
  14941. ExprResult Result = E;
  14942. if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
  14943. return Result;
  14944. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  14945. // leaves Result unchanged on failure.
  14946. Result = E;
  14947. if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
  14948. return Result;
  14949. // If that failed, try to recover with a call.
  14950. tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
  14951. /*complain*/ true);
  14952. return Result;
  14953. }
  14954. // Bound member functions.
  14955. case BuiltinType::BoundMember: {
  14956. ExprResult result = E;
  14957. const Expr *BME = E->IgnoreParens();
  14958. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  14959. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  14960. if (isa<CXXPseudoDestructorExpr>(BME)) {
  14961. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  14962. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  14963. if (ME->getMemberNameInfo().getName().getNameKind() ==
  14964. DeclarationName::CXXDestructorName)
  14965. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  14966. }
  14967. tryToRecoverWithCall(result, PD,
  14968. /*complain*/ true);
  14969. return result;
  14970. }
  14971. // ARC unbridged casts.
  14972. case BuiltinType::ARCUnbridgedCast: {
  14973. Expr *realCast = stripARCUnbridgedCast(E);
  14974. diagnoseARCUnbridgedCast(realCast);
  14975. return realCast;
  14976. }
  14977. // Expressions of unknown type.
  14978. case BuiltinType::UnknownAny:
  14979. return diagnoseUnknownAnyExpr(*this, E);
  14980. // Pseudo-objects.
  14981. case BuiltinType::PseudoObject:
  14982. return checkPseudoObjectRValue(E);
  14983. case BuiltinType::BuiltinFn: {
  14984. // Accept __noop without parens by implicitly converting it to a call expr.
  14985. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  14986. if (DRE) {
  14987. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  14988. if (FD->getBuiltinID() == Builtin::BI__noop) {
  14989. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  14990. CK_BuiltinFnToFnPtr)
  14991. .get();
  14992. return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
  14993. VK_RValue, SourceLocation());
  14994. }
  14995. }
  14996. Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
  14997. return ExprError();
  14998. }
  14999. // Expressions of unknown type.
  15000. case BuiltinType::OMPArraySection:
  15001. Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
  15002. return ExprError();
  15003. // Everything else should be impossible.
  15004. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  15005. case BuiltinType::Id:
  15006. #include "clang/Basic/OpenCLImageTypes.def"
  15007. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  15008. case BuiltinType::Id:
  15009. #include "clang/Basic/OpenCLExtensionTypes.def"
  15010. #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
  15011. #define PLACEHOLDER_TYPE(Id, SingletonId)
  15012. #include "clang/AST/BuiltinTypes.def"
  15013. break;
  15014. }
  15015. llvm_unreachable("invalid placeholder type!");
  15016. }
  15017. bool Sema::CheckCaseExpression(Expr *E) {
  15018. if (E->isTypeDependent())
  15019. return true;
  15020. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  15021. return E->getType()->isIntegralOrEnumerationType();
  15022. return false;
  15023. }
  15024. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  15025. ExprResult
  15026. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  15027. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  15028. "Unknown Objective-C Boolean value!");
  15029. QualType BoolT = Context.ObjCBuiltinBoolTy;
  15030. if (!Context.getBOOLDecl()) {
  15031. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  15032. Sema::LookupOrdinaryName);
  15033. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  15034. NamedDecl *ND = Result.getFoundDecl();
  15035. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  15036. Context.setBOOLDecl(TD);
  15037. }
  15038. }
  15039. if (Context.getBOOLDecl())
  15040. BoolT = Context.getBOOLType();
  15041. return new (Context)
  15042. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  15043. }
  15044. ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
  15045. llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
  15046. SourceLocation RParen) {
  15047. StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
  15048. auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
  15049. return Spec.getPlatform() == Platform;
  15050. });
  15051. VersionTuple Version;
  15052. if (Spec != AvailSpecs.end())
  15053. Version = Spec->getVersion();
  15054. // The use of `@available` in the enclosing function should be analyzed to
  15055. // warn when it's used inappropriately (i.e. not if(@available)).
  15056. if (getCurFunctionOrMethodDecl())
  15057. getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
  15058. else if (getCurBlock() || getCurLambda())
  15059. getCurFunction()->HasPotentialAvailabilityViolations = true;
  15060. return new (Context)
  15061. ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
  15062. }