SemaExpr.cpp 638 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458
  1. //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for expressions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "TreeTransform.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/ASTMutationListener.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/EvaluatedExprVisitor.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/ExprObjC.h"
  25. #include "clang/AST/ExprOpenMP.h"
  26. #include "clang/AST/RecursiveASTVisitor.h"
  27. #include "clang/AST/TypeLoc.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. }
  65. // See if this function is unavailable.
  66. if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
  67. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  68. return false;
  69. return true;
  70. }
  71. static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  72. // Warn if this is used but marked unused.
  73. if (const auto *A = D->getAttr<UnusedAttr>()) {
  74. // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
  75. // should diagnose them.
  76. if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
  77. A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
  78. const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
  79. if (DC && !DC->hasAttr<UnusedAttr>())
  80. S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
  81. }
  82. }
  83. }
  84. /// Emit a note explaining that this function is deleted.
  85. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  86. assert(Decl->isDeleted());
  87. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
  88. if (Method && Method->isDeleted() && Method->isDefaulted()) {
  89. // If the method was explicitly defaulted, point at that declaration.
  90. if (!Method->isImplicit())
  91. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  92. // Try to diagnose why this special member function was implicitly
  93. // deleted. This might fail, if that reason no longer applies.
  94. CXXSpecialMember CSM = getSpecialMember(Method);
  95. if (CSM != CXXInvalid)
  96. ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
  97. return;
  98. }
  99. auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
  100. if (Ctor && Ctor->isInheritingConstructor())
  101. return NoteDeletedInheritingConstructor(Ctor);
  102. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  103. << Decl << true;
  104. }
  105. /// Determine whether a FunctionDecl was ever declared with an
  106. /// explicit storage class.
  107. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  108. for (auto I : D->redecls()) {
  109. if (I->getStorageClass() != SC_None)
  110. return true;
  111. }
  112. return false;
  113. }
  114. /// Check whether we're in an extern inline function and referring to a
  115. /// variable or function with internal linkage (C11 6.7.4p3).
  116. ///
  117. /// This is only a warning because we used to silently accept this code, but
  118. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  119. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  120. /// and so while there may still be user mistakes, most of the time we can't
  121. /// prove that there are errors.
  122. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  123. const NamedDecl *D,
  124. SourceLocation Loc) {
  125. // This is disabled under C++; there are too many ways for this to fire in
  126. // contexts where the warning is a false positive, or where it is technically
  127. // correct but benign.
  128. if (S.getLangOpts().CPlusPlus)
  129. return;
  130. // Check if this is an inlined function or method.
  131. FunctionDecl *Current = S.getCurFunctionDecl();
  132. if (!Current)
  133. return;
  134. if (!Current->isInlined())
  135. return;
  136. if (!Current->isExternallyVisible())
  137. return;
  138. // Check if the decl has internal linkage.
  139. if (D->getFormalLinkage() != InternalLinkage)
  140. return;
  141. // Downgrade from ExtWarn to Extension if
  142. // (1) the supposedly external inline function is in the main file,
  143. // and probably won't be included anywhere else.
  144. // (2) the thing we're referencing is a pure function.
  145. // (3) the thing we're referencing is another inline function.
  146. // This last can give us false negatives, but it's better than warning on
  147. // wrappers for simple C library functions.
  148. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  149. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  150. if (!DowngradeWarning && UsedFn)
  151. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  152. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  153. : diag::ext_internal_in_extern_inline)
  154. << /*IsVar=*/!UsedFn << D;
  155. S.MaybeSuggestAddingStaticToDecl(Current);
  156. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  157. << D;
  158. }
  159. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  160. const FunctionDecl *First = Cur->getFirstDecl();
  161. // Suggest "static" on the function, if possible.
  162. if (!hasAnyExplicitStorageClass(First)) {
  163. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  164. Diag(DeclBegin, diag::note_convert_inline_to_static)
  165. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  166. }
  167. }
  168. /// Determine whether the use of this declaration is valid, and
  169. /// emit any corresponding diagnostics.
  170. ///
  171. /// This routine diagnoses various problems with referencing
  172. /// declarations that can occur when using a declaration. For example,
  173. /// it might warn if a deprecated or unavailable declaration is being
  174. /// used, or produce an error (and return true) if a C++0x deleted
  175. /// function is being used.
  176. ///
  177. /// \returns true if there was an error (this declaration cannot be
  178. /// referenced), false otherwise.
  179. ///
  180. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
  181. const ObjCInterfaceDecl *UnknownObjCClass,
  182. bool ObjCPropertyAccess,
  183. bool AvoidPartialAvailabilityChecks) {
  184. SourceLocation Loc = Locs.front();
  185. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  186. // If there were any diagnostics suppressed by template argument deduction,
  187. // emit them now.
  188. auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  189. if (Pos != SuppressedDiagnostics.end()) {
  190. for (const PartialDiagnosticAt &Suppressed : Pos->second)
  191. Diag(Suppressed.first, Suppressed.second);
  192. // Clear out the list of suppressed diagnostics, so that we don't emit
  193. // them again for this specialization. However, we don't obsolete this
  194. // entry from the table, because we want to avoid ever emitting these
  195. // diagnostics again.
  196. Pos->second.clear();
  197. }
  198. // C++ [basic.start.main]p3:
  199. // The function 'main' shall not be used within a program.
  200. if (cast<FunctionDecl>(D)->isMain())
  201. Diag(Loc, diag::ext_main_used);
  202. }
  203. // See if this is an auto-typed variable whose initializer we are parsing.
  204. if (ParsingInitForAutoVars.count(D)) {
  205. if (isa<BindingDecl>(D)) {
  206. Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
  207. << D->getDeclName();
  208. } else {
  209. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  210. << D->getDeclName() << cast<VarDecl>(D)->getType();
  211. }
  212. return true;
  213. }
  214. // See if this is a deleted function.
  215. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  216. if (FD->isDeleted()) {
  217. auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
  218. if (Ctor && Ctor->isInheritingConstructor())
  219. Diag(Loc, diag::err_deleted_inherited_ctor_use)
  220. << Ctor->getParent()
  221. << Ctor->getInheritedConstructor().getConstructor()->getParent();
  222. else
  223. Diag(Loc, diag::err_deleted_function_use);
  224. NoteDeletedFunction(FD);
  225. return true;
  226. }
  227. // If the function has a deduced return type, and we can't deduce it,
  228. // then we can't use it either.
  229. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  230. DeduceReturnType(FD, Loc))
  231. return true;
  232. if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
  233. return true;
  234. }
  235. auto getReferencedObjCProp = [](const NamedDecl *D) ->
  236. const ObjCPropertyDecl * {
  237. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  238. return MD->findPropertyDecl();
  239. return nullptr;
  240. };
  241. if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
  242. if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
  243. return true;
  244. } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
  245. return true;
  246. }
  247. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  248. // Only the variables omp_in and omp_out are allowed in the combiner.
  249. // Only the variables omp_priv and omp_orig are allowed in the
  250. // initializer-clause.
  251. auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
  252. if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
  253. isa<VarDecl>(D)) {
  254. Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
  255. << getCurFunction()->HasOMPDeclareReductionCombiner;
  256. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  257. return true;
  258. }
  259. DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
  260. AvoidPartialAvailabilityChecks);
  261. DiagnoseUnusedOfDecl(*this, D, Loc);
  262. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  263. return false;
  264. }
  265. /// Retrieve the message suffix that should be added to a
  266. /// diagnostic complaining about the given function being deleted or
  267. /// unavailable.
  268. std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
  269. std::string Message;
  270. if (FD->getAvailability(&Message))
  271. return ": " + Message;
  272. return std::string();
  273. }
  274. /// DiagnoseSentinelCalls - This routine checks whether a call or
  275. /// message-send is to a declaration with the sentinel attribute, and
  276. /// if so, it checks that the requirements of the sentinel are
  277. /// satisfied.
  278. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  279. ArrayRef<Expr *> Args) {
  280. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  281. if (!attr)
  282. return;
  283. // The number of formal parameters of the declaration.
  284. unsigned numFormalParams;
  285. // The kind of declaration. This is also an index into a %select in
  286. // the diagnostic.
  287. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  288. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  289. numFormalParams = MD->param_size();
  290. calleeType = CT_Method;
  291. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  292. numFormalParams = FD->param_size();
  293. calleeType = CT_Function;
  294. } else if (isa<VarDecl>(D)) {
  295. QualType type = cast<ValueDecl>(D)->getType();
  296. const FunctionType *fn = nullptr;
  297. if (const PointerType *ptr = type->getAs<PointerType>()) {
  298. fn = ptr->getPointeeType()->getAs<FunctionType>();
  299. if (!fn) return;
  300. calleeType = CT_Function;
  301. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  302. fn = ptr->getPointeeType()->castAs<FunctionType>();
  303. calleeType = CT_Block;
  304. } else {
  305. return;
  306. }
  307. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  308. numFormalParams = proto->getNumParams();
  309. } else {
  310. numFormalParams = 0;
  311. }
  312. } else {
  313. return;
  314. }
  315. // "nullPos" is the number of formal parameters at the end which
  316. // effectively count as part of the variadic arguments. This is
  317. // useful if you would prefer to not have *any* formal parameters,
  318. // but the language forces you to have at least one.
  319. unsigned nullPos = attr->getNullPos();
  320. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  321. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  322. // The number of arguments which should follow the sentinel.
  323. unsigned numArgsAfterSentinel = attr->getSentinel();
  324. // If there aren't enough arguments for all the formal parameters,
  325. // the sentinel, and the args after the sentinel, complain.
  326. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  327. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  328. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  329. return;
  330. }
  331. // Otherwise, find the sentinel expression.
  332. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  333. if (!sentinelExpr) return;
  334. if (sentinelExpr->isValueDependent()) return;
  335. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  336. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  337. // or 'NULL' if those are actually defined in the context. Only use
  338. // 'nil' for ObjC methods, where it's much more likely that the
  339. // variadic arguments form a list of object pointers.
  340. SourceLocation MissingNilLoc
  341. = getLocForEndOfToken(sentinelExpr->getLocEnd());
  342. std::string NullValue;
  343. if (calleeType == CT_Method && PP.isMacroDefined("nil"))
  344. NullValue = "nil";
  345. else if (getLangOpts().CPlusPlus11)
  346. NullValue = "nullptr";
  347. else if (PP.isMacroDefined("NULL"))
  348. NullValue = "NULL";
  349. else
  350. NullValue = "(void*) 0";
  351. if (MissingNilLoc.isInvalid())
  352. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  353. else
  354. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  355. << int(calleeType)
  356. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  357. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  358. }
  359. SourceRange Sema::getExprRange(Expr *E) const {
  360. return E ? E->getSourceRange() : SourceRange();
  361. }
  362. //===----------------------------------------------------------------------===//
  363. // Standard Promotions and Conversions
  364. //===----------------------------------------------------------------------===//
  365. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  366. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
  367. // Handle any placeholder expressions which made it here.
  368. if (E->getType()->isPlaceholderType()) {
  369. ExprResult result = CheckPlaceholderExpr(E);
  370. if (result.isInvalid()) return ExprError();
  371. E = result.get();
  372. }
  373. QualType Ty = E->getType();
  374. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  375. if (Ty->isFunctionType()) {
  376. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
  377. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
  378. if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
  379. return ExprError();
  380. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  381. CK_FunctionToPointerDecay).get();
  382. } else if (Ty->isArrayType()) {
  383. // In C90 mode, arrays only promote to pointers if the array expression is
  384. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  385. // type 'array of type' is converted to an expression that has type 'pointer
  386. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  387. // that has type 'array of type' ...". The relevant change is "an lvalue"
  388. // (C90) to "an expression" (C99).
  389. //
  390. // C++ 4.2p1:
  391. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  392. // T" can be converted to an rvalue of type "pointer to T".
  393. //
  394. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
  395. E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  396. CK_ArrayToPointerDecay).get();
  397. }
  398. return E;
  399. }
  400. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  401. // Check to see if we are dereferencing a null pointer. If so,
  402. // and if not volatile-qualified, this is undefined behavior that the
  403. // optimizer will delete, so warn about it. People sometimes try to use this
  404. // to get a deterministic trap and are surprised by clang's behavior. This
  405. // only handles the pattern "*null", which is a very syntactic check.
  406. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  407. if (UO->getOpcode() == UO_Deref &&
  408. UO->getSubExpr()->IgnoreParenCasts()->
  409. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  410. !UO->getType().isVolatileQualified()) {
  411. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  412. S.PDiag(diag::warn_indirection_through_null)
  413. << UO->getSubExpr()->getSourceRange());
  414. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  415. S.PDiag(diag::note_indirection_through_null));
  416. }
  417. }
  418. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  419. SourceLocation AssignLoc,
  420. const Expr* RHS) {
  421. const ObjCIvarDecl *IV = OIRE->getDecl();
  422. if (!IV)
  423. return;
  424. DeclarationName MemberName = IV->getDeclName();
  425. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  426. if (!Member || !Member->isStr("isa"))
  427. return;
  428. const Expr *Base = OIRE->getBase();
  429. QualType BaseType = Base->getType();
  430. if (OIRE->isArrow())
  431. BaseType = BaseType->getPointeeType();
  432. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  433. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  434. ObjCInterfaceDecl *ClassDeclared = nullptr;
  435. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  436. if (!ClassDeclared->getSuperClass()
  437. && (*ClassDeclared->ivar_begin()) == IV) {
  438. if (RHS) {
  439. NamedDecl *ObjectSetClass =
  440. S.LookupSingleName(S.TUScope,
  441. &S.Context.Idents.get("object_setClass"),
  442. SourceLocation(), S.LookupOrdinaryName);
  443. if (ObjectSetClass) {
  444. SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
  445. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
  446. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
  447. FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
  448. AssignLoc), ",") <<
  449. FixItHint::CreateInsertion(RHSLocEnd, ")");
  450. }
  451. else
  452. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  453. } else {
  454. NamedDecl *ObjectGetClass =
  455. S.LookupSingleName(S.TUScope,
  456. &S.Context.Idents.get("object_getClass"),
  457. SourceLocation(), S.LookupOrdinaryName);
  458. if (ObjectGetClass)
  459. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
  460. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
  461. FixItHint::CreateReplacement(
  462. SourceRange(OIRE->getOpLoc(),
  463. OIRE->getLocEnd()), ")");
  464. else
  465. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  466. }
  467. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  468. }
  469. }
  470. }
  471. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  472. // Handle any placeholder expressions which made it here.
  473. if (E->getType()->isPlaceholderType()) {
  474. ExprResult result = CheckPlaceholderExpr(E);
  475. if (result.isInvalid()) return ExprError();
  476. E = result.get();
  477. }
  478. // C++ [conv.lval]p1:
  479. // A glvalue of a non-function, non-array type T can be
  480. // converted to a prvalue.
  481. if (!E->isGLValue()) return E;
  482. QualType T = E->getType();
  483. assert(!T.isNull() && "r-value conversion on typeless expression?");
  484. // We don't want to throw lvalue-to-rvalue casts on top of
  485. // expressions of certain types in C++.
  486. if (getLangOpts().CPlusPlus &&
  487. (E->getType() == Context.OverloadTy ||
  488. T->isDependentType() ||
  489. T->isRecordType()))
  490. return E;
  491. // The C standard is actually really unclear on this point, and
  492. // DR106 tells us what the result should be but not why. It's
  493. // generally best to say that void types just doesn't undergo
  494. // lvalue-to-rvalue at all. Note that expressions of unqualified
  495. // 'void' type are never l-values, but qualified void can be.
  496. if (T->isVoidType())
  497. return E;
  498. // OpenCL usually rejects direct accesses to values of 'half' type.
  499. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  500. T->isHalfType()) {
  501. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  502. << 0 << T;
  503. return ExprError();
  504. }
  505. CheckForNullPointerDereference(*this, E);
  506. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  507. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  508. &Context.Idents.get("object_getClass"),
  509. SourceLocation(), LookupOrdinaryName);
  510. if (ObjectGetClass)
  511. Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
  512. FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
  513. FixItHint::CreateReplacement(
  514. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  515. else
  516. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  517. }
  518. else if (const ObjCIvarRefExpr *OIRE =
  519. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  520. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  521. // C++ [conv.lval]p1:
  522. // [...] If T is a non-class type, the type of the prvalue is the
  523. // cv-unqualified version of T. Otherwise, the type of the
  524. // rvalue is T.
  525. //
  526. // C99 6.3.2.1p2:
  527. // If the lvalue has qualified type, the value has the unqualified
  528. // version of the type of the lvalue; otherwise, the value has the
  529. // type of the lvalue.
  530. if (T.hasQualifiers())
  531. T = T.getUnqualifiedType();
  532. // Under the MS ABI, lock down the inheritance model now.
  533. if (T->isMemberPointerType() &&
  534. Context.getTargetInfo().getCXXABI().isMicrosoft())
  535. (void)isCompleteType(E->getExprLoc(), T);
  536. UpdateMarkingForLValueToRValue(E);
  537. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  538. // balance that.
  539. if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  540. Cleanup.setExprNeedsCleanups(true);
  541. ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
  542. nullptr, VK_RValue);
  543. // C11 6.3.2.1p2:
  544. // ... if the lvalue has atomic type, the value has the non-atomic version
  545. // of the type of the lvalue ...
  546. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  547. T = Atomic->getValueType().getUnqualifiedType();
  548. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  549. nullptr, VK_RValue);
  550. }
  551. return Res;
  552. }
  553. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
  554. ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
  555. if (Res.isInvalid())
  556. return ExprError();
  557. Res = DefaultLvalueConversion(Res.get());
  558. if (Res.isInvalid())
  559. return ExprError();
  560. return Res;
  561. }
  562. /// CallExprUnaryConversions - a special case of an unary conversion
  563. /// performed on a function designator of a call expression.
  564. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  565. QualType Ty = E->getType();
  566. ExprResult Res = E;
  567. // Only do implicit cast for a function type, but not for a pointer
  568. // to function type.
  569. if (Ty->isFunctionType()) {
  570. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  571. CK_FunctionToPointerDecay).get();
  572. if (Res.isInvalid())
  573. return ExprError();
  574. }
  575. Res = DefaultLvalueConversion(Res.get());
  576. if (Res.isInvalid())
  577. return ExprError();
  578. return Res.get();
  579. }
  580. /// UsualUnaryConversions - Performs various conversions that are common to most
  581. /// operators (C99 6.3). The conversions of array and function types are
  582. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  583. /// apply if the array is an argument to the sizeof or address (&) operators.
  584. /// In these instances, this routine should *not* be called.
  585. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  586. // First, convert to an r-value.
  587. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  588. if (Res.isInvalid())
  589. return ExprError();
  590. E = Res.get();
  591. QualType Ty = E->getType();
  592. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  593. // Half FP have to be promoted to float unless it is natively supported
  594. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  595. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  596. // Try to perform integral promotions if the object has a theoretically
  597. // promotable type.
  598. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  599. // C99 6.3.1.1p2:
  600. //
  601. // The following may be used in an expression wherever an int or
  602. // unsigned int may be used:
  603. // - an object or expression with an integer type whose integer
  604. // conversion rank is less than or equal to the rank of int
  605. // and unsigned int.
  606. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  607. //
  608. // If an int can represent all values of the original type, the
  609. // value is converted to an int; otherwise, it is converted to an
  610. // unsigned int. These are called the integer promotions. All
  611. // other types are unchanged by the integer promotions.
  612. QualType PTy = Context.isPromotableBitField(E);
  613. if (!PTy.isNull()) {
  614. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  615. return E;
  616. }
  617. if (Ty->isPromotableIntegerType()) {
  618. QualType PT = Context.getPromotedIntegerType(Ty);
  619. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  620. return E;
  621. }
  622. }
  623. return E;
  624. }
  625. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  626. /// do not have a prototype. Arguments that have type float or __fp16
  627. /// are promoted to double. All other argument types are converted by
  628. /// UsualUnaryConversions().
  629. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  630. QualType Ty = E->getType();
  631. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  632. ExprResult Res = UsualUnaryConversions(E);
  633. if (Res.isInvalid())
  634. return ExprError();
  635. E = Res.get();
  636. // If this is a 'float' or '__fp16' (CVR qualified or typedef)
  637. // promote to double.
  638. // Note that default argument promotion applies only to float (and
  639. // half/fp16); it does not apply to _Float16.
  640. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  641. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  642. BTy->getKind() == BuiltinType::Float)) {
  643. if (getLangOpts().OpenCL &&
  644. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  645. if (BTy->getKind() == BuiltinType::Half) {
  646. E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
  647. }
  648. } else {
  649. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  650. }
  651. }
  652. // C++ performs lvalue-to-rvalue conversion as a default argument
  653. // promotion, even on class types, but note:
  654. // C++11 [conv.lval]p2:
  655. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  656. // operand or a subexpression thereof the value contained in the
  657. // referenced object is not accessed. Otherwise, if the glvalue
  658. // has a class type, the conversion copy-initializes a temporary
  659. // of type T from the glvalue and the result of the conversion
  660. // is a prvalue for the temporary.
  661. // FIXME: add some way to gate this entire thing for correctness in
  662. // potentially potentially evaluated contexts.
  663. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  664. ExprResult Temp = PerformCopyInitialization(
  665. InitializedEntity::InitializeTemporary(E->getType()),
  666. E->getExprLoc(), E);
  667. if (Temp.isInvalid())
  668. return ExprError();
  669. E = Temp.get();
  670. }
  671. return E;
  672. }
  673. /// Determine the degree of POD-ness for an expression.
  674. /// Incomplete types are considered POD, since this check can be performed
  675. /// when we're in an unevaluated context.
  676. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  677. if (Ty->isIncompleteType()) {
  678. // C++11 [expr.call]p7:
  679. // After these conversions, if the argument does not have arithmetic,
  680. // enumeration, pointer, pointer to member, or class type, the program
  681. // is ill-formed.
  682. //
  683. // Since we've already performed array-to-pointer and function-to-pointer
  684. // decay, the only such type in C++ is cv void. This also handles
  685. // initializer lists as variadic arguments.
  686. if (Ty->isVoidType())
  687. return VAK_Invalid;
  688. if (Ty->isObjCObjectType())
  689. return VAK_Invalid;
  690. return VAK_Valid;
  691. }
  692. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  693. return VAK_Invalid;
  694. if (Ty.isCXX98PODType(Context))
  695. return VAK_Valid;
  696. // C++11 [expr.call]p7:
  697. // Passing a potentially-evaluated argument of class type (Clause 9)
  698. // having a non-trivial copy constructor, a non-trivial move constructor,
  699. // or a non-trivial destructor, with no corresponding parameter,
  700. // is conditionally-supported with implementation-defined semantics.
  701. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  702. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  703. if (!Record->hasNonTrivialCopyConstructor() &&
  704. !Record->hasNonTrivialMoveConstructor() &&
  705. !Record->hasNonTrivialDestructor())
  706. return VAK_ValidInCXX11;
  707. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  708. return VAK_Valid;
  709. if (Ty->isObjCObjectType())
  710. return VAK_Invalid;
  711. if (getLangOpts().MSVCCompat)
  712. return VAK_MSVCUndefined;
  713. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  714. // permitted to reject them. We should consider doing so.
  715. return VAK_Undefined;
  716. }
  717. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  718. // Don't allow one to pass an Objective-C interface to a vararg.
  719. const QualType &Ty = E->getType();
  720. VarArgKind VAK = isValidVarArgType(Ty);
  721. // Complain about passing non-POD types through varargs.
  722. switch (VAK) {
  723. case VAK_ValidInCXX11:
  724. DiagRuntimeBehavior(
  725. E->getLocStart(), nullptr,
  726. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
  727. << Ty << CT);
  728. LLVM_FALLTHROUGH;
  729. case VAK_Valid:
  730. if (Ty->isRecordType()) {
  731. // This is unlikely to be what the user intended. If the class has a
  732. // 'c_str' member function, the user probably meant to call that.
  733. DiagRuntimeBehavior(E->getLocStart(), nullptr,
  734. PDiag(diag::warn_pass_class_arg_to_vararg)
  735. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  736. }
  737. break;
  738. case VAK_Undefined:
  739. case VAK_MSVCUndefined:
  740. DiagRuntimeBehavior(
  741. E->getLocStart(), nullptr,
  742. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  743. << getLangOpts().CPlusPlus11 << Ty << CT);
  744. break;
  745. case VAK_Invalid:
  746. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  747. Diag(E->getLocStart(),
  748. diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT;
  749. else if (Ty->isObjCObjectType())
  750. DiagRuntimeBehavior(
  751. E->getLocStart(), nullptr,
  752. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  753. << Ty << CT);
  754. else
  755. Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
  756. << isa<InitListExpr>(E) << Ty << CT;
  757. break;
  758. }
  759. }
  760. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  761. /// will create a trap if the resulting type is not a POD type.
  762. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  763. FunctionDecl *FDecl) {
  764. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  765. // Strip the unbridged-cast placeholder expression off, if applicable.
  766. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  767. (CT == VariadicMethod ||
  768. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  769. E = stripARCUnbridgedCast(E);
  770. // Otherwise, do normal placeholder checking.
  771. } else {
  772. ExprResult ExprRes = CheckPlaceholderExpr(E);
  773. if (ExprRes.isInvalid())
  774. return ExprError();
  775. E = ExprRes.get();
  776. }
  777. }
  778. ExprResult ExprRes = DefaultArgumentPromotion(E);
  779. if (ExprRes.isInvalid())
  780. return ExprError();
  781. E = ExprRes.get();
  782. // Diagnostics regarding non-POD argument types are
  783. // emitted along with format string checking in Sema::CheckFunctionCall().
  784. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  785. // Turn this into a trap.
  786. CXXScopeSpec SS;
  787. SourceLocation TemplateKWLoc;
  788. UnqualifiedId Name;
  789. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  790. E->getLocStart());
  791. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
  792. Name, true, false);
  793. if (TrapFn.isInvalid())
  794. return ExprError();
  795. ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
  796. E->getLocStart(), None,
  797. E->getLocEnd());
  798. if (Call.isInvalid())
  799. return ExprError();
  800. ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
  801. Call.get(), E);
  802. if (Comma.isInvalid())
  803. return ExprError();
  804. return Comma.get();
  805. }
  806. if (!getLangOpts().CPlusPlus &&
  807. RequireCompleteType(E->getExprLoc(), E->getType(),
  808. diag::err_call_incomplete_argument))
  809. return ExprError();
  810. return E;
  811. }
  812. /// Converts an integer to complex float type. Helper function of
  813. /// UsualArithmeticConversions()
  814. ///
  815. /// \return false if the integer expression is an integer type and is
  816. /// successfully converted to the complex type.
  817. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  818. ExprResult &ComplexExpr,
  819. QualType IntTy,
  820. QualType ComplexTy,
  821. bool SkipCast) {
  822. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  823. if (SkipCast) return false;
  824. if (IntTy->isIntegerType()) {
  825. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  826. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  827. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  828. CK_FloatingRealToComplex);
  829. } else {
  830. assert(IntTy->isComplexIntegerType());
  831. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  832. CK_IntegralComplexToFloatingComplex);
  833. }
  834. return false;
  835. }
  836. /// Handle arithmetic conversion with complex types. Helper function of
  837. /// UsualArithmeticConversions()
  838. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  839. ExprResult &RHS, QualType LHSType,
  840. QualType RHSType,
  841. bool IsCompAssign) {
  842. // if we have an integer operand, the result is the complex type.
  843. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  844. /*skipCast*/false))
  845. return LHSType;
  846. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  847. /*skipCast*/IsCompAssign))
  848. return RHSType;
  849. // This handles complex/complex, complex/float, or float/complex.
  850. // When both operands are complex, the shorter operand is converted to the
  851. // type of the longer, and that is the type of the result. This corresponds
  852. // to what is done when combining two real floating-point operands.
  853. // The fun begins when size promotion occur across type domains.
  854. // From H&S 6.3.4: When one operand is complex and the other is a real
  855. // floating-point type, the less precise type is converted, within it's
  856. // real or complex domain, to the precision of the other type. For example,
  857. // when combining a "long double" with a "double _Complex", the
  858. // "double _Complex" is promoted to "long double _Complex".
  859. // Compute the rank of the two types, regardless of whether they are complex.
  860. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  861. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  862. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  863. QualType LHSElementType =
  864. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  865. QualType RHSElementType =
  866. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  867. QualType ResultType = S.Context.getComplexType(LHSElementType);
  868. if (Order < 0) {
  869. // Promote the precision of the LHS if not an assignment.
  870. ResultType = S.Context.getComplexType(RHSElementType);
  871. if (!IsCompAssign) {
  872. if (LHSComplexType)
  873. LHS =
  874. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  875. else
  876. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  877. }
  878. } else if (Order > 0) {
  879. // Promote the precision of the RHS.
  880. if (RHSComplexType)
  881. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  882. else
  883. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  884. }
  885. return ResultType;
  886. }
  887. /// Handle arithmetic conversion from integer to float. Helper function
  888. /// of UsualArithmeticConversions()
  889. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  890. ExprResult &IntExpr,
  891. QualType FloatTy, QualType IntTy,
  892. bool ConvertFloat, bool ConvertInt) {
  893. if (IntTy->isIntegerType()) {
  894. if (ConvertInt)
  895. // Convert intExpr to the lhs floating point type.
  896. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  897. CK_IntegralToFloating);
  898. return FloatTy;
  899. }
  900. // Convert both sides to the appropriate complex float.
  901. assert(IntTy->isComplexIntegerType());
  902. QualType result = S.Context.getComplexType(FloatTy);
  903. // _Complex int -> _Complex float
  904. if (ConvertInt)
  905. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  906. CK_IntegralComplexToFloatingComplex);
  907. // float -> _Complex float
  908. if (ConvertFloat)
  909. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  910. CK_FloatingRealToComplex);
  911. return result;
  912. }
  913. /// Handle arithmethic conversion with floating point types. Helper
  914. /// function of UsualArithmeticConversions()
  915. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  916. ExprResult &RHS, QualType LHSType,
  917. QualType RHSType, bool IsCompAssign) {
  918. bool LHSFloat = LHSType->isRealFloatingType();
  919. bool RHSFloat = RHSType->isRealFloatingType();
  920. // If we have two real floating types, convert the smaller operand
  921. // to the bigger result.
  922. if (LHSFloat && RHSFloat) {
  923. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  924. if (order > 0) {
  925. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  926. return LHSType;
  927. }
  928. assert(order < 0 && "illegal float comparison");
  929. if (!IsCompAssign)
  930. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  931. return RHSType;
  932. }
  933. if (LHSFloat) {
  934. // Half FP has to be promoted to float unless it is natively supported
  935. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  936. LHSType = S.Context.FloatTy;
  937. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  938. /*convertFloat=*/!IsCompAssign,
  939. /*convertInt=*/ true);
  940. }
  941. assert(RHSFloat);
  942. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  943. /*convertInt=*/ true,
  944. /*convertFloat=*/!IsCompAssign);
  945. }
  946. /// Diagnose attempts to convert between __float128 and long double if
  947. /// there is no support for such conversion. Helper function of
  948. /// UsualArithmeticConversions().
  949. static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
  950. QualType RHSType) {
  951. /* No issue converting if at least one of the types is not a floating point
  952. type or the two types have the same rank.
  953. */
  954. if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
  955. S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
  956. return false;
  957. assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
  958. "The remaining types must be floating point types.");
  959. auto *LHSComplex = LHSType->getAs<ComplexType>();
  960. auto *RHSComplex = RHSType->getAs<ComplexType>();
  961. QualType LHSElemType = LHSComplex ?
  962. LHSComplex->getElementType() : LHSType;
  963. QualType RHSElemType = RHSComplex ?
  964. RHSComplex->getElementType() : RHSType;
  965. // No issue if the two types have the same representation
  966. if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
  967. &S.Context.getFloatTypeSemantics(RHSElemType))
  968. return false;
  969. bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
  970. RHSElemType == S.Context.LongDoubleTy);
  971. Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
  972. RHSElemType == S.Context.Float128Ty);
  973. // We've handled the situation where __float128 and long double have the same
  974. // representation. We allow all conversions for all possible long double types
  975. // except PPC's double double.
  976. return Float128AndLongDouble &&
  977. (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
  978. &llvm::APFloat::PPCDoubleDouble());
  979. }
  980. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  981. namespace {
  982. /// These helper callbacks are placed in an anonymous namespace to
  983. /// permit their use as function template parameters.
  984. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  985. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  986. }
  987. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  988. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  989. CK_IntegralComplexCast);
  990. }
  991. }
  992. /// Handle integer arithmetic conversions. Helper function of
  993. /// UsualArithmeticConversions()
  994. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  995. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  996. ExprResult &RHS, QualType LHSType,
  997. QualType RHSType, bool IsCompAssign) {
  998. // The rules for this case are in C99 6.3.1.8
  999. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  1000. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  1001. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  1002. if (LHSSigned == RHSSigned) {
  1003. // Same signedness; use the higher-ranked type
  1004. if (order >= 0) {
  1005. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1006. return LHSType;
  1007. } else if (!IsCompAssign)
  1008. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1009. return RHSType;
  1010. } else if (order != (LHSSigned ? 1 : -1)) {
  1011. // The unsigned type has greater than or equal rank to the
  1012. // signed type, so use the unsigned type
  1013. if (RHSSigned) {
  1014. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1015. return LHSType;
  1016. } else if (!IsCompAssign)
  1017. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1018. return RHSType;
  1019. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1020. // The two types are different widths; if we are here, that
  1021. // means the signed type is larger than the unsigned type, so
  1022. // use the signed type.
  1023. if (LHSSigned) {
  1024. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1025. return LHSType;
  1026. } else if (!IsCompAssign)
  1027. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1028. return RHSType;
  1029. } else {
  1030. // The signed type is higher-ranked than the unsigned type,
  1031. // but isn't actually any bigger (like unsigned int and long
  1032. // on most 32-bit systems). Use the unsigned type corresponding
  1033. // to the signed type.
  1034. QualType result =
  1035. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1036. RHS = (*doRHSCast)(S, RHS.get(), result);
  1037. if (!IsCompAssign)
  1038. LHS = (*doLHSCast)(S, LHS.get(), result);
  1039. return result;
  1040. }
  1041. }
  1042. /// Handle conversions with GCC complex int extension. Helper function
  1043. /// of UsualArithmeticConversions()
  1044. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1045. ExprResult &RHS, QualType LHSType,
  1046. QualType RHSType,
  1047. bool IsCompAssign) {
  1048. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1049. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1050. if (LHSComplexInt && RHSComplexInt) {
  1051. QualType LHSEltType = LHSComplexInt->getElementType();
  1052. QualType RHSEltType = RHSComplexInt->getElementType();
  1053. QualType ScalarType =
  1054. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1055. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1056. return S.Context.getComplexType(ScalarType);
  1057. }
  1058. if (LHSComplexInt) {
  1059. QualType LHSEltType = LHSComplexInt->getElementType();
  1060. QualType ScalarType =
  1061. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1062. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1063. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1064. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1065. CK_IntegralRealToComplex);
  1066. return ComplexType;
  1067. }
  1068. assert(RHSComplexInt);
  1069. QualType RHSEltType = RHSComplexInt->getElementType();
  1070. QualType ScalarType =
  1071. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1072. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1073. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1074. if (!IsCompAssign)
  1075. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1076. CK_IntegralRealToComplex);
  1077. return ComplexType;
  1078. }
  1079. /// UsualArithmeticConversions - Performs various conversions that are common to
  1080. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1081. /// routine returns the first non-arithmetic type found. The client is
  1082. /// responsible for emitting appropriate error diagnostics.
  1083. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1084. bool IsCompAssign) {
  1085. if (!IsCompAssign) {
  1086. LHS = UsualUnaryConversions(LHS.get());
  1087. if (LHS.isInvalid())
  1088. return QualType();
  1089. }
  1090. RHS = UsualUnaryConversions(RHS.get());
  1091. if (RHS.isInvalid())
  1092. return QualType();
  1093. // For conversion purposes, we ignore any qualifiers.
  1094. // For example, "const float" and "float" are equivalent.
  1095. QualType LHSType =
  1096. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1097. QualType RHSType =
  1098. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1099. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1100. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1101. LHSType = AtomicLHS->getValueType();
  1102. // If both types are identical, no conversion is needed.
  1103. if (LHSType == RHSType)
  1104. return LHSType;
  1105. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1106. // The caller can deal with this (e.g. pointer + int).
  1107. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1108. return QualType();
  1109. // Apply unary and bitfield promotions to the LHS's type.
  1110. QualType LHSUnpromotedType = LHSType;
  1111. if (LHSType->isPromotableIntegerType())
  1112. LHSType = Context.getPromotedIntegerType(LHSType);
  1113. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1114. if (!LHSBitfieldPromoteTy.isNull())
  1115. LHSType = LHSBitfieldPromoteTy;
  1116. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  1117. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1118. // If both types are identical, no conversion is needed.
  1119. if (LHSType == RHSType)
  1120. return LHSType;
  1121. // At this point, we have two different arithmetic types.
  1122. // Diagnose attempts to convert between __float128 and long double where
  1123. // such conversions currently can't be handled.
  1124. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  1125. return QualType();
  1126. // Handle complex types first (C99 6.3.1.8p1).
  1127. if (LHSType->isComplexType() || RHSType->isComplexType())
  1128. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1129. IsCompAssign);
  1130. // Now handle "real" floating types (i.e. float, double, long double).
  1131. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1132. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1133. IsCompAssign);
  1134. // Handle GCC complex int extension.
  1135. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1136. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1137. IsCompAssign);
  1138. // Finally, we have two differing integer types.
  1139. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1140. (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
  1141. }
  1142. //===----------------------------------------------------------------------===//
  1143. // Semantic Analysis for various Expression Types
  1144. //===----------------------------------------------------------------------===//
  1145. ExprResult
  1146. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1147. SourceLocation DefaultLoc,
  1148. SourceLocation RParenLoc,
  1149. Expr *ControllingExpr,
  1150. ArrayRef<ParsedType> ArgTypes,
  1151. ArrayRef<Expr *> ArgExprs) {
  1152. unsigned NumAssocs = ArgTypes.size();
  1153. assert(NumAssocs == ArgExprs.size());
  1154. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1155. for (unsigned i = 0; i < NumAssocs; ++i) {
  1156. if (ArgTypes[i])
  1157. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1158. else
  1159. Types[i] = nullptr;
  1160. }
  1161. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1162. ControllingExpr,
  1163. llvm::makeArrayRef(Types, NumAssocs),
  1164. ArgExprs);
  1165. delete [] Types;
  1166. return ER;
  1167. }
  1168. ExprResult
  1169. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1170. SourceLocation DefaultLoc,
  1171. SourceLocation RParenLoc,
  1172. Expr *ControllingExpr,
  1173. ArrayRef<TypeSourceInfo *> Types,
  1174. ArrayRef<Expr *> Exprs) {
  1175. unsigned NumAssocs = Types.size();
  1176. assert(NumAssocs == Exprs.size());
  1177. // Decay and strip qualifiers for the controlling expression type, and handle
  1178. // placeholder type replacement. See committee discussion from WG14 DR423.
  1179. {
  1180. EnterExpressionEvaluationContext Unevaluated(
  1181. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  1182. ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
  1183. if (R.isInvalid())
  1184. return ExprError();
  1185. ControllingExpr = R.get();
  1186. }
  1187. // The controlling expression is an unevaluated operand, so side effects are
  1188. // likely unintended.
  1189. if (!inTemplateInstantiation() &&
  1190. ControllingExpr->HasSideEffects(Context, false))
  1191. Diag(ControllingExpr->getExprLoc(),
  1192. diag::warn_side_effects_unevaluated_context);
  1193. bool TypeErrorFound = false,
  1194. IsResultDependent = ControllingExpr->isTypeDependent(),
  1195. ContainsUnexpandedParameterPack
  1196. = ControllingExpr->containsUnexpandedParameterPack();
  1197. for (unsigned i = 0; i < NumAssocs; ++i) {
  1198. if (Exprs[i]->containsUnexpandedParameterPack())
  1199. ContainsUnexpandedParameterPack = true;
  1200. if (Types[i]) {
  1201. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1202. ContainsUnexpandedParameterPack = true;
  1203. if (Types[i]->getType()->isDependentType()) {
  1204. IsResultDependent = true;
  1205. } else {
  1206. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1207. // complete object type other than a variably modified type."
  1208. unsigned D = 0;
  1209. if (Types[i]->getType()->isIncompleteType())
  1210. D = diag::err_assoc_type_incomplete;
  1211. else if (!Types[i]->getType()->isObjectType())
  1212. D = diag::err_assoc_type_nonobject;
  1213. else if (Types[i]->getType()->isVariablyModifiedType())
  1214. D = diag::err_assoc_type_variably_modified;
  1215. if (D != 0) {
  1216. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1217. << Types[i]->getTypeLoc().getSourceRange()
  1218. << Types[i]->getType();
  1219. TypeErrorFound = true;
  1220. }
  1221. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1222. // selection shall specify compatible types."
  1223. for (unsigned j = i+1; j < NumAssocs; ++j)
  1224. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1225. Context.typesAreCompatible(Types[i]->getType(),
  1226. Types[j]->getType())) {
  1227. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1228. diag::err_assoc_compatible_types)
  1229. << Types[j]->getTypeLoc().getSourceRange()
  1230. << Types[j]->getType()
  1231. << Types[i]->getType();
  1232. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1233. diag::note_compat_assoc)
  1234. << Types[i]->getTypeLoc().getSourceRange()
  1235. << Types[i]->getType();
  1236. TypeErrorFound = true;
  1237. }
  1238. }
  1239. }
  1240. }
  1241. if (TypeErrorFound)
  1242. return ExprError();
  1243. // If we determined that the generic selection is result-dependent, don't
  1244. // try to compute the result expression.
  1245. if (IsResultDependent)
  1246. return new (Context) GenericSelectionExpr(
  1247. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1248. ContainsUnexpandedParameterPack);
  1249. SmallVector<unsigned, 1> CompatIndices;
  1250. unsigned DefaultIndex = -1U;
  1251. for (unsigned i = 0; i < NumAssocs; ++i) {
  1252. if (!Types[i])
  1253. DefaultIndex = i;
  1254. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1255. Types[i]->getType()))
  1256. CompatIndices.push_back(i);
  1257. }
  1258. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1259. // type compatible with at most one of the types named in its generic
  1260. // association list."
  1261. if (CompatIndices.size() > 1) {
  1262. // We strip parens here because the controlling expression is typically
  1263. // parenthesized in macro definitions.
  1264. ControllingExpr = ControllingExpr->IgnoreParens();
  1265. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
  1266. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1267. << (unsigned) CompatIndices.size();
  1268. for (unsigned I : CompatIndices) {
  1269. Diag(Types[I]->getTypeLoc().getBeginLoc(),
  1270. diag::note_compat_assoc)
  1271. << Types[I]->getTypeLoc().getSourceRange()
  1272. << Types[I]->getType();
  1273. }
  1274. return ExprError();
  1275. }
  1276. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1277. // its controlling expression shall have type compatible with exactly one of
  1278. // the types named in its generic association list."
  1279. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1280. // We strip parens here because the controlling expression is typically
  1281. // parenthesized in macro definitions.
  1282. ControllingExpr = ControllingExpr->IgnoreParens();
  1283. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
  1284. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1285. return ExprError();
  1286. }
  1287. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1288. // type name that is compatible with the type of the controlling expression,
  1289. // then the result expression of the generic selection is the expression
  1290. // in that generic association. Otherwise, the result expression of the
  1291. // generic selection is the expression in the default generic association."
  1292. unsigned ResultIndex =
  1293. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1294. return new (Context) GenericSelectionExpr(
  1295. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1296. ContainsUnexpandedParameterPack, ResultIndex);
  1297. }
  1298. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1299. /// location of the token and the offset of the ud-suffix within it.
  1300. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1301. unsigned Offset) {
  1302. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1303. S.getLangOpts());
  1304. }
  1305. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1306. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1307. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1308. IdentifierInfo *UDSuffix,
  1309. SourceLocation UDSuffixLoc,
  1310. ArrayRef<Expr*> Args,
  1311. SourceLocation LitEndLoc) {
  1312. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1313. QualType ArgTy[2];
  1314. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1315. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1316. if (ArgTy[ArgIdx]->isArrayType())
  1317. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1318. }
  1319. DeclarationName OpName =
  1320. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1321. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1322. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1323. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1324. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1325. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1326. /*AllowStringTemplate*/ false,
  1327. /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
  1328. return ExprError();
  1329. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1330. }
  1331. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1332. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1333. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1334. /// multiple tokens. However, the common case is that StringToks points to one
  1335. /// string.
  1336. ///
  1337. ExprResult
  1338. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1339. assert(!StringToks.empty() && "Must have at least one string!");
  1340. StringLiteralParser Literal(StringToks, PP);
  1341. if (Literal.hadError)
  1342. return ExprError();
  1343. SmallVector<SourceLocation, 4> StringTokLocs;
  1344. for (const Token &Tok : StringToks)
  1345. StringTokLocs.push_back(Tok.getLocation());
  1346. QualType CharTy = Context.CharTy;
  1347. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1348. if (Literal.isWide()) {
  1349. CharTy = Context.getWideCharType();
  1350. Kind = StringLiteral::Wide;
  1351. } else if (Literal.isUTF8()) {
  1352. if (getLangOpts().Char8)
  1353. CharTy = Context.Char8Ty;
  1354. Kind = StringLiteral::UTF8;
  1355. } else if (Literal.isUTF16()) {
  1356. CharTy = Context.Char16Ty;
  1357. Kind = StringLiteral::UTF16;
  1358. } else if (Literal.isUTF32()) {
  1359. CharTy = Context.Char32Ty;
  1360. Kind = StringLiteral::UTF32;
  1361. } else if (Literal.isPascal()) {
  1362. CharTy = Context.UnsignedCharTy;
  1363. }
  1364. QualType CharTyConst = CharTy;
  1365. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  1366. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  1367. CharTyConst.addConst();
  1368. CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
  1369. // Get an array type for the string, according to C99 6.4.5. This includes
  1370. // the nul terminator character as well as the string length for pascal
  1371. // strings.
  1372. QualType StrTy = Context.getConstantArrayType(
  1373. CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
  1374. ArrayType::Normal, 0);
  1375. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1376. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1377. Kind, Literal.Pascal, StrTy,
  1378. &StringTokLocs[0],
  1379. StringTokLocs.size());
  1380. if (Literal.getUDSuffix().empty())
  1381. return Lit;
  1382. // We're building a user-defined literal.
  1383. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1384. SourceLocation UDSuffixLoc =
  1385. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1386. Literal.getUDSuffixOffset());
  1387. // Make sure we're allowed user-defined literals here.
  1388. if (!UDLScope)
  1389. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1390. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1391. // operator "" X (str, len)
  1392. QualType SizeType = Context.getSizeType();
  1393. DeclarationName OpName =
  1394. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1395. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1396. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1397. QualType ArgTy[] = {
  1398. Context.getArrayDecayedType(StrTy), SizeType
  1399. };
  1400. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1401. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1402. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1403. /*AllowStringTemplate*/ true,
  1404. /*DiagnoseMissing*/ true)) {
  1405. case LOLR_Cooked: {
  1406. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1407. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1408. StringTokLocs[0]);
  1409. Expr *Args[] = { Lit, LenArg };
  1410. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1411. }
  1412. case LOLR_StringTemplate: {
  1413. TemplateArgumentListInfo ExplicitArgs;
  1414. unsigned CharBits = Context.getIntWidth(CharTy);
  1415. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1416. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1417. TemplateArgument TypeArg(CharTy);
  1418. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1419. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1420. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1421. Value = Lit->getCodeUnit(I);
  1422. TemplateArgument Arg(Context, Value, CharTy);
  1423. TemplateArgumentLocInfo ArgInfo;
  1424. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1425. }
  1426. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1427. &ExplicitArgs);
  1428. }
  1429. case LOLR_Raw:
  1430. case LOLR_Template:
  1431. case LOLR_ErrorNoDiagnostic:
  1432. llvm_unreachable("unexpected literal operator lookup result");
  1433. case LOLR_Error:
  1434. return ExprError();
  1435. }
  1436. llvm_unreachable("unexpected literal operator lookup result");
  1437. }
  1438. ExprResult
  1439. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1440. SourceLocation Loc,
  1441. const CXXScopeSpec *SS) {
  1442. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1443. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1444. }
  1445. /// BuildDeclRefExpr - Build an expression that references a
  1446. /// declaration that does not require a closure capture.
  1447. ExprResult
  1448. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1449. const DeclarationNameInfo &NameInfo,
  1450. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1451. const TemplateArgumentListInfo *TemplateArgs) {
  1452. bool RefersToCapturedVariable =
  1453. isa<VarDecl>(D) &&
  1454. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1455. DeclRefExpr *E;
  1456. if (isa<VarTemplateSpecializationDecl>(D)) {
  1457. VarTemplateSpecializationDecl *VarSpec =
  1458. cast<VarTemplateSpecializationDecl>(D);
  1459. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1460. : NestedNameSpecifierLoc(),
  1461. VarSpec->getTemplateKeywordLoc(), D,
  1462. RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
  1463. FoundD, TemplateArgs);
  1464. } else {
  1465. assert(!TemplateArgs && "No template arguments for non-variable"
  1466. " template specialization references");
  1467. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1468. : NestedNameSpecifierLoc(),
  1469. SourceLocation(), D, RefersToCapturedVariable,
  1470. NameInfo, Ty, VK, FoundD);
  1471. }
  1472. MarkDeclRefReferenced(E);
  1473. if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
  1474. Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
  1475. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
  1476. getCurFunction()->recordUseOfWeak(E);
  1477. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1478. if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
  1479. FD = IFD->getAnonField();
  1480. if (FD) {
  1481. UnusedPrivateFields.remove(FD);
  1482. // Just in case we're building an illegal pointer-to-member.
  1483. if (FD->isBitField())
  1484. E->setObjectKind(OK_BitField);
  1485. }
  1486. // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
  1487. // designates a bit-field.
  1488. if (auto *BD = dyn_cast<BindingDecl>(D))
  1489. if (auto *BE = BD->getBinding())
  1490. E->setObjectKind(BE->getObjectKind());
  1491. return E;
  1492. }
  1493. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1494. /// possibly a list of template arguments.
  1495. ///
  1496. /// If this produces template arguments, it is permitted to call
  1497. /// DecomposeTemplateName.
  1498. ///
  1499. /// This actually loses a lot of source location information for
  1500. /// non-standard name kinds; we should consider preserving that in
  1501. /// some way.
  1502. void
  1503. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1504. TemplateArgumentListInfo &Buffer,
  1505. DeclarationNameInfo &NameInfo,
  1506. const TemplateArgumentListInfo *&TemplateArgs) {
  1507. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
  1508. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1509. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1510. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1511. Id.TemplateId->NumArgs);
  1512. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1513. TemplateName TName = Id.TemplateId->Template.get();
  1514. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1515. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1516. TemplateArgs = &Buffer;
  1517. } else {
  1518. NameInfo = GetNameFromUnqualifiedId(Id);
  1519. TemplateArgs = nullptr;
  1520. }
  1521. }
  1522. static void emitEmptyLookupTypoDiagnostic(
  1523. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1524. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1525. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1526. DeclContext *Ctx =
  1527. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1528. if (!TC) {
  1529. // Emit a special diagnostic for failed member lookups.
  1530. // FIXME: computing the declaration context might fail here (?)
  1531. if (Ctx)
  1532. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1533. << SS.getRange();
  1534. else
  1535. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1536. return;
  1537. }
  1538. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1539. bool DroppedSpecifier =
  1540. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1541. unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
  1542. ? diag::note_implicit_param_decl
  1543. : diag::note_previous_decl;
  1544. if (!Ctx)
  1545. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1546. SemaRef.PDiag(NoteID));
  1547. else
  1548. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1549. << Typo << Ctx << DroppedSpecifier
  1550. << SS.getRange(),
  1551. SemaRef.PDiag(NoteID));
  1552. }
  1553. /// Diagnose an empty lookup.
  1554. ///
  1555. /// \return false if new lookup candidates were found
  1556. bool
  1557. Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1558. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1559. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1560. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1561. DeclarationName Name = R.getLookupName();
  1562. unsigned diagnostic = diag::err_undeclared_var_use;
  1563. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1564. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1565. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1566. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1567. diagnostic = diag::err_undeclared_use;
  1568. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1569. }
  1570. // If the original lookup was an unqualified lookup, fake an
  1571. // unqualified lookup. This is useful when (for example) the
  1572. // original lookup would not have found something because it was a
  1573. // dependent name.
  1574. DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
  1575. while (DC) {
  1576. if (isa<CXXRecordDecl>(DC)) {
  1577. LookupQualifiedName(R, DC);
  1578. if (!R.empty()) {
  1579. // Don't give errors about ambiguities in this lookup.
  1580. R.suppressDiagnostics();
  1581. // During a default argument instantiation the CurContext points
  1582. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1583. // function parameter list, hence add an explicit check.
  1584. bool isDefaultArgument =
  1585. !CodeSynthesisContexts.empty() &&
  1586. CodeSynthesisContexts.back().Kind ==
  1587. CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
  1588. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1589. bool isInstance = CurMethod &&
  1590. CurMethod->isInstance() &&
  1591. DC == CurMethod->getParent() && !isDefaultArgument;
  1592. // Give a code modification hint to insert 'this->'.
  1593. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1594. // Actually quite difficult!
  1595. if (getLangOpts().MSVCCompat)
  1596. diagnostic = diag::ext_found_via_dependent_bases_lookup;
  1597. if (isInstance) {
  1598. Diag(R.getNameLoc(), diagnostic) << Name
  1599. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1600. CheckCXXThisCapture(R.getNameLoc());
  1601. } else {
  1602. Diag(R.getNameLoc(), diagnostic) << Name;
  1603. }
  1604. // Do we really want to note all of these?
  1605. for (NamedDecl *D : R)
  1606. Diag(D->getLocation(), diag::note_dependent_var_use);
  1607. // Return true if we are inside a default argument instantiation
  1608. // and the found name refers to an instance member function, otherwise
  1609. // the function calling DiagnoseEmptyLookup will try to create an
  1610. // implicit member call and this is wrong for default argument.
  1611. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1612. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1613. return true;
  1614. }
  1615. // Tell the callee to try to recover.
  1616. return false;
  1617. }
  1618. R.clear();
  1619. }
  1620. // In Microsoft mode, if we are performing lookup from within a friend
  1621. // function definition declared at class scope then we must set
  1622. // DC to the lexical parent to be able to search into the parent
  1623. // class.
  1624. if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
  1625. cast<FunctionDecl>(DC)->getFriendObjectKind() &&
  1626. DC->getLexicalParent()->isRecord())
  1627. DC = DC->getLexicalParent();
  1628. else
  1629. DC = DC->getParent();
  1630. }
  1631. // We didn't find anything, so try to correct for a typo.
  1632. TypoCorrection Corrected;
  1633. if (S && Out) {
  1634. SourceLocation TypoLoc = R.getNameLoc();
  1635. assert(!ExplicitTemplateArgs &&
  1636. "Diagnosing an empty lookup with explicit template args!");
  1637. *Out = CorrectTypoDelayed(
  1638. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
  1639. [=](const TypoCorrection &TC) {
  1640. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1641. diagnostic, diagnostic_suggest);
  1642. },
  1643. nullptr, CTK_ErrorRecovery);
  1644. if (*Out)
  1645. return true;
  1646. } else if (S && (Corrected =
  1647. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
  1648. &SS, std::move(CCC), CTK_ErrorRecovery))) {
  1649. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1650. bool DroppedSpecifier =
  1651. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1652. R.setLookupName(Corrected.getCorrection());
  1653. bool AcceptableWithRecovery = false;
  1654. bool AcceptableWithoutRecovery = false;
  1655. NamedDecl *ND = Corrected.getFoundDecl();
  1656. if (ND) {
  1657. if (Corrected.isOverloaded()) {
  1658. OverloadCandidateSet OCS(R.getNameLoc(),
  1659. OverloadCandidateSet::CSK_Normal);
  1660. OverloadCandidateSet::iterator Best;
  1661. for (NamedDecl *CD : Corrected) {
  1662. if (FunctionTemplateDecl *FTD =
  1663. dyn_cast<FunctionTemplateDecl>(CD))
  1664. AddTemplateOverloadCandidate(
  1665. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1666. Args, OCS);
  1667. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  1668. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1669. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1670. Args, OCS);
  1671. }
  1672. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1673. case OR_Success:
  1674. ND = Best->FoundDecl;
  1675. Corrected.setCorrectionDecl(ND);
  1676. break;
  1677. default:
  1678. // FIXME: Arbitrarily pick the first declaration for the note.
  1679. Corrected.setCorrectionDecl(ND);
  1680. break;
  1681. }
  1682. }
  1683. R.addDecl(ND);
  1684. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1685. CXXRecordDecl *Record = nullptr;
  1686. if (Corrected.getCorrectionSpecifier()) {
  1687. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1688. Record = Ty->getAsCXXRecordDecl();
  1689. }
  1690. if (!Record)
  1691. Record = cast<CXXRecordDecl>(
  1692. ND->getDeclContext()->getRedeclContext());
  1693. R.setNamingClass(Record);
  1694. }
  1695. auto *UnderlyingND = ND->getUnderlyingDecl();
  1696. AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
  1697. isa<FunctionTemplateDecl>(UnderlyingND);
  1698. // FIXME: If we ended up with a typo for a type name or
  1699. // Objective-C class name, we're in trouble because the parser
  1700. // is in the wrong place to recover. Suggest the typo
  1701. // correction, but don't make it a fix-it since we're not going
  1702. // to recover well anyway.
  1703. AcceptableWithoutRecovery =
  1704. isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
  1705. } else {
  1706. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1707. // because we aren't able to recover.
  1708. AcceptableWithoutRecovery = true;
  1709. }
  1710. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1711. unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
  1712. ? diag::note_implicit_param_decl
  1713. : diag::note_previous_decl;
  1714. if (SS.isEmpty())
  1715. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1716. PDiag(NoteID), AcceptableWithRecovery);
  1717. else
  1718. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1719. << Name << computeDeclContext(SS, false)
  1720. << DroppedSpecifier << SS.getRange(),
  1721. PDiag(NoteID), AcceptableWithRecovery);
  1722. // Tell the callee whether to try to recover.
  1723. return !AcceptableWithRecovery;
  1724. }
  1725. }
  1726. R.clear();
  1727. // Emit a special diagnostic for failed member lookups.
  1728. // FIXME: computing the declaration context might fail here (?)
  1729. if (!SS.isEmpty()) {
  1730. Diag(R.getNameLoc(), diag::err_no_member)
  1731. << Name << computeDeclContext(SS, false)
  1732. << SS.getRange();
  1733. return true;
  1734. }
  1735. // Give up, we can't recover.
  1736. Diag(R.getNameLoc(), diagnostic) << Name;
  1737. return true;
  1738. }
  1739. /// In Microsoft mode, if we are inside a template class whose parent class has
  1740. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1741. /// assume the identifier is a member of a dependent base class. We can only
  1742. /// recover successfully in static methods, instance methods, and other contexts
  1743. /// where 'this' is available. This doesn't precisely match MSVC's
  1744. /// instantiation model, but it's close enough.
  1745. static Expr *
  1746. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1747. DeclarationNameInfo &NameInfo,
  1748. SourceLocation TemplateKWLoc,
  1749. const TemplateArgumentListInfo *TemplateArgs) {
  1750. // Only try to recover from lookup into dependent bases in static methods or
  1751. // contexts where 'this' is available.
  1752. QualType ThisType = S.getCurrentThisType();
  1753. const CXXRecordDecl *RD = nullptr;
  1754. if (!ThisType.isNull())
  1755. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1756. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1757. RD = MD->getParent();
  1758. if (!RD || !RD->hasAnyDependentBases())
  1759. return nullptr;
  1760. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1761. // is available, suggest inserting 'this->' as a fixit.
  1762. SourceLocation Loc = NameInfo.getLoc();
  1763. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1764. DB << NameInfo.getName() << RD;
  1765. if (!ThisType.isNull()) {
  1766. DB << FixItHint::CreateInsertion(Loc, "this->");
  1767. return CXXDependentScopeMemberExpr::Create(
  1768. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1769. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1770. /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
  1771. }
  1772. // Synthesize a fake NNS that points to the derived class. This will
  1773. // perform name lookup during template instantiation.
  1774. CXXScopeSpec SS;
  1775. auto *NNS =
  1776. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1777. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1778. return DependentScopeDeclRefExpr::Create(
  1779. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1780. TemplateArgs);
  1781. }
  1782. ExprResult
  1783. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1784. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1785. bool HasTrailingLParen, bool IsAddressOfOperand,
  1786. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1787. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1788. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1789. "cannot be direct & operand and have a trailing lparen");
  1790. if (SS.isInvalid())
  1791. return ExprError();
  1792. TemplateArgumentListInfo TemplateArgsBuffer;
  1793. // Decompose the UnqualifiedId into the following data.
  1794. DeclarationNameInfo NameInfo;
  1795. const TemplateArgumentListInfo *TemplateArgs;
  1796. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1797. DeclarationName Name = NameInfo.getName();
  1798. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1799. SourceLocation NameLoc = NameInfo.getLoc();
  1800. if (II && II->isEditorPlaceholder()) {
  1801. // FIXME: When typed placeholders are supported we can create a typed
  1802. // placeholder expression node.
  1803. return ExprError();
  1804. }
  1805. // C++ [temp.dep.expr]p3:
  1806. // An id-expression is type-dependent if it contains:
  1807. // -- an identifier that was declared with a dependent type,
  1808. // (note: handled after lookup)
  1809. // -- a template-id that is dependent,
  1810. // (note: handled in BuildTemplateIdExpr)
  1811. // -- a conversion-function-id that specifies a dependent type,
  1812. // -- a nested-name-specifier that contains a class-name that
  1813. // names a dependent type.
  1814. // Determine whether this is a member of an unknown specialization;
  1815. // we need to handle these differently.
  1816. bool DependentID = false;
  1817. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1818. Name.getCXXNameType()->isDependentType()) {
  1819. DependentID = true;
  1820. } else if (SS.isSet()) {
  1821. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1822. if (RequireCompleteDeclContext(SS, DC))
  1823. return ExprError();
  1824. } else {
  1825. DependentID = true;
  1826. }
  1827. }
  1828. if (DependentID)
  1829. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1830. IsAddressOfOperand, TemplateArgs);
  1831. // Perform the required lookup.
  1832. LookupResult R(*this, NameInfo,
  1833. (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
  1834. ? LookupObjCImplicitSelfParam
  1835. : LookupOrdinaryName);
  1836. if (TemplateKWLoc.isValid() || TemplateArgs) {
  1837. // Lookup the template name again to correctly establish the context in
  1838. // which it was found. This is really unfortunate as we already did the
  1839. // lookup to determine that it was a template name in the first place. If
  1840. // this becomes a performance hit, we can work harder to preserve those
  1841. // results until we get here but it's likely not worth it.
  1842. bool MemberOfUnknownSpecialization;
  1843. if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1844. MemberOfUnknownSpecialization, TemplateKWLoc))
  1845. return ExprError();
  1846. if (MemberOfUnknownSpecialization ||
  1847. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1848. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1849. IsAddressOfOperand, TemplateArgs);
  1850. } else {
  1851. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1852. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1853. // If the result might be in a dependent base class, this is a dependent
  1854. // id-expression.
  1855. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1856. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1857. IsAddressOfOperand, TemplateArgs);
  1858. // If this reference is in an Objective-C method, then we need to do
  1859. // some special Objective-C lookup, too.
  1860. if (IvarLookupFollowUp) {
  1861. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1862. if (E.isInvalid())
  1863. return ExprError();
  1864. if (Expr *Ex = E.getAs<Expr>())
  1865. return Ex;
  1866. }
  1867. }
  1868. if (R.isAmbiguous())
  1869. return ExprError();
  1870. // This could be an implicitly declared function reference (legal in C90,
  1871. // extension in C99, forbidden in C++).
  1872. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  1873. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  1874. if (D) R.addDecl(D);
  1875. }
  1876. // Determine whether this name might be a candidate for
  1877. // argument-dependent lookup.
  1878. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  1879. if (R.empty() && !ADL) {
  1880. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  1881. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  1882. TemplateKWLoc, TemplateArgs))
  1883. return E;
  1884. }
  1885. // Don't diagnose an empty lookup for inline assembly.
  1886. if (IsInlineAsmIdentifier)
  1887. return ExprError();
  1888. // If this name wasn't predeclared and if this is not a function
  1889. // call, diagnose the problem.
  1890. TypoExpr *TE = nullptr;
  1891. auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
  1892. II, SS.isValid() ? SS.getScopeRep() : nullptr);
  1893. DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
  1894. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  1895. "Typo correction callback misconfigured");
  1896. if (CCC) {
  1897. // Make sure the callback knows what the typo being diagnosed is.
  1898. CCC->setTypoName(II);
  1899. if (SS.isValid())
  1900. CCC->setTypoNNS(SS.getScopeRep());
  1901. }
  1902. // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
  1903. // a template name, but we happen to have always already looked up the name
  1904. // before we get here if it must be a template name.
  1905. if (DiagnoseEmptyLookup(S, SS, R,
  1906. CCC ? std::move(CCC) : std::move(DefaultValidator),
  1907. nullptr, None, &TE)) {
  1908. if (TE && KeywordReplacement) {
  1909. auto &State = getTypoExprState(TE);
  1910. auto BestTC = State.Consumer->getNextCorrection();
  1911. if (BestTC.isKeyword()) {
  1912. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  1913. if (State.DiagHandler)
  1914. State.DiagHandler(BestTC);
  1915. KeywordReplacement->startToken();
  1916. KeywordReplacement->setKind(II->getTokenID());
  1917. KeywordReplacement->setIdentifierInfo(II);
  1918. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  1919. // Clean up the state associated with the TypoExpr, since it has
  1920. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  1921. clearDelayedTypo(TE);
  1922. // Signal that a correction to a keyword was performed by returning a
  1923. // valid-but-null ExprResult.
  1924. return (Expr*)nullptr;
  1925. }
  1926. State.Consumer->resetCorrectionStream();
  1927. }
  1928. return TE ? TE : ExprError();
  1929. }
  1930. assert(!R.empty() &&
  1931. "DiagnoseEmptyLookup returned false but added no results");
  1932. // If we found an Objective-C instance variable, let
  1933. // LookupInObjCMethod build the appropriate expression to
  1934. // reference the ivar.
  1935. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  1936. R.clear();
  1937. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  1938. // In a hopelessly buggy code, Objective-C instance variable
  1939. // lookup fails and no expression will be built to reference it.
  1940. if (!E.isInvalid() && !E.get())
  1941. return ExprError();
  1942. return E;
  1943. }
  1944. }
  1945. // This is guaranteed from this point on.
  1946. assert(!R.empty() || ADL);
  1947. // Check whether this might be a C++ implicit instance member access.
  1948. // C++ [class.mfct.non-static]p3:
  1949. // When an id-expression that is not part of a class member access
  1950. // syntax and not used to form a pointer to member is used in the
  1951. // body of a non-static member function of class X, if name lookup
  1952. // resolves the name in the id-expression to a non-static non-type
  1953. // member of some class C, the id-expression is transformed into a
  1954. // class member access expression using (*this) as the
  1955. // postfix-expression to the left of the . operator.
  1956. //
  1957. // But we don't actually need to do this for '&' operands if R
  1958. // resolved to a function or overloaded function set, because the
  1959. // expression is ill-formed if it actually works out to be a
  1960. // non-static member function:
  1961. //
  1962. // C++ [expr.ref]p4:
  1963. // Otherwise, if E1.E2 refers to a non-static member function. . .
  1964. // [t]he expression can be used only as the left-hand operand of a
  1965. // member function call.
  1966. //
  1967. // There are other safeguards against such uses, but it's important
  1968. // to get this right here so that we don't end up making a
  1969. // spuriously dependent expression if we're inside a dependent
  1970. // instance method.
  1971. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  1972. bool MightBeImplicitMember;
  1973. if (!IsAddressOfOperand)
  1974. MightBeImplicitMember = true;
  1975. else if (!SS.isEmpty())
  1976. MightBeImplicitMember = false;
  1977. else if (R.isOverloadedResult())
  1978. MightBeImplicitMember = false;
  1979. else if (R.isUnresolvableResult())
  1980. MightBeImplicitMember = true;
  1981. else
  1982. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  1983. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  1984. isa<MSPropertyDecl>(R.getFoundDecl());
  1985. if (MightBeImplicitMember)
  1986. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  1987. R, TemplateArgs, S);
  1988. }
  1989. if (TemplateArgs || TemplateKWLoc.isValid()) {
  1990. // In C++1y, if this is a variable template id, then check it
  1991. // in BuildTemplateIdExpr().
  1992. // The single lookup result must be a variable template declaration.
  1993. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
  1994. Id.TemplateId->Kind == TNK_Var_template) {
  1995. assert(R.getAsSingle<VarTemplateDecl>() &&
  1996. "There should only be one declaration found.");
  1997. }
  1998. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  1999. }
  2000. return BuildDeclarationNameExpr(SS, R, ADL);
  2001. }
  2002. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2003. /// declaration name, generally during template instantiation.
  2004. /// There's a large number of things which don't need to be done along
  2005. /// this path.
  2006. ExprResult Sema::BuildQualifiedDeclarationNameExpr(
  2007. CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
  2008. bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
  2009. DeclContext *DC = computeDeclContext(SS, false);
  2010. if (!DC)
  2011. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2012. NameInfo, /*TemplateArgs=*/nullptr);
  2013. if (RequireCompleteDeclContext(SS, DC))
  2014. return ExprError();
  2015. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2016. LookupQualifiedName(R, DC);
  2017. if (R.isAmbiguous())
  2018. return ExprError();
  2019. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2020. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2021. NameInfo, /*TemplateArgs=*/nullptr);
  2022. if (R.empty()) {
  2023. Diag(NameInfo.getLoc(), diag::err_no_member)
  2024. << NameInfo.getName() << DC << SS.getRange();
  2025. return ExprError();
  2026. }
  2027. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2028. // Diagnose a missing typename if this resolved unambiguously to a type in
  2029. // a dependent context. If we can recover with a type, downgrade this to
  2030. // a warning in Microsoft compatibility mode.
  2031. unsigned DiagID = diag::err_typename_missing;
  2032. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2033. DiagID = diag::ext_typename_missing;
  2034. SourceLocation Loc = SS.getBeginLoc();
  2035. auto D = Diag(Loc, DiagID);
  2036. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2037. << SourceRange(Loc, NameInfo.getEndLoc());
  2038. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2039. // context.
  2040. if (!RecoveryTSI)
  2041. return ExprError();
  2042. // Only issue the fixit if we're prepared to recover.
  2043. D << FixItHint::CreateInsertion(Loc, "typename ");
  2044. // Recover by pretending this was an elaborated type.
  2045. QualType Ty = Context.getTypeDeclType(TD);
  2046. TypeLocBuilder TLB;
  2047. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2048. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2049. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2050. QTL.setElaboratedKeywordLoc(SourceLocation());
  2051. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2052. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2053. return ExprEmpty();
  2054. }
  2055. // Defend against this resolving to an implicit member access. We usually
  2056. // won't get here if this might be a legitimate a class member (we end up in
  2057. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2058. // a pointer-to-member or in an unevaluated context in C++11.
  2059. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2060. return BuildPossibleImplicitMemberExpr(SS,
  2061. /*TemplateKWLoc=*/SourceLocation(),
  2062. R, /*TemplateArgs=*/nullptr, S);
  2063. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2064. }
  2065. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  2066. /// detected that we're currently inside an ObjC method. Perform some
  2067. /// additional lookup.
  2068. ///
  2069. /// Ideally, most of this would be done by lookup, but there's
  2070. /// actually quite a lot of extra work involved.
  2071. ///
  2072. /// Returns a null sentinel to indicate trivial success.
  2073. ExprResult
  2074. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2075. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2076. SourceLocation Loc = Lookup.getNameLoc();
  2077. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2078. // Check for error condition which is already reported.
  2079. if (!CurMethod)
  2080. return ExprError();
  2081. // There are two cases to handle here. 1) scoped lookup could have failed,
  2082. // in which case we should look for an ivar. 2) scoped lookup could have
  2083. // found a decl, but that decl is outside the current instance method (i.e.
  2084. // a global variable). In these two cases, we do a lookup for an ivar with
  2085. // this name, if the lookup sucedes, we replace it our current decl.
  2086. // If we're in a class method, we don't normally want to look for
  2087. // ivars. But if we don't find anything else, and there's an
  2088. // ivar, that's an error.
  2089. bool IsClassMethod = CurMethod->isClassMethod();
  2090. bool LookForIvars;
  2091. if (Lookup.empty())
  2092. LookForIvars = true;
  2093. else if (IsClassMethod)
  2094. LookForIvars = false;
  2095. else
  2096. LookForIvars = (Lookup.isSingleResult() &&
  2097. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2098. ObjCInterfaceDecl *IFace = nullptr;
  2099. if (LookForIvars) {
  2100. IFace = CurMethod->getClassInterface();
  2101. ObjCInterfaceDecl *ClassDeclared;
  2102. ObjCIvarDecl *IV = nullptr;
  2103. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2104. // Diagnose using an ivar in a class method.
  2105. if (IsClassMethod)
  2106. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2107. << IV->getDeclName());
  2108. // If we're referencing an invalid decl, just return this as a silent
  2109. // error node. The error diagnostic was already emitted on the decl.
  2110. if (IV->isInvalidDecl())
  2111. return ExprError();
  2112. // Check if referencing a field with __attribute__((deprecated)).
  2113. if (DiagnoseUseOfDecl(IV, Loc))
  2114. return ExprError();
  2115. // Diagnose the use of an ivar outside of the declaring class.
  2116. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2117. !declaresSameEntity(ClassDeclared, IFace) &&
  2118. !getLangOpts().DebuggerSupport)
  2119. Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
  2120. // FIXME: This should use a new expr for a direct reference, don't
  2121. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2122. IdentifierInfo &II = Context.Idents.get("self");
  2123. UnqualifiedId SelfName;
  2124. SelfName.setIdentifier(&II, SourceLocation());
  2125. SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
  2126. CXXScopeSpec SelfScopeSpec;
  2127. SourceLocation TemplateKWLoc;
  2128. ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
  2129. SelfName, false, false);
  2130. if (SelfExpr.isInvalid())
  2131. return ExprError();
  2132. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2133. if (SelfExpr.isInvalid())
  2134. return ExprError();
  2135. MarkAnyDeclReferenced(Loc, IV, true);
  2136. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2137. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2138. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2139. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2140. ObjCIvarRefExpr *Result = new (Context)
  2141. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2142. IV->getLocation(), SelfExpr.get(), true, true);
  2143. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2144. if (!isUnevaluatedContext() &&
  2145. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2146. getCurFunction()->recordUseOfWeak(Result);
  2147. }
  2148. if (getLangOpts().ObjCAutoRefCount) {
  2149. if (CurContext->isClosure())
  2150. Diag(Loc, diag::warn_implicitly_retains_self)
  2151. << FixItHint::CreateInsertion(Loc, "self->");
  2152. }
  2153. return Result;
  2154. }
  2155. } else if (CurMethod->isInstanceMethod()) {
  2156. // We should warn if a local variable hides an ivar.
  2157. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2158. ObjCInterfaceDecl *ClassDeclared;
  2159. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2160. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2161. declaresSameEntity(IFace, ClassDeclared))
  2162. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2163. }
  2164. }
  2165. } else if (Lookup.isSingleResult() &&
  2166. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2167. // If accessing a stand-alone ivar in a class method, this is an error.
  2168. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  2169. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2170. << IV->getDeclName());
  2171. }
  2172. if (Lookup.empty() && II && AllowBuiltinCreation) {
  2173. // FIXME. Consolidate this with similar code in LookupName.
  2174. if (unsigned BuiltinID = II->getBuiltinID()) {
  2175. if (!(getLangOpts().CPlusPlus &&
  2176. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  2177. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  2178. S, Lookup.isForRedeclaration(),
  2179. Lookup.getNameLoc());
  2180. if (D) Lookup.addDecl(D);
  2181. }
  2182. }
  2183. }
  2184. // Sentinel value saying that we didn't do anything special.
  2185. return ExprResult((Expr *)nullptr);
  2186. }
  2187. /// Cast a base object to a member's actual type.
  2188. ///
  2189. /// Logically this happens in three phases:
  2190. ///
  2191. /// * First we cast from the base type to the naming class.
  2192. /// The naming class is the class into which we were looking
  2193. /// when we found the member; it's the qualifier type if a
  2194. /// qualifier was provided, and otherwise it's the base type.
  2195. ///
  2196. /// * Next we cast from the naming class to the declaring class.
  2197. /// If the member we found was brought into a class's scope by
  2198. /// a using declaration, this is that class; otherwise it's
  2199. /// the class declaring the member.
  2200. ///
  2201. /// * Finally we cast from the declaring class to the "true"
  2202. /// declaring class of the member. This conversion does not
  2203. /// obey access control.
  2204. ExprResult
  2205. Sema::PerformObjectMemberConversion(Expr *From,
  2206. NestedNameSpecifier *Qualifier,
  2207. NamedDecl *FoundDecl,
  2208. NamedDecl *Member) {
  2209. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2210. if (!RD)
  2211. return From;
  2212. QualType DestRecordType;
  2213. QualType DestType;
  2214. QualType FromRecordType;
  2215. QualType FromType = From->getType();
  2216. bool PointerConversions = false;
  2217. if (isa<FieldDecl>(Member)) {
  2218. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2219. if (FromType->getAs<PointerType>()) {
  2220. DestType = Context.getPointerType(DestRecordType);
  2221. FromRecordType = FromType->getPointeeType();
  2222. PointerConversions = true;
  2223. } else {
  2224. DestType = DestRecordType;
  2225. FromRecordType = FromType;
  2226. }
  2227. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2228. if (Method->isStatic())
  2229. return From;
  2230. DestType = Method->getThisType(Context);
  2231. DestRecordType = DestType->getPointeeType();
  2232. if (FromType->getAs<PointerType>()) {
  2233. FromRecordType = FromType->getPointeeType();
  2234. PointerConversions = true;
  2235. } else {
  2236. FromRecordType = FromType;
  2237. DestType = DestRecordType;
  2238. }
  2239. } else {
  2240. // No conversion necessary.
  2241. return From;
  2242. }
  2243. if (DestType->isDependentType() || FromType->isDependentType())
  2244. return From;
  2245. // If the unqualified types are the same, no conversion is necessary.
  2246. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2247. return From;
  2248. SourceRange FromRange = From->getSourceRange();
  2249. SourceLocation FromLoc = FromRange.getBegin();
  2250. ExprValueKind VK = From->getValueKind();
  2251. // C++ [class.member.lookup]p8:
  2252. // [...] Ambiguities can often be resolved by qualifying a name with its
  2253. // class name.
  2254. //
  2255. // If the member was a qualified name and the qualified referred to a
  2256. // specific base subobject type, we'll cast to that intermediate type
  2257. // first and then to the object in which the member is declared. That allows
  2258. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2259. //
  2260. // class Base { public: int x; };
  2261. // class Derived1 : public Base { };
  2262. // class Derived2 : public Base { };
  2263. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2264. //
  2265. // void VeryDerived::f() {
  2266. // x = 17; // error: ambiguous base subobjects
  2267. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2268. // }
  2269. if (Qualifier && Qualifier->getAsType()) {
  2270. QualType QType = QualType(Qualifier->getAsType(), 0);
  2271. assert(QType->isRecordType() && "lookup done with non-record type");
  2272. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2273. // In C++98, the qualifier type doesn't actually have to be a base
  2274. // type of the object type, in which case we just ignore it.
  2275. // Otherwise build the appropriate casts.
  2276. if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
  2277. CXXCastPath BasePath;
  2278. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2279. FromLoc, FromRange, &BasePath))
  2280. return ExprError();
  2281. if (PointerConversions)
  2282. QType = Context.getPointerType(QType);
  2283. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2284. VK, &BasePath).get();
  2285. FromType = QType;
  2286. FromRecordType = QRecordType;
  2287. // If the qualifier type was the same as the destination type,
  2288. // we're done.
  2289. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2290. return From;
  2291. }
  2292. }
  2293. bool IgnoreAccess = false;
  2294. // If we actually found the member through a using declaration, cast
  2295. // down to the using declaration's type.
  2296. //
  2297. // Pointer equality is fine here because only one declaration of a
  2298. // class ever has member declarations.
  2299. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2300. assert(isa<UsingShadowDecl>(FoundDecl));
  2301. QualType URecordType = Context.getTypeDeclType(
  2302. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2303. // We only need to do this if the naming-class to declaring-class
  2304. // conversion is non-trivial.
  2305. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2306. assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
  2307. CXXCastPath BasePath;
  2308. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2309. FromLoc, FromRange, &BasePath))
  2310. return ExprError();
  2311. QualType UType = URecordType;
  2312. if (PointerConversions)
  2313. UType = Context.getPointerType(UType);
  2314. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2315. VK, &BasePath).get();
  2316. FromType = UType;
  2317. FromRecordType = URecordType;
  2318. }
  2319. // We don't do access control for the conversion from the
  2320. // declaring class to the true declaring class.
  2321. IgnoreAccess = true;
  2322. }
  2323. CXXCastPath BasePath;
  2324. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2325. FromLoc, FromRange, &BasePath,
  2326. IgnoreAccess))
  2327. return ExprError();
  2328. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2329. VK, &BasePath);
  2330. }
  2331. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2332. const LookupResult &R,
  2333. bool HasTrailingLParen) {
  2334. // Only when used directly as the postfix-expression of a call.
  2335. if (!HasTrailingLParen)
  2336. return false;
  2337. // Never if a scope specifier was provided.
  2338. if (SS.isSet())
  2339. return false;
  2340. // Only in C++ or ObjC++.
  2341. if (!getLangOpts().CPlusPlus)
  2342. return false;
  2343. // Turn off ADL when we find certain kinds of declarations during
  2344. // normal lookup:
  2345. for (NamedDecl *D : R) {
  2346. // C++0x [basic.lookup.argdep]p3:
  2347. // -- a declaration of a class member
  2348. // Since using decls preserve this property, we check this on the
  2349. // original decl.
  2350. if (D->isCXXClassMember())
  2351. return false;
  2352. // C++0x [basic.lookup.argdep]p3:
  2353. // -- a block-scope function declaration that is not a
  2354. // using-declaration
  2355. // NOTE: we also trigger this for function templates (in fact, we
  2356. // don't check the decl type at all, since all other decl types
  2357. // turn off ADL anyway).
  2358. if (isa<UsingShadowDecl>(D))
  2359. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2360. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2361. return false;
  2362. // C++0x [basic.lookup.argdep]p3:
  2363. // -- a declaration that is neither a function or a function
  2364. // template
  2365. // And also for builtin functions.
  2366. if (isa<FunctionDecl>(D)) {
  2367. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2368. // But also builtin functions.
  2369. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2370. return false;
  2371. } else if (!isa<FunctionTemplateDecl>(D))
  2372. return false;
  2373. }
  2374. return true;
  2375. }
  2376. /// Diagnoses obvious problems with the use of the given declaration
  2377. /// as an expression. This is only actually called for lookups that
  2378. /// were not overloaded, and it doesn't promise that the declaration
  2379. /// will in fact be used.
  2380. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2381. if (D->isInvalidDecl())
  2382. return true;
  2383. if (isa<TypedefNameDecl>(D)) {
  2384. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2385. return true;
  2386. }
  2387. if (isa<ObjCInterfaceDecl>(D)) {
  2388. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2389. return true;
  2390. }
  2391. if (isa<NamespaceDecl>(D)) {
  2392. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2393. return true;
  2394. }
  2395. return false;
  2396. }
  2397. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2398. LookupResult &R, bool NeedsADL,
  2399. bool AcceptInvalidDecl) {
  2400. // If this is a single, fully-resolved result and we don't need ADL,
  2401. // just build an ordinary singleton decl ref.
  2402. if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
  2403. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2404. R.getRepresentativeDecl(), nullptr,
  2405. AcceptInvalidDecl);
  2406. // We only need to check the declaration if there's exactly one
  2407. // result, because in the overloaded case the results can only be
  2408. // functions and function templates.
  2409. if (R.isSingleResult() &&
  2410. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2411. return ExprError();
  2412. // Otherwise, just build an unresolved lookup expression. Suppress
  2413. // any lookup-related diagnostics; we'll hash these out later, when
  2414. // we've picked a target.
  2415. R.suppressDiagnostics();
  2416. UnresolvedLookupExpr *ULE
  2417. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2418. SS.getWithLocInContext(Context),
  2419. R.getLookupNameInfo(),
  2420. NeedsADL, R.isOverloadedResult(),
  2421. R.begin(), R.end());
  2422. return ULE;
  2423. }
  2424. static void
  2425. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  2426. ValueDecl *var, DeclContext *DC);
  2427. /// Complete semantic analysis for a reference to the given declaration.
  2428. ExprResult Sema::BuildDeclarationNameExpr(
  2429. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2430. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2431. bool AcceptInvalidDecl) {
  2432. assert(D && "Cannot refer to a NULL declaration");
  2433. assert(!isa<FunctionTemplateDecl>(D) &&
  2434. "Cannot refer unambiguously to a function template");
  2435. SourceLocation Loc = NameInfo.getLoc();
  2436. if (CheckDeclInExpr(*this, Loc, D))
  2437. return ExprError();
  2438. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2439. // Specifically diagnose references to class templates that are missing
  2440. // a template argument list.
  2441. diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
  2442. return ExprError();
  2443. }
  2444. // Make sure that we're referring to a value.
  2445. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2446. if (!VD) {
  2447. Diag(Loc, diag::err_ref_non_value)
  2448. << D << SS.getRange();
  2449. Diag(D->getLocation(), diag::note_declared_at);
  2450. return ExprError();
  2451. }
  2452. // Check whether this declaration can be used. Note that we suppress
  2453. // this check when we're going to perform argument-dependent lookup
  2454. // on this function name, because this might not be the function
  2455. // that overload resolution actually selects.
  2456. if (DiagnoseUseOfDecl(VD, Loc))
  2457. return ExprError();
  2458. // Only create DeclRefExpr's for valid Decl's.
  2459. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2460. return ExprError();
  2461. // Handle members of anonymous structs and unions. If we got here,
  2462. // and the reference is to a class member indirect field, then this
  2463. // must be the subject of a pointer-to-member expression.
  2464. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2465. if (!indirectField->isCXXClassMember())
  2466. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2467. indirectField);
  2468. {
  2469. QualType type = VD->getType();
  2470. if (type.isNull())
  2471. return ExprError();
  2472. if (auto *FPT = type->getAs<FunctionProtoType>()) {
  2473. // C++ [except.spec]p17:
  2474. // An exception-specification is considered to be needed when:
  2475. // - in an expression, the function is the unique lookup result or
  2476. // the selected member of a set of overloaded functions.
  2477. ResolveExceptionSpec(Loc, FPT);
  2478. type = VD->getType();
  2479. }
  2480. ExprValueKind valueKind = VK_RValue;
  2481. switch (D->getKind()) {
  2482. // Ignore all the non-ValueDecl kinds.
  2483. #define ABSTRACT_DECL(kind)
  2484. #define VALUE(type, base)
  2485. #define DECL(type, base) \
  2486. case Decl::type:
  2487. #include "clang/AST/DeclNodes.inc"
  2488. llvm_unreachable("invalid value decl kind");
  2489. // These shouldn't make it here.
  2490. case Decl::ObjCAtDefsField:
  2491. case Decl::ObjCIvar:
  2492. llvm_unreachable("forming non-member reference to ivar?");
  2493. // Enum constants are always r-values and never references.
  2494. // Unresolved using declarations are dependent.
  2495. case Decl::EnumConstant:
  2496. case Decl::UnresolvedUsingValue:
  2497. case Decl::OMPDeclareReduction:
  2498. valueKind = VK_RValue;
  2499. break;
  2500. // Fields and indirect fields that got here must be for
  2501. // pointer-to-member expressions; we just call them l-values for
  2502. // internal consistency, because this subexpression doesn't really
  2503. // exist in the high-level semantics.
  2504. case Decl::Field:
  2505. case Decl::IndirectField:
  2506. assert(getLangOpts().CPlusPlus &&
  2507. "building reference to field in C?");
  2508. // These can't have reference type in well-formed programs, but
  2509. // for internal consistency we do this anyway.
  2510. type = type.getNonReferenceType();
  2511. valueKind = VK_LValue;
  2512. break;
  2513. // Non-type template parameters are either l-values or r-values
  2514. // depending on the type.
  2515. case Decl::NonTypeTemplateParm: {
  2516. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2517. type = reftype->getPointeeType();
  2518. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2519. break;
  2520. }
  2521. // For non-references, we need to strip qualifiers just in case
  2522. // the template parameter was declared as 'const int' or whatever.
  2523. valueKind = VK_RValue;
  2524. type = type.getUnqualifiedType();
  2525. break;
  2526. }
  2527. case Decl::Var:
  2528. case Decl::VarTemplateSpecialization:
  2529. case Decl::VarTemplatePartialSpecialization:
  2530. case Decl::Decomposition:
  2531. case Decl::OMPCapturedExpr:
  2532. // In C, "extern void blah;" is valid and is an r-value.
  2533. if (!getLangOpts().CPlusPlus &&
  2534. !type.hasQualifiers() &&
  2535. type->isVoidType()) {
  2536. valueKind = VK_RValue;
  2537. break;
  2538. }
  2539. LLVM_FALLTHROUGH;
  2540. case Decl::ImplicitParam:
  2541. case Decl::ParmVar: {
  2542. // These are always l-values.
  2543. valueKind = VK_LValue;
  2544. type = type.getNonReferenceType();
  2545. // FIXME: Does the addition of const really only apply in
  2546. // potentially-evaluated contexts? Since the variable isn't actually
  2547. // captured in an unevaluated context, it seems that the answer is no.
  2548. if (!isUnevaluatedContext()) {
  2549. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2550. if (!CapturedType.isNull())
  2551. type = CapturedType;
  2552. }
  2553. break;
  2554. }
  2555. case Decl::Binding: {
  2556. // These are always lvalues.
  2557. valueKind = VK_LValue;
  2558. type = type.getNonReferenceType();
  2559. // FIXME: Support lambda-capture of BindingDecls, once CWG actually
  2560. // decides how that's supposed to work.
  2561. auto *BD = cast<BindingDecl>(VD);
  2562. if (BD->getDeclContext()->isFunctionOrMethod() &&
  2563. BD->getDeclContext() != CurContext)
  2564. diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
  2565. break;
  2566. }
  2567. case Decl::Function: {
  2568. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2569. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2570. type = Context.BuiltinFnTy;
  2571. valueKind = VK_RValue;
  2572. break;
  2573. }
  2574. }
  2575. const FunctionType *fty = type->castAs<FunctionType>();
  2576. // If we're referring to a function with an __unknown_anytype
  2577. // result type, make the entire expression __unknown_anytype.
  2578. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2579. type = Context.UnknownAnyTy;
  2580. valueKind = VK_RValue;
  2581. break;
  2582. }
  2583. // Functions are l-values in C++.
  2584. if (getLangOpts().CPlusPlus) {
  2585. valueKind = VK_LValue;
  2586. break;
  2587. }
  2588. // C99 DR 316 says that, if a function type comes from a
  2589. // function definition (without a prototype), that type is only
  2590. // used for checking compatibility. Therefore, when referencing
  2591. // the function, we pretend that we don't have the full function
  2592. // type.
  2593. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2594. isa<FunctionProtoType>(fty))
  2595. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2596. fty->getExtInfo());
  2597. // Functions are r-values in C.
  2598. valueKind = VK_RValue;
  2599. break;
  2600. }
  2601. case Decl::CXXDeductionGuide:
  2602. llvm_unreachable("building reference to deduction guide");
  2603. case Decl::MSProperty:
  2604. valueKind = VK_LValue;
  2605. break;
  2606. case Decl::CXXMethod:
  2607. // If we're referring to a method with an __unknown_anytype
  2608. // result type, make the entire expression __unknown_anytype.
  2609. // This should only be possible with a type written directly.
  2610. if (const FunctionProtoType *proto
  2611. = dyn_cast<FunctionProtoType>(VD->getType()))
  2612. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2613. type = Context.UnknownAnyTy;
  2614. valueKind = VK_RValue;
  2615. break;
  2616. }
  2617. // C++ methods are l-values if static, r-values if non-static.
  2618. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2619. valueKind = VK_LValue;
  2620. break;
  2621. }
  2622. LLVM_FALLTHROUGH;
  2623. case Decl::CXXConversion:
  2624. case Decl::CXXDestructor:
  2625. case Decl::CXXConstructor:
  2626. valueKind = VK_RValue;
  2627. break;
  2628. }
  2629. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2630. TemplateArgs);
  2631. }
  2632. }
  2633. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2634. SmallString<32> &Target) {
  2635. Target.resize(CharByteWidth * (Source.size() + 1));
  2636. char *ResultPtr = &Target[0];
  2637. const llvm::UTF8 *ErrorPtr;
  2638. bool success =
  2639. llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2640. (void)success;
  2641. assert(success);
  2642. Target.resize(ResultPtr - &Target[0]);
  2643. }
  2644. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2645. PredefinedExpr::IdentType IT) {
  2646. // Pick the current block, lambda, captured statement or function.
  2647. Decl *currentDecl = nullptr;
  2648. if (const BlockScopeInfo *BSI = getCurBlock())
  2649. currentDecl = BSI->TheDecl;
  2650. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2651. currentDecl = LSI->CallOperator;
  2652. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2653. currentDecl = CSI->TheCapturedDecl;
  2654. else
  2655. currentDecl = getCurFunctionOrMethodDecl();
  2656. if (!currentDecl) {
  2657. Diag(Loc, diag::ext_predef_outside_function);
  2658. currentDecl = Context.getTranslationUnitDecl();
  2659. }
  2660. QualType ResTy;
  2661. StringLiteral *SL = nullptr;
  2662. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2663. ResTy = Context.DependentTy;
  2664. else {
  2665. // Pre-defined identifiers are of type char[x], where x is the length of
  2666. // the string.
  2667. auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
  2668. unsigned Length = Str.length();
  2669. llvm::APInt LengthI(32, Length + 1);
  2670. if (IT == PredefinedExpr::LFunction) {
  2671. ResTy =
  2672. Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
  2673. SmallString<32> RawChars;
  2674. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2675. Str, RawChars);
  2676. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2677. /*IndexTypeQuals*/ 0);
  2678. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2679. /*Pascal*/ false, ResTy, Loc);
  2680. } else {
  2681. ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
  2682. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2683. /*IndexTypeQuals*/ 0);
  2684. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2685. /*Pascal*/ false, ResTy, Loc);
  2686. }
  2687. }
  2688. return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
  2689. }
  2690. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2691. PredefinedExpr::IdentType IT;
  2692. switch (Kind) {
  2693. default: llvm_unreachable("Unknown simple primary expr!");
  2694. case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2695. case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
  2696. case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
  2697. case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
  2698. case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
  2699. case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
  2700. }
  2701. return BuildPredefinedExpr(Loc, IT);
  2702. }
  2703. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2704. SmallString<16> CharBuffer;
  2705. bool Invalid = false;
  2706. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2707. if (Invalid)
  2708. return ExprError();
  2709. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2710. PP, Tok.getKind());
  2711. if (Literal.hadError())
  2712. return ExprError();
  2713. QualType Ty;
  2714. if (Literal.isWide())
  2715. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2716. else if (Literal.isUTF8() && getLangOpts().Char8)
  2717. Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
  2718. else if (Literal.isUTF16())
  2719. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2720. else if (Literal.isUTF32())
  2721. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2722. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2723. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2724. else
  2725. Ty = Context.CharTy; // 'x' -> char in C++
  2726. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2727. if (Literal.isWide())
  2728. Kind = CharacterLiteral::Wide;
  2729. else if (Literal.isUTF16())
  2730. Kind = CharacterLiteral::UTF16;
  2731. else if (Literal.isUTF32())
  2732. Kind = CharacterLiteral::UTF32;
  2733. else if (Literal.isUTF8())
  2734. Kind = CharacterLiteral::UTF8;
  2735. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2736. Tok.getLocation());
  2737. if (Literal.getUDSuffix().empty())
  2738. return Lit;
  2739. // We're building a user-defined literal.
  2740. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2741. SourceLocation UDSuffixLoc =
  2742. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2743. // Make sure we're allowed user-defined literals here.
  2744. if (!UDLScope)
  2745. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2746. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2747. // operator "" X (ch)
  2748. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2749. Lit, Tok.getLocation());
  2750. }
  2751. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2752. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2753. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2754. Context.IntTy, Loc);
  2755. }
  2756. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2757. QualType Ty, SourceLocation Loc) {
  2758. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2759. using llvm::APFloat;
  2760. APFloat Val(Format);
  2761. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2762. // Overflow is always an error, but underflow is only an error if
  2763. // we underflowed to zero (APFloat reports denormals as underflow).
  2764. if ((result & APFloat::opOverflow) ||
  2765. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2766. unsigned diagnostic;
  2767. SmallString<20> buffer;
  2768. if (result & APFloat::opOverflow) {
  2769. diagnostic = diag::warn_float_overflow;
  2770. APFloat::getLargest(Format).toString(buffer);
  2771. } else {
  2772. diagnostic = diag::warn_float_underflow;
  2773. APFloat::getSmallest(Format).toString(buffer);
  2774. }
  2775. S.Diag(Loc, diagnostic)
  2776. << Ty
  2777. << StringRef(buffer.data(), buffer.size());
  2778. }
  2779. bool isExact = (result == APFloat::opOK);
  2780. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2781. }
  2782. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2783. assert(E && "Invalid expression");
  2784. if (E->isValueDependent())
  2785. return false;
  2786. QualType QT = E->getType();
  2787. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2788. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2789. return true;
  2790. }
  2791. llvm::APSInt ValueAPS;
  2792. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2793. if (R.isInvalid())
  2794. return true;
  2795. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2796. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2797. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2798. << ValueAPS.toString(10) << ValueIsPositive;
  2799. return true;
  2800. }
  2801. return false;
  2802. }
  2803. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2804. // Fast path for a single digit (which is quite common). A single digit
  2805. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2806. if (Tok.getLength() == 1) {
  2807. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2808. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2809. }
  2810. SmallString<128> SpellingBuffer;
  2811. // NumericLiteralParser wants to overread by one character. Add padding to
  2812. // the buffer in case the token is copied to the buffer. If getSpelling()
  2813. // returns a StringRef to the memory buffer, it should have a null char at
  2814. // the EOF, so it is also safe.
  2815. SpellingBuffer.resize(Tok.getLength() + 1);
  2816. // Get the spelling of the token, which eliminates trigraphs, etc.
  2817. bool Invalid = false;
  2818. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2819. if (Invalid)
  2820. return ExprError();
  2821. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2822. if (Literal.hadError)
  2823. return ExprError();
  2824. if (Literal.hasUDSuffix()) {
  2825. // We're building a user-defined literal.
  2826. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2827. SourceLocation UDSuffixLoc =
  2828. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2829. // Make sure we're allowed user-defined literals here.
  2830. if (!UDLScope)
  2831. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2832. QualType CookedTy;
  2833. if (Literal.isFloatingLiteral()) {
  2834. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2835. // long double, the literal is treated as a call of the form
  2836. // operator "" X (f L)
  2837. CookedTy = Context.LongDoubleTy;
  2838. } else {
  2839. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2840. // unsigned long long, the literal is treated as a call of the form
  2841. // operator "" X (n ULL)
  2842. CookedTy = Context.UnsignedLongLongTy;
  2843. }
  2844. DeclarationName OpName =
  2845. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  2846. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  2847. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  2848. SourceLocation TokLoc = Tok.getLocation();
  2849. // Perform literal operator lookup to determine if we're building a raw
  2850. // literal or a cooked one.
  2851. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  2852. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  2853. /*AllowRaw*/ true, /*AllowTemplate*/ true,
  2854. /*AllowStringTemplate*/ false,
  2855. /*DiagnoseMissing*/ !Literal.isImaginary)) {
  2856. case LOLR_ErrorNoDiagnostic:
  2857. // Lookup failure for imaginary constants isn't fatal, there's still the
  2858. // GNU extension producing _Complex types.
  2859. break;
  2860. case LOLR_Error:
  2861. return ExprError();
  2862. case LOLR_Cooked: {
  2863. Expr *Lit;
  2864. if (Literal.isFloatingLiteral()) {
  2865. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  2866. } else {
  2867. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  2868. if (Literal.GetIntegerValue(ResultVal))
  2869. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2870. << /* Unsigned */ 1;
  2871. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  2872. Tok.getLocation());
  2873. }
  2874. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2875. }
  2876. case LOLR_Raw: {
  2877. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  2878. // literal is treated as a call of the form
  2879. // operator "" X ("n")
  2880. unsigned Length = Literal.getUDSuffixOffset();
  2881. QualType StrTy = Context.getConstantArrayType(
  2882. Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
  2883. llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
  2884. Expr *Lit = StringLiteral::Create(
  2885. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  2886. /*Pascal*/false, StrTy, &TokLoc, 1);
  2887. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2888. }
  2889. case LOLR_Template: {
  2890. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  2891. // template), L is treated as a call fo the form
  2892. // operator "" X <'c1', 'c2', ... 'ck'>()
  2893. // where n is the source character sequence c1 c2 ... ck.
  2894. TemplateArgumentListInfo ExplicitArgs;
  2895. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  2896. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  2897. llvm::APSInt Value(CharBits, CharIsUnsigned);
  2898. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  2899. Value = TokSpelling[I];
  2900. TemplateArgument Arg(Context, Value, Context.CharTy);
  2901. TemplateArgumentLocInfo ArgInfo;
  2902. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  2903. }
  2904. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  2905. &ExplicitArgs);
  2906. }
  2907. case LOLR_StringTemplate:
  2908. llvm_unreachable("unexpected literal operator lookup result");
  2909. }
  2910. }
  2911. Expr *Res;
  2912. if (Literal.isFixedPointLiteral()) {
  2913. QualType Ty;
  2914. if (Literal.isAccum) {
  2915. if (Literal.isHalf) {
  2916. Ty = Context.ShortAccumTy;
  2917. } else if (Literal.isLong) {
  2918. Ty = Context.LongAccumTy;
  2919. } else {
  2920. Ty = Context.AccumTy;
  2921. }
  2922. } else if (Literal.isFract) {
  2923. if (Literal.isHalf) {
  2924. Ty = Context.ShortFractTy;
  2925. } else if (Literal.isLong) {
  2926. Ty = Context.LongFractTy;
  2927. } else {
  2928. Ty = Context.FractTy;
  2929. }
  2930. }
  2931. if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
  2932. bool isSigned = !Literal.isUnsigned;
  2933. unsigned scale = Context.getFixedPointScale(Ty);
  2934. unsigned ibits = Context.getFixedPointIBits(Ty);
  2935. unsigned bit_width = Context.getTypeInfo(Ty).Width;
  2936. llvm::APInt Val(bit_width, 0, isSigned);
  2937. bool Overflowed = Literal.GetFixedPointValue(Val, scale);
  2938. // Do not use bit_width since some types may have padding like _Fract or
  2939. // unsigned _Accums if SameFBits is set.
  2940. auto MaxVal = llvm::APInt::getMaxValue(ibits + scale).zextOrSelf(bit_width);
  2941. if (Literal.isFract && Val == MaxVal + 1)
  2942. // Clause 6.4.4 - The value of a constant shall be in the range of
  2943. // representable values for its type, with exception for constants of a
  2944. // fract type with a value of exactly 1; such a constant shall denote
  2945. // the maximal value for the type.
  2946. --Val;
  2947. else if (Val.ugt(MaxVal) || Overflowed)
  2948. Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
  2949. Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
  2950. Tok.getLocation(), scale);
  2951. } else if (Literal.isFloatingLiteral()) {
  2952. QualType Ty;
  2953. if (Literal.isHalf){
  2954. if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
  2955. Ty = Context.HalfTy;
  2956. else {
  2957. Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
  2958. return ExprError();
  2959. }
  2960. } else if (Literal.isFloat)
  2961. Ty = Context.FloatTy;
  2962. else if (Literal.isLong)
  2963. Ty = Context.LongDoubleTy;
  2964. else if (Literal.isFloat16)
  2965. Ty = Context.Float16Ty;
  2966. else if (Literal.isFloat128)
  2967. Ty = Context.Float128Ty;
  2968. else
  2969. Ty = Context.DoubleTy;
  2970. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  2971. if (Ty == Context.DoubleTy) {
  2972. if (getLangOpts().SinglePrecisionConstants) {
  2973. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  2974. if (BTy->getKind() != BuiltinType::Float) {
  2975. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2976. }
  2977. } else if (getLangOpts().OpenCL &&
  2978. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  2979. // Impose single-precision float type when cl_khr_fp64 is not enabled.
  2980. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  2981. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2982. }
  2983. }
  2984. } else if (!Literal.isIntegerLiteral()) {
  2985. return ExprError();
  2986. } else {
  2987. QualType Ty;
  2988. // 'long long' is a C99 or C++11 feature.
  2989. if (!getLangOpts().C99 && Literal.isLongLong) {
  2990. if (getLangOpts().CPlusPlus)
  2991. Diag(Tok.getLocation(),
  2992. getLangOpts().CPlusPlus11 ?
  2993. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  2994. else
  2995. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  2996. }
  2997. // Get the value in the widest-possible width.
  2998. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  2999. llvm::APInt ResultVal(MaxWidth, 0);
  3000. if (Literal.GetIntegerValue(ResultVal)) {
  3001. // If this value didn't fit into uintmax_t, error and force to ull.
  3002. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3003. << /* Unsigned */ 1;
  3004. Ty = Context.UnsignedLongLongTy;
  3005. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  3006. "long long is not intmax_t?");
  3007. } else {
  3008. // If this value fits into a ULL, try to figure out what else it fits into
  3009. // according to the rules of C99 6.4.4.1p5.
  3010. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  3011. // be an unsigned int.
  3012. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  3013. // Check from smallest to largest, picking the smallest type we can.
  3014. unsigned Width = 0;
  3015. // Microsoft specific integer suffixes are explicitly sized.
  3016. if (Literal.MicrosoftInteger) {
  3017. if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  3018. Width = 8;
  3019. Ty = Context.CharTy;
  3020. } else {
  3021. Width = Literal.MicrosoftInteger;
  3022. Ty = Context.getIntTypeForBitwidth(Width,
  3023. /*Signed=*/!Literal.isUnsigned);
  3024. }
  3025. }
  3026. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  3027. // Are int/unsigned possibilities?
  3028. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3029. // Does it fit in a unsigned int?
  3030. if (ResultVal.isIntN(IntSize)) {
  3031. // Does it fit in a signed int?
  3032. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  3033. Ty = Context.IntTy;
  3034. else if (AllowUnsigned)
  3035. Ty = Context.UnsignedIntTy;
  3036. Width = IntSize;
  3037. }
  3038. }
  3039. // Are long/unsigned long possibilities?
  3040. if (Ty.isNull() && !Literal.isLongLong) {
  3041. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  3042. // Does it fit in a unsigned long?
  3043. if (ResultVal.isIntN(LongSize)) {
  3044. // Does it fit in a signed long?
  3045. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  3046. Ty = Context.LongTy;
  3047. else if (AllowUnsigned)
  3048. Ty = Context.UnsignedLongTy;
  3049. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  3050. // is compatible.
  3051. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3052. const unsigned LongLongSize =
  3053. Context.getTargetInfo().getLongLongWidth();
  3054. Diag(Tok.getLocation(),
  3055. getLangOpts().CPlusPlus
  3056. ? Literal.isLong
  3057. ? diag::warn_old_implicitly_unsigned_long_cxx
  3058. : /*C++98 UB*/ diag::
  3059. ext_old_implicitly_unsigned_long_cxx
  3060. : diag::warn_old_implicitly_unsigned_long)
  3061. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3062. : /*will be ill-formed*/ 1);
  3063. Ty = Context.UnsignedLongTy;
  3064. }
  3065. Width = LongSize;
  3066. }
  3067. }
  3068. // Check long long if needed.
  3069. if (Ty.isNull()) {
  3070. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3071. // Does it fit in a unsigned long long?
  3072. if (ResultVal.isIntN(LongLongSize)) {
  3073. // Does it fit in a signed long long?
  3074. // To be compatible with MSVC, hex integer literals ending with the
  3075. // LL or i64 suffix are always signed in Microsoft mode.
  3076. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3077. (getLangOpts().MSVCCompat && Literal.isLongLong)))
  3078. Ty = Context.LongLongTy;
  3079. else if (AllowUnsigned)
  3080. Ty = Context.UnsignedLongLongTy;
  3081. Width = LongLongSize;
  3082. }
  3083. }
  3084. // If we still couldn't decide a type, we probably have something that
  3085. // does not fit in a signed long long, but has no U suffix.
  3086. if (Ty.isNull()) {
  3087. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3088. Ty = Context.UnsignedLongLongTy;
  3089. Width = Context.getTargetInfo().getLongLongWidth();
  3090. }
  3091. if (ResultVal.getBitWidth() != Width)
  3092. ResultVal = ResultVal.trunc(Width);
  3093. }
  3094. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3095. }
  3096. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3097. if (Literal.isImaginary) {
  3098. Res = new (Context) ImaginaryLiteral(Res,
  3099. Context.getComplexType(Res->getType()));
  3100. Diag(Tok.getLocation(), diag::ext_imaginary_constant);
  3101. }
  3102. return Res;
  3103. }
  3104. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3105. assert(E && "ActOnParenExpr() missing expr");
  3106. return new (Context) ParenExpr(L, R, E);
  3107. }
  3108. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3109. SourceLocation Loc,
  3110. SourceRange ArgRange) {
  3111. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3112. // scalar or vector data type argument..."
  3113. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3114. // type (C99 6.2.5p18) or void.
  3115. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3116. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3117. << T << ArgRange;
  3118. return true;
  3119. }
  3120. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3121. "Scalar types should always be complete");
  3122. return false;
  3123. }
  3124. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3125. SourceLocation Loc,
  3126. SourceRange ArgRange,
  3127. UnaryExprOrTypeTrait TraitKind) {
  3128. // Invalid types must be hard errors for SFINAE in C++.
  3129. if (S.LangOpts.CPlusPlus)
  3130. return true;
  3131. // C99 6.5.3.4p1:
  3132. if (T->isFunctionType() &&
  3133. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
  3134. // sizeof(function)/alignof(function) is allowed as an extension.
  3135. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3136. << TraitKind << ArgRange;
  3137. return false;
  3138. }
  3139. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3140. // this is an error (OpenCL v1.1 s6.3.k)
  3141. if (T->isVoidType()) {
  3142. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3143. : diag::ext_sizeof_alignof_void_type;
  3144. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3145. return false;
  3146. }
  3147. return true;
  3148. }
  3149. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3150. SourceLocation Loc,
  3151. SourceRange ArgRange,
  3152. UnaryExprOrTypeTrait TraitKind) {
  3153. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3154. // runtime doesn't allow it.
  3155. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3156. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3157. << T << (TraitKind == UETT_SizeOf)
  3158. << ArgRange;
  3159. return true;
  3160. }
  3161. return false;
  3162. }
  3163. /// Check whether E is a pointer from a decayed array type (the decayed
  3164. /// pointer type is equal to T) and emit a warning if it is.
  3165. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3166. Expr *E) {
  3167. // Don't warn if the operation changed the type.
  3168. if (T != E->getType())
  3169. return;
  3170. // Now look for array decays.
  3171. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3172. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3173. return;
  3174. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3175. << ICE->getType()
  3176. << ICE->getSubExpr()->getType();
  3177. }
  3178. /// Check the constraints on expression operands to unary type expression
  3179. /// and type traits.
  3180. ///
  3181. /// Completes any types necessary and validates the constraints on the operand
  3182. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3183. /// the expression as it completes the type for that expression through template
  3184. /// instantiation, etc.
  3185. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3186. UnaryExprOrTypeTrait ExprKind) {
  3187. QualType ExprTy = E->getType();
  3188. assert(!ExprTy->isReferenceType());
  3189. if (ExprKind == UETT_VecStep)
  3190. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3191. E->getSourceRange());
  3192. // Whitelist some types as extensions
  3193. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3194. E->getSourceRange(), ExprKind))
  3195. return false;
  3196. // 'alignof' applied to an expression only requires the base element type of
  3197. // the expression to be complete. 'sizeof' requires the expression's type to
  3198. // be complete (and will attempt to complete it if it's an array of unknown
  3199. // bound).
  3200. if (ExprKind == UETT_AlignOf) {
  3201. if (RequireCompleteType(E->getExprLoc(),
  3202. Context.getBaseElementType(E->getType()),
  3203. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3204. E->getSourceRange()))
  3205. return true;
  3206. } else {
  3207. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3208. ExprKind, E->getSourceRange()))
  3209. return true;
  3210. }
  3211. // Completing the expression's type may have changed it.
  3212. ExprTy = E->getType();
  3213. assert(!ExprTy->isReferenceType());
  3214. if (ExprTy->isFunctionType()) {
  3215. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3216. << ExprKind << E->getSourceRange();
  3217. return true;
  3218. }
  3219. // The operand for sizeof and alignof is in an unevaluated expression context,
  3220. // so side effects could result in unintended consequences.
  3221. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
  3222. !inTemplateInstantiation() && E->HasSideEffects(Context, false))
  3223. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3224. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3225. E->getSourceRange(), ExprKind))
  3226. return true;
  3227. if (ExprKind == UETT_SizeOf) {
  3228. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3229. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3230. QualType OType = PVD->getOriginalType();
  3231. QualType Type = PVD->getType();
  3232. if (Type->isPointerType() && OType->isArrayType()) {
  3233. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3234. << Type << OType;
  3235. Diag(PVD->getLocation(), diag::note_declared_at);
  3236. }
  3237. }
  3238. }
  3239. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3240. // decays into a pointer and returns an unintended result. This is most
  3241. // likely a typo for "sizeof(array) op x".
  3242. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3243. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3244. BO->getLHS());
  3245. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3246. BO->getRHS());
  3247. }
  3248. }
  3249. return false;
  3250. }
  3251. /// Check the constraints on operands to unary expression and type
  3252. /// traits.
  3253. ///
  3254. /// This will complete any types necessary, and validate the various constraints
  3255. /// on those operands.
  3256. ///
  3257. /// The UsualUnaryConversions() function is *not* called by this routine.
  3258. /// C99 6.3.2.1p[2-4] all state:
  3259. /// Except when it is the operand of the sizeof operator ...
  3260. ///
  3261. /// C++ [expr.sizeof]p4
  3262. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3263. /// standard conversions are not applied to the operand of sizeof.
  3264. ///
  3265. /// This policy is followed for all of the unary trait expressions.
  3266. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3267. SourceLocation OpLoc,
  3268. SourceRange ExprRange,
  3269. UnaryExprOrTypeTrait ExprKind) {
  3270. if (ExprType->isDependentType())
  3271. return false;
  3272. // C++ [expr.sizeof]p2:
  3273. // When applied to a reference or a reference type, the result
  3274. // is the size of the referenced type.
  3275. // C++11 [expr.alignof]p3:
  3276. // When alignof is applied to a reference type, the result
  3277. // shall be the alignment of the referenced type.
  3278. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3279. ExprType = Ref->getPointeeType();
  3280. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3281. // When alignof or _Alignof is applied to an array type, the result
  3282. // is the alignment of the element type.
  3283. if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
  3284. ExprType = Context.getBaseElementType(ExprType);
  3285. if (ExprKind == UETT_VecStep)
  3286. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3287. // Whitelist some types as extensions
  3288. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3289. ExprKind))
  3290. return false;
  3291. if (RequireCompleteType(OpLoc, ExprType,
  3292. diag::err_sizeof_alignof_incomplete_type,
  3293. ExprKind, ExprRange))
  3294. return true;
  3295. if (ExprType->isFunctionType()) {
  3296. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3297. << ExprKind << ExprRange;
  3298. return true;
  3299. }
  3300. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3301. ExprKind))
  3302. return true;
  3303. return false;
  3304. }
  3305. static bool CheckAlignOfExpr(Sema &S, Expr *E) {
  3306. E = E->IgnoreParens();
  3307. // Cannot know anything else if the expression is dependent.
  3308. if (E->isTypeDependent())
  3309. return false;
  3310. if (E->getObjectKind() == OK_BitField) {
  3311. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
  3312. << 1 << E->getSourceRange();
  3313. return true;
  3314. }
  3315. ValueDecl *D = nullptr;
  3316. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3317. D = DRE->getDecl();
  3318. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3319. D = ME->getMemberDecl();
  3320. }
  3321. // If it's a field, require the containing struct to have a
  3322. // complete definition so that we can compute the layout.
  3323. //
  3324. // This can happen in C++11 onwards, either by naming the member
  3325. // in a way that is not transformed into a member access expression
  3326. // (in an unevaluated operand, for instance), or by naming the member
  3327. // in a trailing-return-type.
  3328. //
  3329. // For the record, since __alignof__ on expressions is a GCC
  3330. // extension, GCC seems to permit this but always gives the
  3331. // nonsensical answer 0.
  3332. //
  3333. // We don't really need the layout here --- we could instead just
  3334. // directly check for all the appropriate alignment-lowing
  3335. // attributes --- but that would require duplicating a lot of
  3336. // logic that just isn't worth duplicating for such a marginal
  3337. // use-case.
  3338. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3339. // Fast path this check, since we at least know the record has a
  3340. // definition if we can find a member of it.
  3341. if (!FD->getParent()->isCompleteDefinition()) {
  3342. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3343. << E->getSourceRange();
  3344. return true;
  3345. }
  3346. // Otherwise, if it's a field, and the field doesn't have
  3347. // reference type, then it must have a complete type (or be a
  3348. // flexible array member, which we explicitly want to
  3349. // white-list anyway), which makes the following checks trivial.
  3350. if (!FD->getType()->isReferenceType())
  3351. return false;
  3352. }
  3353. return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
  3354. }
  3355. bool Sema::CheckVecStepExpr(Expr *E) {
  3356. E = E->IgnoreParens();
  3357. // Cannot know anything else if the expression is dependent.
  3358. if (E->isTypeDependent())
  3359. return false;
  3360. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3361. }
  3362. static void captureVariablyModifiedType(ASTContext &Context, QualType T,
  3363. CapturingScopeInfo *CSI) {
  3364. assert(T->isVariablyModifiedType());
  3365. assert(CSI != nullptr);
  3366. // We're going to walk down into the type and look for VLA expressions.
  3367. do {
  3368. const Type *Ty = T.getTypePtr();
  3369. switch (Ty->getTypeClass()) {
  3370. #define TYPE(Class, Base)
  3371. #define ABSTRACT_TYPE(Class, Base)
  3372. #define NON_CANONICAL_TYPE(Class, Base)
  3373. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  3374. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  3375. #include "clang/AST/TypeNodes.def"
  3376. T = QualType();
  3377. break;
  3378. // These types are never variably-modified.
  3379. case Type::Builtin:
  3380. case Type::Complex:
  3381. case Type::Vector:
  3382. case Type::ExtVector:
  3383. case Type::Record:
  3384. case Type::Enum:
  3385. case Type::Elaborated:
  3386. case Type::TemplateSpecialization:
  3387. case Type::ObjCObject:
  3388. case Type::ObjCInterface:
  3389. case Type::ObjCObjectPointer:
  3390. case Type::ObjCTypeParam:
  3391. case Type::Pipe:
  3392. llvm_unreachable("type class is never variably-modified!");
  3393. case Type::Adjusted:
  3394. T = cast<AdjustedType>(Ty)->getOriginalType();
  3395. break;
  3396. case Type::Decayed:
  3397. T = cast<DecayedType>(Ty)->getPointeeType();
  3398. break;
  3399. case Type::Pointer:
  3400. T = cast<PointerType>(Ty)->getPointeeType();
  3401. break;
  3402. case Type::BlockPointer:
  3403. T = cast<BlockPointerType>(Ty)->getPointeeType();
  3404. break;
  3405. case Type::LValueReference:
  3406. case Type::RValueReference:
  3407. T = cast<ReferenceType>(Ty)->getPointeeType();
  3408. break;
  3409. case Type::MemberPointer:
  3410. T = cast<MemberPointerType>(Ty)->getPointeeType();
  3411. break;
  3412. case Type::ConstantArray:
  3413. case Type::IncompleteArray:
  3414. // Losing element qualification here is fine.
  3415. T = cast<ArrayType>(Ty)->getElementType();
  3416. break;
  3417. case Type::VariableArray: {
  3418. // Losing element qualification here is fine.
  3419. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  3420. // Unknown size indication requires no size computation.
  3421. // Otherwise, evaluate and record it.
  3422. if (auto Size = VAT->getSizeExpr()) {
  3423. if (!CSI->isVLATypeCaptured(VAT)) {
  3424. RecordDecl *CapRecord = nullptr;
  3425. if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
  3426. CapRecord = LSI->Lambda;
  3427. } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  3428. CapRecord = CRSI->TheRecordDecl;
  3429. }
  3430. if (CapRecord) {
  3431. auto ExprLoc = Size->getExprLoc();
  3432. auto SizeType = Context.getSizeType();
  3433. // Build the non-static data member.
  3434. auto Field =
  3435. FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
  3436. /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
  3437. /*BW*/ nullptr, /*Mutable*/ false,
  3438. /*InitStyle*/ ICIS_NoInit);
  3439. Field->setImplicit(true);
  3440. Field->setAccess(AS_private);
  3441. Field->setCapturedVLAType(VAT);
  3442. CapRecord->addDecl(Field);
  3443. CSI->addVLATypeCapture(ExprLoc, SizeType);
  3444. }
  3445. }
  3446. }
  3447. T = VAT->getElementType();
  3448. break;
  3449. }
  3450. case Type::FunctionProto:
  3451. case Type::FunctionNoProto:
  3452. T = cast<FunctionType>(Ty)->getReturnType();
  3453. break;
  3454. case Type::Paren:
  3455. case Type::TypeOf:
  3456. case Type::UnaryTransform:
  3457. case Type::Attributed:
  3458. case Type::SubstTemplateTypeParm:
  3459. case Type::PackExpansion:
  3460. // Keep walking after single level desugaring.
  3461. T = T.getSingleStepDesugaredType(Context);
  3462. break;
  3463. case Type::Typedef:
  3464. T = cast<TypedefType>(Ty)->desugar();
  3465. break;
  3466. case Type::Decltype:
  3467. T = cast<DecltypeType>(Ty)->desugar();
  3468. break;
  3469. case Type::Auto:
  3470. case Type::DeducedTemplateSpecialization:
  3471. T = cast<DeducedType>(Ty)->getDeducedType();
  3472. break;
  3473. case Type::TypeOfExpr:
  3474. T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  3475. break;
  3476. case Type::Atomic:
  3477. T = cast<AtomicType>(Ty)->getValueType();
  3478. break;
  3479. }
  3480. } while (!T.isNull() && T->isVariablyModifiedType());
  3481. }
  3482. /// Build a sizeof or alignof expression given a type operand.
  3483. ExprResult
  3484. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3485. SourceLocation OpLoc,
  3486. UnaryExprOrTypeTrait ExprKind,
  3487. SourceRange R) {
  3488. if (!TInfo)
  3489. return ExprError();
  3490. QualType T = TInfo->getType();
  3491. if (!T->isDependentType() &&
  3492. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3493. return ExprError();
  3494. if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
  3495. if (auto *TT = T->getAs<TypedefType>()) {
  3496. for (auto I = FunctionScopes.rbegin(),
  3497. E = std::prev(FunctionScopes.rend());
  3498. I != E; ++I) {
  3499. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  3500. if (CSI == nullptr)
  3501. break;
  3502. DeclContext *DC = nullptr;
  3503. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  3504. DC = LSI->CallOperator;
  3505. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  3506. DC = CRSI->TheCapturedDecl;
  3507. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  3508. DC = BSI->TheDecl;
  3509. if (DC) {
  3510. if (DC->containsDecl(TT->getDecl()))
  3511. break;
  3512. captureVariablyModifiedType(Context, T, CSI);
  3513. }
  3514. }
  3515. }
  3516. }
  3517. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3518. return new (Context) UnaryExprOrTypeTraitExpr(
  3519. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3520. }
  3521. /// Build a sizeof or alignof expression given an expression
  3522. /// operand.
  3523. ExprResult
  3524. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3525. UnaryExprOrTypeTrait ExprKind) {
  3526. ExprResult PE = CheckPlaceholderExpr(E);
  3527. if (PE.isInvalid())
  3528. return ExprError();
  3529. E = PE.get();
  3530. // Verify that the operand is valid.
  3531. bool isInvalid = false;
  3532. if (E->isTypeDependent()) {
  3533. // Delay type-checking for type-dependent expressions.
  3534. } else if (ExprKind == UETT_AlignOf) {
  3535. isInvalid = CheckAlignOfExpr(*this, E);
  3536. } else if (ExprKind == UETT_VecStep) {
  3537. isInvalid = CheckVecStepExpr(E);
  3538. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3539. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3540. isInvalid = true;
  3541. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3542. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
  3543. isInvalid = true;
  3544. } else {
  3545. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3546. }
  3547. if (isInvalid)
  3548. return ExprError();
  3549. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3550. PE = TransformToPotentiallyEvaluated(E);
  3551. if (PE.isInvalid()) return ExprError();
  3552. E = PE.get();
  3553. }
  3554. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3555. return new (Context) UnaryExprOrTypeTraitExpr(
  3556. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3557. }
  3558. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3559. /// expr and the same for @c alignof and @c __alignof
  3560. /// Note that the ArgRange is invalid if isType is false.
  3561. ExprResult
  3562. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3563. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3564. void *TyOrEx, SourceRange ArgRange) {
  3565. // If error parsing type, ignore.
  3566. if (!TyOrEx) return ExprError();
  3567. if (IsType) {
  3568. TypeSourceInfo *TInfo;
  3569. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3570. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3571. }
  3572. Expr *ArgEx = (Expr *)TyOrEx;
  3573. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3574. return Result;
  3575. }
  3576. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3577. bool IsReal) {
  3578. if (V.get()->isTypeDependent())
  3579. return S.Context.DependentTy;
  3580. // _Real and _Imag are only l-values for normal l-values.
  3581. if (V.get()->getObjectKind() != OK_Ordinary) {
  3582. V = S.DefaultLvalueConversion(V.get());
  3583. if (V.isInvalid())
  3584. return QualType();
  3585. }
  3586. // These operators return the element type of a complex type.
  3587. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3588. return CT->getElementType();
  3589. // Otherwise they pass through real integer and floating point types here.
  3590. if (V.get()->getType()->isArithmeticType())
  3591. return V.get()->getType();
  3592. // Test for placeholders.
  3593. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3594. if (PR.isInvalid()) return QualType();
  3595. if (PR.get() != V.get()) {
  3596. V = PR;
  3597. return CheckRealImagOperand(S, V, Loc, IsReal);
  3598. }
  3599. // Reject anything else.
  3600. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3601. << (IsReal ? "__real" : "__imag");
  3602. return QualType();
  3603. }
  3604. ExprResult
  3605. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3606. tok::TokenKind Kind, Expr *Input) {
  3607. UnaryOperatorKind Opc;
  3608. switch (Kind) {
  3609. default: llvm_unreachable("Unknown unary op!");
  3610. case tok::plusplus: Opc = UO_PostInc; break;
  3611. case tok::minusminus: Opc = UO_PostDec; break;
  3612. }
  3613. // Since this might is a postfix expression, get rid of ParenListExprs.
  3614. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3615. if (Result.isInvalid()) return ExprError();
  3616. Input = Result.get();
  3617. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3618. }
  3619. /// Diagnose if arithmetic on the given ObjC pointer is illegal.
  3620. ///
  3621. /// \return true on error
  3622. static bool checkArithmeticOnObjCPointer(Sema &S,
  3623. SourceLocation opLoc,
  3624. Expr *op) {
  3625. assert(op->getType()->isObjCObjectPointerType());
  3626. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3627. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3628. return false;
  3629. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3630. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3631. << op->getSourceRange();
  3632. return true;
  3633. }
  3634. static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
  3635. auto *BaseNoParens = Base->IgnoreParens();
  3636. if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
  3637. return MSProp->getPropertyDecl()->getType()->isArrayType();
  3638. return isa<MSPropertySubscriptExpr>(BaseNoParens);
  3639. }
  3640. ExprResult
  3641. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3642. Expr *idx, SourceLocation rbLoc) {
  3643. if (base && !base->getType().isNull() &&
  3644. base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
  3645. return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
  3646. /*Length=*/nullptr, rbLoc);
  3647. // Since this might be a postfix expression, get rid of ParenListExprs.
  3648. if (isa<ParenListExpr>(base)) {
  3649. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3650. if (result.isInvalid()) return ExprError();
  3651. base = result.get();
  3652. }
  3653. // Handle any non-overload placeholder types in the base and index
  3654. // expressions. We can't handle overloads here because the other
  3655. // operand might be an overloadable type, in which case the overload
  3656. // resolution for the operator overload should get the first crack
  3657. // at the overload.
  3658. bool IsMSPropertySubscript = false;
  3659. if (base->getType()->isNonOverloadPlaceholderType()) {
  3660. IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
  3661. if (!IsMSPropertySubscript) {
  3662. ExprResult result = CheckPlaceholderExpr(base);
  3663. if (result.isInvalid())
  3664. return ExprError();
  3665. base = result.get();
  3666. }
  3667. }
  3668. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3669. ExprResult result = CheckPlaceholderExpr(idx);
  3670. if (result.isInvalid()) return ExprError();
  3671. idx = result.get();
  3672. }
  3673. // Build an unanalyzed expression if either operand is type-dependent.
  3674. if (getLangOpts().CPlusPlus &&
  3675. (base->isTypeDependent() || idx->isTypeDependent())) {
  3676. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3677. VK_LValue, OK_Ordinary, rbLoc);
  3678. }
  3679. // MSDN, property (C++)
  3680. // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
  3681. // This attribute can also be used in the declaration of an empty array in a
  3682. // class or structure definition. For example:
  3683. // __declspec(property(get=GetX, put=PutX)) int x[];
  3684. // The above statement indicates that x[] can be used with one or more array
  3685. // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
  3686. // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
  3687. if (IsMSPropertySubscript) {
  3688. // Build MS property subscript expression if base is MS property reference
  3689. // or MS property subscript.
  3690. return new (Context) MSPropertySubscriptExpr(
  3691. base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
  3692. }
  3693. // Use C++ overloaded-operator rules if either operand has record
  3694. // type. The spec says to do this if either type is *overloadable*,
  3695. // but enum types can't declare subscript operators or conversion
  3696. // operators, so there's nothing interesting for overload resolution
  3697. // to do if there aren't any record types involved.
  3698. //
  3699. // ObjC pointers have their own subscripting logic that is not tied
  3700. // to overload resolution and so should not take this path.
  3701. if (getLangOpts().CPlusPlus &&
  3702. (base->getType()->isRecordType() ||
  3703. (!base->getType()->isObjCObjectPointerType() &&
  3704. idx->getType()->isRecordType()))) {
  3705. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3706. }
  3707. return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3708. }
  3709. ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
  3710. Expr *LowerBound,
  3711. SourceLocation ColonLoc, Expr *Length,
  3712. SourceLocation RBLoc) {
  3713. if (Base->getType()->isPlaceholderType() &&
  3714. !Base->getType()->isSpecificPlaceholderType(
  3715. BuiltinType::OMPArraySection)) {
  3716. ExprResult Result = CheckPlaceholderExpr(Base);
  3717. if (Result.isInvalid())
  3718. return ExprError();
  3719. Base = Result.get();
  3720. }
  3721. if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
  3722. ExprResult Result = CheckPlaceholderExpr(LowerBound);
  3723. if (Result.isInvalid())
  3724. return ExprError();
  3725. Result = DefaultLvalueConversion(Result.get());
  3726. if (Result.isInvalid())
  3727. return ExprError();
  3728. LowerBound = Result.get();
  3729. }
  3730. if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
  3731. ExprResult Result = CheckPlaceholderExpr(Length);
  3732. if (Result.isInvalid())
  3733. return ExprError();
  3734. Result = DefaultLvalueConversion(Result.get());
  3735. if (Result.isInvalid())
  3736. return ExprError();
  3737. Length = Result.get();
  3738. }
  3739. // Build an unanalyzed expression if either operand is type-dependent.
  3740. if (Base->isTypeDependent() ||
  3741. (LowerBound &&
  3742. (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
  3743. (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
  3744. return new (Context)
  3745. OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
  3746. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3747. }
  3748. // Perform default conversions.
  3749. QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
  3750. QualType ResultTy;
  3751. if (OriginalTy->isAnyPointerType()) {
  3752. ResultTy = OriginalTy->getPointeeType();
  3753. } else if (OriginalTy->isArrayType()) {
  3754. ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
  3755. } else {
  3756. return ExprError(
  3757. Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
  3758. << Base->getSourceRange());
  3759. }
  3760. // C99 6.5.2.1p1
  3761. if (LowerBound) {
  3762. auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
  3763. LowerBound);
  3764. if (Res.isInvalid())
  3765. return ExprError(Diag(LowerBound->getExprLoc(),
  3766. diag::err_omp_typecheck_section_not_integer)
  3767. << 0 << LowerBound->getSourceRange());
  3768. LowerBound = Res.get();
  3769. if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3770. LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3771. Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
  3772. << 0 << LowerBound->getSourceRange();
  3773. }
  3774. if (Length) {
  3775. auto Res =
  3776. PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
  3777. if (Res.isInvalid())
  3778. return ExprError(Diag(Length->getExprLoc(),
  3779. diag::err_omp_typecheck_section_not_integer)
  3780. << 1 << Length->getSourceRange());
  3781. Length = Res.get();
  3782. if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3783. Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3784. Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
  3785. << 1 << Length->getSourceRange();
  3786. }
  3787. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3788. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3789. // type. Note that functions are not objects, and that (in C99 parlance)
  3790. // incomplete types are not object types.
  3791. if (ResultTy->isFunctionType()) {
  3792. Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
  3793. << ResultTy << Base->getSourceRange();
  3794. return ExprError();
  3795. }
  3796. if (RequireCompleteType(Base->getExprLoc(), ResultTy,
  3797. diag::err_omp_section_incomplete_type, Base))
  3798. return ExprError();
  3799. if (LowerBound && !OriginalTy->isAnyPointerType()) {
  3800. llvm::APSInt LowerBoundValue;
  3801. if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
  3802. // OpenMP 4.5, [2.4 Array Sections]
  3803. // The array section must be a subset of the original array.
  3804. if (LowerBoundValue.isNegative()) {
  3805. Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
  3806. << LowerBound->getSourceRange();
  3807. return ExprError();
  3808. }
  3809. }
  3810. }
  3811. if (Length) {
  3812. llvm::APSInt LengthValue;
  3813. if (Length->EvaluateAsInt(LengthValue, Context)) {
  3814. // OpenMP 4.5, [2.4 Array Sections]
  3815. // The length must evaluate to non-negative integers.
  3816. if (LengthValue.isNegative()) {
  3817. Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
  3818. << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
  3819. << Length->getSourceRange();
  3820. return ExprError();
  3821. }
  3822. }
  3823. } else if (ColonLoc.isValid() &&
  3824. (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
  3825. !OriginalTy->isVariableArrayType()))) {
  3826. // OpenMP 4.5, [2.4 Array Sections]
  3827. // When the size of the array dimension is not known, the length must be
  3828. // specified explicitly.
  3829. Diag(ColonLoc, diag::err_omp_section_length_undefined)
  3830. << (!OriginalTy.isNull() && OriginalTy->isArrayType());
  3831. return ExprError();
  3832. }
  3833. if (!Base->getType()->isSpecificPlaceholderType(
  3834. BuiltinType::OMPArraySection)) {
  3835. ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
  3836. if (Result.isInvalid())
  3837. return ExprError();
  3838. Base = Result.get();
  3839. }
  3840. return new (Context)
  3841. OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
  3842. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3843. }
  3844. ExprResult
  3845. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  3846. Expr *Idx, SourceLocation RLoc) {
  3847. Expr *LHSExp = Base;
  3848. Expr *RHSExp = Idx;
  3849. ExprValueKind VK = VK_LValue;
  3850. ExprObjectKind OK = OK_Ordinary;
  3851. // Per C++ core issue 1213, the result is an xvalue if either operand is
  3852. // a non-lvalue array, and an lvalue otherwise.
  3853. if (getLangOpts().CPlusPlus11 &&
  3854. ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
  3855. (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
  3856. VK = VK_XValue;
  3857. // Perform default conversions.
  3858. if (!LHSExp->getType()->getAs<VectorType>()) {
  3859. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  3860. if (Result.isInvalid())
  3861. return ExprError();
  3862. LHSExp = Result.get();
  3863. }
  3864. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  3865. if (Result.isInvalid())
  3866. return ExprError();
  3867. RHSExp = Result.get();
  3868. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  3869. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  3870. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  3871. // in the subscript position. As a result, we need to derive the array base
  3872. // and index from the expression types.
  3873. Expr *BaseExpr, *IndexExpr;
  3874. QualType ResultType;
  3875. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  3876. BaseExpr = LHSExp;
  3877. IndexExpr = RHSExp;
  3878. ResultType = Context.DependentTy;
  3879. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  3880. BaseExpr = LHSExp;
  3881. IndexExpr = RHSExp;
  3882. ResultType = PTy->getPointeeType();
  3883. } else if (const ObjCObjectPointerType *PTy =
  3884. LHSTy->getAs<ObjCObjectPointerType>()) {
  3885. BaseExpr = LHSExp;
  3886. IndexExpr = RHSExp;
  3887. // Use custom logic if this should be the pseudo-object subscript
  3888. // expression.
  3889. if (!LangOpts.isSubscriptPointerArithmetic())
  3890. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  3891. nullptr);
  3892. ResultType = PTy->getPointeeType();
  3893. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  3894. // Handle the uncommon case of "123[Ptr]".
  3895. BaseExpr = RHSExp;
  3896. IndexExpr = LHSExp;
  3897. ResultType = PTy->getPointeeType();
  3898. } else if (const ObjCObjectPointerType *PTy =
  3899. RHSTy->getAs<ObjCObjectPointerType>()) {
  3900. // Handle the uncommon case of "123[Ptr]".
  3901. BaseExpr = RHSExp;
  3902. IndexExpr = LHSExp;
  3903. ResultType = PTy->getPointeeType();
  3904. if (!LangOpts.isSubscriptPointerArithmetic()) {
  3905. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  3906. << ResultType << BaseExpr->getSourceRange();
  3907. return ExprError();
  3908. }
  3909. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  3910. BaseExpr = LHSExp; // vectors: V[123]
  3911. IndexExpr = RHSExp;
  3912. VK = LHSExp->getValueKind();
  3913. if (VK != VK_RValue)
  3914. OK = OK_VectorComponent;
  3915. ResultType = VTy->getElementType();
  3916. QualType BaseType = BaseExpr->getType();
  3917. Qualifiers BaseQuals = BaseType.getQualifiers();
  3918. Qualifiers MemberQuals = ResultType.getQualifiers();
  3919. Qualifiers Combined = BaseQuals + MemberQuals;
  3920. if (Combined != MemberQuals)
  3921. ResultType = Context.getQualifiedType(ResultType, Combined);
  3922. } else if (LHSTy->isArrayType()) {
  3923. // If we see an array that wasn't promoted by
  3924. // DefaultFunctionArrayLvalueConversion, it must be an array that
  3925. // wasn't promoted because of the C90 rule that doesn't
  3926. // allow promoting non-lvalue arrays. Warn, then
  3927. // force the promotion here.
  3928. Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3929. LHSExp->getSourceRange();
  3930. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  3931. CK_ArrayToPointerDecay).get();
  3932. LHSTy = LHSExp->getType();
  3933. BaseExpr = LHSExp;
  3934. IndexExpr = RHSExp;
  3935. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  3936. } else if (RHSTy->isArrayType()) {
  3937. // Same as previous, except for 123[f().a] case
  3938. Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3939. RHSExp->getSourceRange();
  3940. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  3941. CK_ArrayToPointerDecay).get();
  3942. RHSTy = RHSExp->getType();
  3943. BaseExpr = RHSExp;
  3944. IndexExpr = LHSExp;
  3945. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  3946. } else {
  3947. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  3948. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  3949. }
  3950. // C99 6.5.2.1p1
  3951. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  3952. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  3953. << IndexExpr->getSourceRange());
  3954. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3955. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3956. && !IndexExpr->isTypeDependent())
  3957. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  3958. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3959. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3960. // type. Note that Functions are not objects, and that (in C99 parlance)
  3961. // incomplete types are not object types.
  3962. if (ResultType->isFunctionType()) {
  3963. Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
  3964. << ResultType << BaseExpr->getSourceRange();
  3965. return ExprError();
  3966. }
  3967. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  3968. // GNU extension: subscripting on pointer to void
  3969. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  3970. << BaseExpr->getSourceRange();
  3971. // C forbids expressions of unqualified void type from being l-values.
  3972. // See IsCForbiddenLValueType.
  3973. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  3974. } else if (!ResultType->isDependentType() &&
  3975. RequireCompleteType(LLoc, ResultType,
  3976. diag::err_subscript_incomplete_type, BaseExpr))
  3977. return ExprError();
  3978. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  3979. !ResultType.isCForbiddenLValueType());
  3980. return new (Context)
  3981. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  3982. }
  3983. bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
  3984. ParmVarDecl *Param) {
  3985. if (Param->hasUnparsedDefaultArg()) {
  3986. Diag(CallLoc,
  3987. diag::err_use_of_default_argument_to_function_declared_later) <<
  3988. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  3989. Diag(UnparsedDefaultArgLocs[Param],
  3990. diag::note_default_argument_declared_here);
  3991. return true;
  3992. }
  3993. if (Param->hasUninstantiatedDefaultArg()) {
  3994. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  3995. EnterExpressionEvaluationContext EvalContext(
  3996. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  3997. // Instantiate the expression.
  3998. //
  3999. // FIXME: Pass in a correct Pattern argument, otherwise
  4000. // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
  4001. //
  4002. // template<typename T>
  4003. // struct A {
  4004. // static int FooImpl();
  4005. //
  4006. // template<typename Tp>
  4007. // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
  4008. // // template argument list [[T], [Tp]], should be [[Tp]].
  4009. // friend A<Tp> Foo(int a);
  4010. // };
  4011. //
  4012. // template<typename T>
  4013. // A<T> Foo(int a = A<T>::FooImpl());
  4014. MultiLevelTemplateArgumentList MutiLevelArgList
  4015. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  4016. InstantiatingTemplate Inst(*this, CallLoc, Param,
  4017. MutiLevelArgList.getInnermost());
  4018. if (Inst.isInvalid())
  4019. return true;
  4020. if (Inst.isAlreadyInstantiating()) {
  4021. Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
  4022. Param->setInvalidDecl();
  4023. return true;
  4024. }
  4025. ExprResult Result;
  4026. {
  4027. // C++ [dcl.fct.default]p5:
  4028. // The names in the [default argument] expression are bound, and
  4029. // the semantic constraints are checked, at the point where the
  4030. // default argument expression appears.
  4031. ContextRAII SavedContext(*this, FD);
  4032. LocalInstantiationScope Local(*this);
  4033. Result = SubstInitializer(UninstExpr, MutiLevelArgList,
  4034. /*DirectInit*/false);
  4035. }
  4036. if (Result.isInvalid())
  4037. return true;
  4038. // Check the expression as an initializer for the parameter.
  4039. InitializedEntity Entity
  4040. = InitializedEntity::InitializeParameter(Context, Param);
  4041. InitializationKind Kind
  4042. = InitializationKind::CreateCopy(Param->getLocation(),
  4043. /*FIXME:EqualLoc*/UninstExpr->getLocStart());
  4044. Expr *ResultE = Result.getAs<Expr>();
  4045. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  4046. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  4047. if (Result.isInvalid())
  4048. return true;
  4049. Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
  4050. Param->getOuterLocStart());
  4051. if (Result.isInvalid())
  4052. return true;
  4053. // Remember the instantiated default argument.
  4054. Param->setDefaultArg(Result.getAs<Expr>());
  4055. if (ASTMutationListener *L = getASTMutationListener()) {
  4056. L->DefaultArgumentInstantiated(Param);
  4057. }
  4058. }
  4059. // If the default argument expression is not set yet, we are building it now.
  4060. if (!Param->hasInit()) {
  4061. Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
  4062. Param->setInvalidDecl();
  4063. return true;
  4064. }
  4065. // If the default expression creates temporaries, we need to
  4066. // push them to the current stack of expression temporaries so they'll
  4067. // be properly destroyed.
  4068. // FIXME: We should really be rebuilding the default argument with new
  4069. // bound temporaries; see the comment in PR5810.
  4070. // We don't need to do that with block decls, though, because
  4071. // blocks in default argument expression can never capture anything.
  4072. if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
  4073. // Set the "needs cleanups" bit regardless of whether there are
  4074. // any explicit objects.
  4075. Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
  4076. // Append all the objects to the cleanup list. Right now, this
  4077. // should always be a no-op, because blocks in default argument
  4078. // expressions should never be able to capture anything.
  4079. assert(!Init->getNumObjects() &&
  4080. "default argument expression has capturing blocks?");
  4081. }
  4082. // We already type-checked the argument, so we know it works.
  4083. // Just mark all of the declarations in this potentially-evaluated expression
  4084. // as being "referenced".
  4085. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  4086. /*SkipLocalVariables=*/true);
  4087. return false;
  4088. }
  4089. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  4090. FunctionDecl *FD, ParmVarDecl *Param) {
  4091. if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
  4092. return ExprError();
  4093. return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
  4094. }
  4095. Sema::VariadicCallType
  4096. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  4097. Expr *Fn) {
  4098. if (Proto && Proto->isVariadic()) {
  4099. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  4100. return VariadicConstructor;
  4101. else if (Fn && Fn->getType()->isBlockPointerType())
  4102. return VariadicBlock;
  4103. else if (FDecl) {
  4104. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4105. if (Method->isInstance())
  4106. return VariadicMethod;
  4107. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  4108. return VariadicMethod;
  4109. return VariadicFunction;
  4110. }
  4111. return VariadicDoesNotApply;
  4112. }
  4113. namespace {
  4114. class FunctionCallCCC : public FunctionCallFilterCCC {
  4115. public:
  4116. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  4117. unsigned NumArgs, MemberExpr *ME)
  4118. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  4119. FunctionName(FuncName) {}
  4120. bool ValidateCandidate(const TypoCorrection &candidate) override {
  4121. if (!candidate.getCorrectionSpecifier() ||
  4122. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  4123. return false;
  4124. }
  4125. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  4126. }
  4127. private:
  4128. const IdentifierInfo *const FunctionName;
  4129. };
  4130. }
  4131. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  4132. FunctionDecl *FDecl,
  4133. ArrayRef<Expr *> Args) {
  4134. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  4135. DeclarationName FuncName = FDecl->getDeclName();
  4136. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
  4137. if (TypoCorrection Corrected = S.CorrectTypo(
  4138. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  4139. S.getScopeForContext(S.CurContext), nullptr,
  4140. llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
  4141. Args.size(), ME),
  4142. Sema::CTK_ErrorRecovery)) {
  4143. if (NamedDecl *ND = Corrected.getFoundDecl()) {
  4144. if (Corrected.isOverloaded()) {
  4145. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  4146. OverloadCandidateSet::iterator Best;
  4147. for (NamedDecl *CD : Corrected) {
  4148. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  4149. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  4150. OCS);
  4151. }
  4152. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  4153. case OR_Success:
  4154. ND = Best->FoundDecl;
  4155. Corrected.setCorrectionDecl(ND);
  4156. break;
  4157. default:
  4158. break;
  4159. }
  4160. }
  4161. ND = ND->getUnderlyingDecl();
  4162. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
  4163. return Corrected;
  4164. }
  4165. }
  4166. return TypoCorrection();
  4167. }
  4168. /// ConvertArgumentsForCall - Converts the arguments specified in
  4169. /// Args/NumArgs to the parameter types of the function FDecl with
  4170. /// function prototype Proto. Call is the call expression itself, and
  4171. /// Fn is the function expression. For a C++ member function, this
  4172. /// routine does not attempt to convert the object argument. Returns
  4173. /// true if the call is ill-formed.
  4174. bool
  4175. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  4176. FunctionDecl *FDecl,
  4177. const FunctionProtoType *Proto,
  4178. ArrayRef<Expr *> Args,
  4179. SourceLocation RParenLoc,
  4180. bool IsExecConfig) {
  4181. // Bail out early if calling a builtin with custom typechecking.
  4182. if (FDecl)
  4183. if (unsigned ID = FDecl->getBuiltinID())
  4184. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  4185. return false;
  4186. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  4187. // assignment, to the types of the corresponding parameter, ...
  4188. unsigned NumParams = Proto->getNumParams();
  4189. bool Invalid = false;
  4190. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  4191. unsigned FnKind = Fn->getType()->isBlockPointerType()
  4192. ? 1 /* block */
  4193. : (IsExecConfig ? 3 /* kernel function (exec config) */
  4194. : 0 /* function */);
  4195. // If too few arguments are available (and we don't have default
  4196. // arguments for the remaining parameters), don't make the call.
  4197. if (Args.size() < NumParams) {
  4198. if (Args.size() < MinArgs) {
  4199. TypoCorrection TC;
  4200. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4201. unsigned diag_id =
  4202. MinArgs == NumParams && !Proto->isVariadic()
  4203. ? diag::err_typecheck_call_too_few_args_suggest
  4204. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  4205. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  4206. << static_cast<unsigned>(Args.size())
  4207. << TC.getCorrectionRange());
  4208. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  4209. Diag(RParenLoc,
  4210. MinArgs == NumParams && !Proto->isVariadic()
  4211. ? diag::err_typecheck_call_too_few_args_one
  4212. : diag::err_typecheck_call_too_few_args_at_least_one)
  4213. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  4214. else
  4215. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  4216. ? diag::err_typecheck_call_too_few_args
  4217. : diag::err_typecheck_call_too_few_args_at_least)
  4218. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  4219. << Fn->getSourceRange();
  4220. // Emit the location of the prototype.
  4221. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4222. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  4223. << FDecl;
  4224. return true;
  4225. }
  4226. Call->setNumArgs(Context, NumParams);
  4227. }
  4228. // If too many are passed and not variadic, error on the extras and drop
  4229. // them.
  4230. if (Args.size() > NumParams) {
  4231. if (!Proto->isVariadic()) {
  4232. TypoCorrection TC;
  4233. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4234. unsigned diag_id =
  4235. MinArgs == NumParams && !Proto->isVariadic()
  4236. ? diag::err_typecheck_call_too_many_args_suggest
  4237. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  4238. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  4239. << static_cast<unsigned>(Args.size())
  4240. << TC.getCorrectionRange());
  4241. } else if (NumParams == 1 && FDecl &&
  4242. FDecl->getParamDecl(0)->getDeclName())
  4243. Diag(Args[NumParams]->getLocStart(),
  4244. MinArgs == NumParams
  4245. ? diag::err_typecheck_call_too_many_args_one
  4246. : diag::err_typecheck_call_too_many_args_at_most_one)
  4247. << FnKind << FDecl->getParamDecl(0)
  4248. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  4249. << SourceRange(Args[NumParams]->getLocStart(),
  4250. Args.back()->getLocEnd());
  4251. else
  4252. Diag(Args[NumParams]->getLocStart(),
  4253. MinArgs == NumParams
  4254. ? diag::err_typecheck_call_too_many_args
  4255. : diag::err_typecheck_call_too_many_args_at_most)
  4256. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  4257. << Fn->getSourceRange()
  4258. << SourceRange(Args[NumParams]->getLocStart(),
  4259. Args.back()->getLocEnd());
  4260. // Emit the location of the prototype.
  4261. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4262. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  4263. << FDecl;
  4264. // This deletes the extra arguments.
  4265. Call->setNumArgs(Context, NumParams);
  4266. return true;
  4267. }
  4268. }
  4269. SmallVector<Expr *, 8> AllArgs;
  4270. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  4271. Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
  4272. Proto, 0, Args, AllArgs, CallType);
  4273. if (Invalid)
  4274. return true;
  4275. unsigned TotalNumArgs = AllArgs.size();
  4276. for (unsigned i = 0; i < TotalNumArgs; ++i)
  4277. Call->setArg(i, AllArgs[i]);
  4278. return false;
  4279. }
  4280. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  4281. const FunctionProtoType *Proto,
  4282. unsigned FirstParam, ArrayRef<Expr *> Args,
  4283. SmallVectorImpl<Expr *> &AllArgs,
  4284. VariadicCallType CallType, bool AllowExplicit,
  4285. bool IsListInitialization) {
  4286. unsigned NumParams = Proto->getNumParams();
  4287. bool Invalid = false;
  4288. size_t ArgIx = 0;
  4289. // Continue to check argument types (even if we have too few/many args).
  4290. for (unsigned i = FirstParam; i < NumParams; i++) {
  4291. QualType ProtoArgType = Proto->getParamType(i);
  4292. Expr *Arg;
  4293. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  4294. if (ArgIx < Args.size()) {
  4295. Arg = Args[ArgIx++];
  4296. if (RequireCompleteType(Arg->getLocStart(),
  4297. ProtoArgType,
  4298. diag::err_call_incomplete_argument, Arg))
  4299. return true;
  4300. // Strip the unbridged-cast placeholder expression off, if applicable.
  4301. bool CFAudited = false;
  4302. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  4303. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4304. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4305. Arg = stripARCUnbridgedCast(Arg);
  4306. else if (getLangOpts().ObjCAutoRefCount &&
  4307. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4308. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4309. CFAudited = true;
  4310. if (Proto->getExtParameterInfo(i).isNoEscape())
  4311. if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
  4312. BE->getBlockDecl()->setDoesNotEscape();
  4313. InitializedEntity Entity =
  4314. Param ? InitializedEntity::InitializeParameter(Context, Param,
  4315. ProtoArgType)
  4316. : InitializedEntity::InitializeParameter(
  4317. Context, ProtoArgType, Proto->isParamConsumed(i));
  4318. // Remember that parameter belongs to a CF audited API.
  4319. if (CFAudited)
  4320. Entity.setParameterCFAudited();
  4321. ExprResult ArgE = PerformCopyInitialization(
  4322. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  4323. if (ArgE.isInvalid())
  4324. return true;
  4325. Arg = ArgE.getAs<Expr>();
  4326. } else {
  4327. assert(Param && "can't use default arguments without a known callee");
  4328. ExprResult ArgExpr =
  4329. BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  4330. if (ArgExpr.isInvalid())
  4331. return true;
  4332. Arg = ArgExpr.getAs<Expr>();
  4333. }
  4334. // Check for array bounds violations for each argument to the call. This
  4335. // check only triggers warnings when the argument isn't a more complex Expr
  4336. // with its own checking, such as a BinaryOperator.
  4337. CheckArrayAccess(Arg);
  4338. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  4339. CheckStaticArrayArgument(CallLoc, Param, Arg);
  4340. AllArgs.push_back(Arg);
  4341. }
  4342. // If this is a variadic call, handle args passed through "...".
  4343. if (CallType != VariadicDoesNotApply) {
  4344. // Assume that extern "C" functions with variadic arguments that
  4345. // return __unknown_anytype aren't *really* variadic.
  4346. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  4347. FDecl->isExternC()) {
  4348. for (Expr *A : Args.slice(ArgIx)) {
  4349. QualType paramType; // ignored
  4350. ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
  4351. Invalid |= arg.isInvalid();
  4352. AllArgs.push_back(arg.get());
  4353. }
  4354. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  4355. } else {
  4356. for (Expr *A : Args.slice(ArgIx)) {
  4357. ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
  4358. Invalid |= Arg.isInvalid();
  4359. AllArgs.push_back(Arg.get());
  4360. }
  4361. }
  4362. // Check for array bounds violations.
  4363. for (Expr *A : Args.slice(ArgIx))
  4364. CheckArrayAccess(A);
  4365. }
  4366. return Invalid;
  4367. }
  4368. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  4369. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  4370. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  4371. TL = DTL.getOriginalLoc();
  4372. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  4373. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  4374. << ATL.getLocalSourceRange();
  4375. }
  4376. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  4377. /// array parameter, check that it is non-null, and that if it is formed by
  4378. /// array-to-pointer decay, the underlying array is sufficiently large.
  4379. ///
  4380. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  4381. /// array type derivation, then for each call to the function, the value of the
  4382. /// corresponding actual argument shall provide access to the first element of
  4383. /// an array with at least as many elements as specified by the size expression.
  4384. void
  4385. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  4386. ParmVarDecl *Param,
  4387. const Expr *ArgExpr) {
  4388. // Static array parameters are not supported in C++.
  4389. if (!Param || getLangOpts().CPlusPlus)
  4390. return;
  4391. QualType OrigTy = Param->getOriginalType();
  4392. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  4393. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  4394. return;
  4395. if (ArgExpr->isNullPointerConstant(Context,
  4396. Expr::NPC_NeverValueDependent)) {
  4397. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  4398. DiagnoseCalleeStaticArrayParam(*this, Param);
  4399. return;
  4400. }
  4401. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  4402. if (!CAT)
  4403. return;
  4404. const ConstantArrayType *ArgCAT =
  4405. Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
  4406. if (!ArgCAT)
  4407. return;
  4408. if (ArgCAT->getSize().ult(CAT->getSize())) {
  4409. Diag(CallLoc, diag::warn_static_array_too_small)
  4410. << ArgExpr->getSourceRange()
  4411. << (unsigned) ArgCAT->getSize().getZExtValue()
  4412. << (unsigned) CAT->getSize().getZExtValue();
  4413. DiagnoseCalleeStaticArrayParam(*this, Param);
  4414. }
  4415. }
  4416. /// Given a function expression of unknown-any type, try to rebuild it
  4417. /// to have a function type.
  4418. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4419. /// Is the given type a placeholder that we need to lower out
  4420. /// immediately during argument processing?
  4421. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4422. // Placeholders are never sugared.
  4423. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4424. if (!placeholder) return false;
  4425. switch (placeholder->getKind()) {
  4426. // Ignore all the non-placeholder types.
  4427. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  4428. case BuiltinType::Id:
  4429. #include "clang/Basic/OpenCLImageTypes.def"
  4430. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4431. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4432. #include "clang/AST/BuiltinTypes.def"
  4433. return false;
  4434. // We cannot lower out overload sets; they might validly be resolved
  4435. // by the call machinery.
  4436. case BuiltinType::Overload:
  4437. return false;
  4438. // Unbridged casts in ARC can be handled in some call positions and
  4439. // should be left in place.
  4440. case BuiltinType::ARCUnbridgedCast:
  4441. return false;
  4442. // Pseudo-objects should be converted as soon as possible.
  4443. case BuiltinType::PseudoObject:
  4444. return true;
  4445. // The debugger mode could theoretically but currently does not try
  4446. // to resolve unknown-typed arguments based on known parameter types.
  4447. case BuiltinType::UnknownAny:
  4448. return true;
  4449. // These are always invalid as call arguments and should be reported.
  4450. case BuiltinType::BoundMember:
  4451. case BuiltinType::BuiltinFn:
  4452. case BuiltinType::OMPArraySection:
  4453. return true;
  4454. }
  4455. llvm_unreachable("bad builtin type kind");
  4456. }
  4457. /// Check an argument list for placeholders that we won't try to
  4458. /// handle later.
  4459. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4460. // Apply this processing to all the arguments at once instead of
  4461. // dying at the first failure.
  4462. bool hasInvalid = false;
  4463. for (size_t i = 0, e = args.size(); i != e; i++) {
  4464. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4465. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4466. if (result.isInvalid()) hasInvalid = true;
  4467. else args[i] = result.get();
  4468. } else if (hasInvalid) {
  4469. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4470. }
  4471. }
  4472. return hasInvalid;
  4473. }
  4474. /// If a builtin function has a pointer argument with no explicit address
  4475. /// space, then it should be able to accept a pointer to any address
  4476. /// space as input. In order to do this, we need to replace the
  4477. /// standard builtin declaration with one that uses the same address space
  4478. /// as the call.
  4479. ///
  4480. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4481. /// it does not contain any pointer arguments without
  4482. /// an address space qualifer. Otherwise the rewritten
  4483. /// FunctionDecl is returned.
  4484. /// TODO: Handle pointer return types.
  4485. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4486. const FunctionDecl *FDecl,
  4487. MultiExprArg ArgExprs) {
  4488. QualType DeclType = FDecl->getType();
  4489. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4490. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
  4491. !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
  4492. return nullptr;
  4493. bool NeedsNewDecl = false;
  4494. unsigned i = 0;
  4495. SmallVector<QualType, 8> OverloadParams;
  4496. for (QualType ParamType : FT->param_types()) {
  4497. // Convert array arguments to pointer to simplify type lookup.
  4498. ExprResult ArgRes =
  4499. Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
  4500. if (ArgRes.isInvalid())
  4501. return nullptr;
  4502. Expr *Arg = ArgRes.get();
  4503. QualType ArgType = Arg->getType();
  4504. if (!ParamType->isPointerType() ||
  4505. ParamType.getQualifiers().hasAddressSpace() ||
  4506. !ArgType->isPointerType() ||
  4507. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4508. OverloadParams.push_back(ParamType);
  4509. continue;
  4510. }
  4511. NeedsNewDecl = true;
  4512. LangAS AS = ArgType->getPointeeType().getAddressSpace();
  4513. QualType PointeeType = ParamType->getPointeeType();
  4514. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4515. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4516. }
  4517. if (!NeedsNewDecl)
  4518. return nullptr;
  4519. FunctionProtoType::ExtProtoInfo EPI;
  4520. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4521. OverloadParams, EPI);
  4522. DeclContext *Parent = Context.getTranslationUnitDecl();
  4523. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4524. FDecl->getLocation(),
  4525. FDecl->getLocation(),
  4526. FDecl->getIdentifier(),
  4527. OverloadTy,
  4528. /*TInfo=*/nullptr,
  4529. SC_Extern, false,
  4530. /*hasPrototype=*/true);
  4531. SmallVector<ParmVarDecl*, 16> Params;
  4532. FT = cast<FunctionProtoType>(OverloadTy);
  4533. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4534. QualType ParamType = FT->getParamType(i);
  4535. ParmVarDecl *Parm =
  4536. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4537. SourceLocation(), nullptr, ParamType,
  4538. /*TInfo=*/nullptr, SC_None, nullptr);
  4539. Parm->setScopeInfo(0, i);
  4540. Params.push_back(Parm);
  4541. }
  4542. OverloadDecl->setParams(Params);
  4543. return OverloadDecl;
  4544. }
  4545. static void checkDirectCallValidity(Sema &S, const Expr *Fn,
  4546. FunctionDecl *Callee,
  4547. MultiExprArg ArgExprs) {
  4548. // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
  4549. // similar attributes) really don't like it when functions are called with an
  4550. // invalid number of args.
  4551. if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
  4552. /*PartialOverloading=*/false) &&
  4553. !Callee->isVariadic())
  4554. return;
  4555. if (Callee->getMinRequiredArguments() > ArgExprs.size())
  4556. return;
  4557. if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
  4558. S.Diag(Fn->getLocStart(),
  4559. isa<CXXMethodDecl>(Callee)
  4560. ? diag::err_ovl_no_viable_member_function_in_call
  4561. : diag::err_ovl_no_viable_function_in_call)
  4562. << Callee << Callee->getSourceRange();
  4563. S.Diag(Callee->getLocation(),
  4564. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  4565. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4566. return;
  4567. }
  4568. }
  4569. static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
  4570. const UnresolvedMemberExpr *const UME, Sema &S) {
  4571. const auto GetFunctionLevelDCIfCXXClass =
  4572. [](Sema &S) -> const CXXRecordDecl * {
  4573. const DeclContext *const DC = S.getFunctionLevelDeclContext();
  4574. if (!DC || !DC->getParent())
  4575. return nullptr;
  4576. // If the call to some member function was made from within a member
  4577. // function body 'M' return return 'M's parent.
  4578. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  4579. return MD->getParent()->getCanonicalDecl();
  4580. // else the call was made from within a default member initializer of a
  4581. // class, so return the class.
  4582. if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
  4583. return RD->getCanonicalDecl();
  4584. return nullptr;
  4585. };
  4586. // If our DeclContext is neither a member function nor a class (in the
  4587. // case of a lambda in a default member initializer), we can't have an
  4588. // enclosing 'this'.
  4589. const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
  4590. if (!CurParentClass)
  4591. return false;
  4592. // The naming class for implicit member functions call is the class in which
  4593. // name lookup starts.
  4594. const CXXRecordDecl *const NamingClass =
  4595. UME->getNamingClass()->getCanonicalDecl();
  4596. assert(NamingClass && "Must have naming class even for implicit access");
  4597. // If the unresolved member functions were found in a 'naming class' that is
  4598. // related (either the same or derived from) to the class that contains the
  4599. // member function that itself contained the implicit member access.
  4600. return CurParentClass == NamingClass ||
  4601. CurParentClass->isDerivedFrom(NamingClass);
  4602. }
  4603. static void
  4604. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4605. Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
  4606. if (!UME)
  4607. return;
  4608. LambdaScopeInfo *const CurLSI = S.getCurLambda();
  4609. // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
  4610. // already been captured, or if this is an implicit member function call (if
  4611. // it isn't, an attempt to capture 'this' should already have been made).
  4612. if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
  4613. !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
  4614. return;
  4615. // Check if the naming class in which the unresolved members were found is
  4616. // related (same as or is a base of) to the enclosing class.
  4617. if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
  4618. return;
  4619. DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
  4620. // If the enclosing function is not dependent, then this lambda is
  4621. // capture ready, so if we can capture this, do so.
  4622. if (!EnclosingFunctionCtx->isDependentContext()) {
  4623. // If the current lambda and all enclosing lambdas can capture 'this' -
  4624. // then go ahead and capture 'this' (since our unresolved overload set
  4625. // contains at least one non-static member function).
  4626. if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
  4627. S.CheckCXXThisCapture(CallLoc);
  4628. } else if (S.CurContext->isDependentContext()) {
  4629. // ... since this is an implicit member reference, that might potentially
  4630. // involve a 'this' capture, mark 'this' for potential capture in
  4631. // enclosing lambdas.
  4632. if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
  4633. CurLSI->addPotentialThisCapture(CallLoc);
  4634. }
  4635. }
  4636. /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
  4637. /// This provides the location of the left/right parens and a list of comma
  4638. /// locations.
  4639. ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  4640. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4641. Expr *ExecConfig, bool IsExecConfig) {
  4642. // Since this might be a postfix expression, get rid of ParenListExprs.
  4643. ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
  4644. if (Result.isInvalid()) return ExprError();
  4645. Fn = Result.get();
  4646. if (checkArgsForPlaceholders(*this, ArgExprs))
  4647. return ExprError();
  4648. if (getLangOpts().CPlusPlus) {
  4649. // If this is a pseudo-destructor expression, build the call immediately.
  4650. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4651. if (!ArgExprs.empty()) {
  4652. // Pseudo-destructor calls should not have any arguments.
  4653. Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
  4654. << FixItHint::CreateRemoval(
  4655. SourceRange(ArgExprs.front()->getLocStart(),
  4656. ArgExprs.back()->getLocEnd()));
  4657. }
  4658. return new (Context)
  4659. CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
  4660. }
  4661. if (Fn->getType() == Context.PseudoObjectTy) {
  4662. ExprResult result = CheckPlaceholderExpr(Fn);
  4663. if (result.isInvalid()) return ExprError();
  4664. Fn = result.get();
  4665. }
  4666. // Determine whether this is a dependent call inside a C++ template,
  4667. // in which case we won't do any semantic analysis now.
  4668. bool Dependent = false;
  4669. if (Fn->isTypeDependent())
  4670. Dependent = true;
  4671. else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4672. Dependent = true;
  4673. if (Dependent) {
  4674. if (ExecConfig) {
  4675. return new (Context) CUDAKernelCallExpr(
  4676. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4677. Context.DependentTy, VK_RValue, RParenLoc);
  4678. } else {
  4679. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4680. *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
  4681. Fn->getLocStart());
  4682. return new (Context) CallExpr(
  4683. Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
  4684. }
  4685. }
  4686. // Determine whether this is a call to an object (C++ [over.call.object]).
  4687. if (Fn->getType()->isRecordType())
  4688. return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
  4689. RParenLoc);
  4690. if (Fn->getType() == Context.UnknownAnyTy) {
  4691. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4692. if (result.isInvalid()) return ExprError();
  4693. Fn = result.get();
  4694. }
  4695. if (Fn->getType() == Context.BoundMemberTy) {
  4696. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4697. RParenLoc);
  4698. }
  4699. }
  4700. // Check for overloaded calls. This can happen even in C due to extensions.
  4701. if (Fn->getType() == Context.OverloadTy) {
  4702. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4703. // We aren't supposed to apply this logic if there's an '&' involved.
  4704. if (!find.HasFormOfMemberPointer) {
  4705. if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4706. return new (Context) CallExpr(
  4707. Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
  4708. OverloadExpr *ovl = find.Expression;
  4709. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
  4710. return BuildOverloadedCallExpr(
  4711. Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
  4712. /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
  4713. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4714. RParenLoc);
  4715. }
  4716. }
  4717. // If we're directly calling a function, get the appropriate declaration.
  4718. if (Fn->getType() == Context.UnknownAnyTy) {
  4719. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4720. if (result.isInvalid()) return ExprError();
  4721. Fn = result.get();
  4722. }
  4723. Expr *NakedFn = Fn->IgnoreParens();
  4724. bool CallingNDeclIndirectly = false;
  4725. NamedDecl *NDecl = nullptr;
  4726. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
  4727. if (UnOp->getOpcode() == UO_AddrOf) {
  4728. CallingNDeclIndirectly = true;
  4729. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4730. }
  4731. }
  4732. if (isa<DeclRefExpr>(NakedFn)) {
  4733. NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
  4734. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  4735. if (FDecl && FDecl->getBuiltinID()) {
  4736. // Rewrite the function decl for this builtin by replacing parameters
  4737. // with no explicit address space with the address space of the arguments
  4738. // in ArgExprs.
  4739. if ((FDecl =
  4740. rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  4741. NDecl = FDecl;
  4742. Fn = DeclRefExpr::Create(
  4743. Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
  4744. SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
  4745. }
  4746. }
  4747. } else if (isa<MemberExpr>(NakedFn))
  4748. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  4749. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  4750. if (CallingNDeclIndirectly &&
  4751. !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  4752. Fn->getLocStart()))
  4753. return ExprError();
  4754. if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
  4755. return ExprError();
  4756. checkDirectCallValidity(*this, Fn, FD, ArgExprs);
  4757. }
  4758. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  4759. ExecConfig, IsExecConfig);
  4760. }
  4761. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  4762. ///
  4763. /// __builtin_astype( value, dst type )
  4764. ///
  4765. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  4766. SourceLocation BuiltinLoc,
  4767. SourceLocation RParenLoc) {
  4768. ExprValueKind VK = VK_RValue;
  4769. ExprObjectKind OK = OK_Ordinary;
  4770. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  4771. QualType SrcTy = E->getType();
  4772. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  4773. return ExprError(Diag(BuiltinLoc,
  4774. diag::err_invalid_astype_of_different_size)
  4775. << DstTy
  4776. << SrcTy
  4777. << E->getSourceRange());
  4778. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  4779. }
  4780. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  4781. /// provided arguments.
  4782. ///
  4783. /// __builtin_convertvector( value, dst type )
  4784. ///
  4785. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  4786. SourceLocation BuiltinLoc,
  4787. SourceLocation RParenLoc) {
  4788. TypeSourceInfo *TInfo;
  4789. GetTypeFromParser(ParsedDestTy, &TInfo);
  4790. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  4791. }
  4792. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  4793. /// i.e. an expression not of \p OverloadTy. The expression should
  4794. /// unary-convert to an expression of function-pointer or
  4795. /// block-pointer type.
  4796. ///
  4797. /// \param NDecl the declaration being called, if available
  4798. ExprResult
  4799. Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  4800. SourceLocation LParenLoc,
  4801. ArrayRef<Expr *> Args,
  4802. SourceLocation RParenLoc,
  4803. Expr *Config, bool IsExecConfig) {
  4804. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  4805. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  4806. // Functions with 'interrupt' attribute cannot be called directly.
  4807. if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
  4808. Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
  4809. return ExprError();
  4810. }
  4811. // Interrupt handlers don't save off the VFP regs automatically on ARM,
  4812. // so there's some risk when calling out to non-interrupt handler functions
  4813. // that the callee might not preserve them. This is easy to diagnose here,
  4814. // but can be very challenging to debug.
  4815. if (auto *Caller = getCurFunctionDecl())
  4816. if (Caller->hasAttr<ARMInterruptAttr>()) {
  4817. bool VFP = Context.getTargetInfo().hasFeature("vfp");
  4818. if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
  4819. Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
  4820. }
  4821. // Promote the function operand.
  4822. // We special-case function promotion here because we only allow promoting
  4823. // builtin functions to function pointers in the callee of a call.
  4824. ExprResult Result;
  4825. if (BuiltinID &&
  4826. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  4827. Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
  4828. CK_BuiltinFnToFnPtr).get();
  4829. } else {
  4830. Result = CallExprUnaryConversions(Fn);
  4831. }
  4832. if (Result.isInvalid())
  4833. return ExprError();
  4834. Fn = Result.get();
  4835. // Make the call expr early, before semantic checks. This guarantees cleanup
  4836. // of arguments and function on error.
  4837. CallExpr *TheCall;
  4838. if (Config)
  4839. TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
  4840. cast<CallExpr>(Config), Args,
  4841. Context.BoolTy, VK_RValue,
  4842. RParenLoc);
  4843. else
  4844. TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
  4845. VK_RValue, RParenLoc);
  4846. if (!getLangOpts().CPlusPlus) {
  4847. // C cannot always handle TypoExpr nodes in builtin calls and direct
  4848. // function calls as their argument checking don't necessarily handle
  4849. // dependent types properly, so make sure any TypoExprs have been
  4850. // dealt with.
  4851. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  4852. if (!Result.isUsable()) return ExprError();
  4853. TheCall = dyn_cast<CallExpr>(Result.get());
  4854. if (!TheCall) return Result;
  4855. Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
  4856. }
  4857. // Bail out early if calling a builtin with custom typechecking.
  4858. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  4859. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4860. retry:
  4861. const FunctionType *FuncT;
  4862. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  4863. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  4864. // have type pointer to function".
  4865. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  4866. if (!FuncT)
  4867. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4868. << Fn->getType() << Fn->getSourceRange());
  4869. } else if (const BlockPointerType *BPT =
  4870. Fn->getType()->getAs<BlockPointerType>()) {
  4871. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  4872. } else {
  4873. // Handle calls to expressions of unknown-any type.
  4874. if (Fn->getType() == Context.UnknownAnyTy) {
  4875. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  4876. if (rewrite.isInvalid()) return ExprError();
  4877. Fn = rewrite.get();
  4878. TheCall->setCallee(Fn);
  4879. goto retry;
  4880. }
  4881. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4882. << Fn->getType() << Fn->getSourceRange());
  4883. }
  4884. if (getLangOpts().CUDA) {
  4885. if (Config) {
  4886. // CUDA: Kernel calls must be to global functions
  4887. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  4888. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  4889. << FDecl << Fn->getSourceRange());
  4890. // CUDA: Kernel function must have 'void' return type
  4891. if (!FuncT->getReturnType()->isVoidType())
  4892. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  4893. << Fn->getType() << Fn->getSourceRange());
  4894. } else {
  4895. // CUDA: Calls to global functions must be configured
  4896. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  4897. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  4898. << FDecl << Fn->getSourceRange());
  4899. }
  4900. }
  4901. // Check for a valid return type
  4902. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
  4903. FDecl))
  4904. return ExprError();
  4905. // We know the result type of the call, set it.
  4906. TheCall->setType(FuncT->getCallResultType(Context));
  4907. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  4908. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
  4909. if (Proto) {
  4910. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  4911. IsExecConfig))
  4912. return ExprError();
  4913. } else {
  4914. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  4915. if (FDecl) {
  4916. // Check if we have too few/too many template arguments, based
  4917. // on our knowledge of the function definition.
  4918. const FunctionDecl *Def = nullptr;
  4919. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  4920. Proto = Def->getType()->getAs<FunctionProtoType>();
  4921. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  4922. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  4923. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  4924. }
  4925. // If the function we're calling isn't a function prototype, but we have
  4926. // a function prototype from a prior declaratiom, use that prototype.
  4927. if (!FDecl->hasPrototype())
  4928. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  4929. }
  4930. // Promote the arguments (C99 6.5.2.2p6).
  4931. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  4932. Expr *Arg = Args[i];
  4933. if (Proto && i < Proto->getNumParams()) {
  4934. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4935. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  4936. ExprResult ArgE =
  4937. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4938. if (ArgE.isInvalid())
  4939. return true;
  4940. Arg = ArgE.getAs<Expr>();
  4941. } else {
  4942. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  4943. if (ArgE.isInvalid())
  4944. return true;
  4945. Arg = ArgE.getAs<Expr>();
  4946. }
  4947. if (RequireCompleteType(Arg->getLocStart(),
  4948. Arg->getType(),
  4949. diag::err_call_incomplete_argument, Arg))
  4950. return ExprError();
  4951. TheCall->setArg(i, Arg);
  4952. }
  4953. }
  4954. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4955. if (!Method->isStatic())
  4956. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  4957. << Fn->getSourceRange());
  4958. // Check for sentinels
  4959. if (NDecl)
  4960. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  4961. // Do special checking on direct calls to functions.
  4962. if (FDecl) {
  4963. if (CheckFunctionCall(FDecl, TheCall, Proto))
  4964. return ExprError();
  4965. if (BuiltinID)
  4966. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4967. } else if (NDecl) {
  4968. if (CheckPointerCall(NDecl, TheCall, Proto))
  4969. return ExprError();
  4970. } else {
  4971. if (CheckOtherCall(TheCall, Proto))
  4972. return ExprError();
  4973. }
  4974. return MaybeBindToTemporary(TheCall);
  4975. }
  4976. ExprResult
  4977. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  4978. SourceLocation RParenLoc, Expr *InitExpr) {
  4979. assert(Ty && "ActOnCompoundLiteral(): missing type");
  4980. assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
  4981. TypeSourceInfo *TInfo;
  4982. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  4983. if (!TInfo)
  4984. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  4985. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  4986. }
  4987. ExprResult
  4988. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  4989. SourceLocation RParenLoc, Expr *LiteralExpr) {
  4990. QualType literalType = TInfo->getType();
  4991. if (literalType->isArrayType()) {
  4992. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  4993. diag::err_illegal_decl_array_incomplete_type,
  4994. SourceRange(LParenLoc,
  4995. LiteralExpr->getSourceRange().getEnd())))
  4996. return ExprError();
  4997. if (literalType->isVariableArrayType())
  4998. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  4999. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  5000. } else if (!literalType->isDependentType() &&
  5001. RequireCompleteType(LParenLoc, literalType,
  5002. diag::err_typecheck_decl_incomplete_type,
  5003. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  5004. return ExprError();
  5005. InitializedEntity Entity
  5006. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  5007. InitializationKind Kind
  5008. = InitializationKind::CreateCStyleCast(LParenLoc,
  5009. SourceRange(LParenLoc, RParenLoc),
  5010. /*InitList=*/true);
  5011. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  5012. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  5013. &literalType);
  5014. if (Result.isInvalid())
  5015. return ExprError();
  5016. LiteralExpr = Result.get();
  5017. bool isFileScope = !CurContext->isFunctionOrMethod();
  5018. if (isFileScope &&
  5019. !LiteralExpr->isTypeDependent() &&
  5020. !LiteralExpr->isValueDependent() &&
  5021. !literalType->isDependentType()) { // 6.5.2.5p3
  5022. if (CheckForConstantInitializer(LiteralExpr, literalType))
  5023. return ExprError();
  5024. }
  5025. // In C, compound literals are l-values for some reason.
  5026. // For GCC compatibility, in C++, file-scope array compound literals with
  5027. // constant initializers are also l-values, and compound literals are
  5028. // otherwise prvalues.
  5029. //
  5030. // (GCC also treats C++ list-initialized file-scope array prvalues with
  5031. // constant initializers as l-values, but that's non-conforming, so we don't
  5032. // follow it there.)
  5033. //
  5034. // FIXME: It would be better to handle the lvalue cases as materializing and
  5035. // lifetime-extending a temporary object, but our materialized temporaries
  5036. // representation only supports lifetime extension from a variable, not "out
  5037. // of thin air".
  5038. // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
  5039. // is bound to the result of applying array-to-pointer decay to the compound
  5040. // literal.
  5041. // FIXME: GCC supports compound literals of reference type, which should
  5042. // obviously have a value kind derived from the kind of reference involved.
  5043. ExprValueKind VK =
  5044. (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
  5045. ? VK_RValue
  5046. : VK_LValue;
  5047. return MaybeBindToTemporary(
  5048. new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  5049. VK, LiteralExpr, isFileScope));
  5050. }
  5051. ExprResult
  5052. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  5053. SourceLocation RBraceLoc) {
  5054. // Immediately handle non-overload placeholders. Overloads can be
  5055. // resolved contextually, but everything else here can't.
  5056. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  5057. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  5058. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  5059. // Ignore failures; dropping the entire initializer list because
  5060. // of one failure would be terrible for indexing/etc.
  5061. if (result.isInvalid()) continue;
  5062. InitArgList[I] = result.get();
  5063. }
  5064. }
  5065. // Semantic analysis for initializers is done by ActOnDeclarator() and
  5066. // CheckInitializer() - it requires knowledge of the object being initialized.
  5067. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  5068. RBraceLoc);
  5069. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  5070. return E;
  5071. }
  5072. /// Do an explicit extend of the given block pointer if we're in ARC.
  5073. void Sema::maybeExtendBlockObject(ExprResult &E) {
  5074. assert(E.get()->getType()->isBlockPointerType());
  5075. assert(E.get()->isRValue());
  5076. // Only do this in an r-value context.
  5077. if (!getLangOpts().ObjCAutoRefCount) return;
  5078. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  5079. CK_ARCExtendBlockObject, E.get(),
  5080. /*base path*/ nullptr, VK_RValue);
  5081. Cleanup.setExprNeedsCleanups(true);
  5082. }
  5083. /// Prepare a conversion of the given expression to an ObjC object
  5084. /// pointer type.
  5085. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  5086. QualType type = E.get()->getType();
  5087. if (type->isObjCObjectPointerType()) {
  5088. return CK_BitCast;
  5089. } else if (type->isBlockPointerType()) {
  5090. maybeExtendBlockObject(E);
  5091. return CK_BlockPointerToObjCPointerCast;
  5092. } else {
  5093. assert(type->isPointerType());
  5094. return CK_CPointerToObjCPointerCast;
  5095. }
  5096. }
  5097. /// Prepares for a scalar cast, performing all the necessary stages
  5098. /// except the final cast and returning the kind required.
  5099. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  5100. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  5101. // Also, callers should have filtered out the invalid cases with
  5102. // pointers. Everything else should be possible.
  5103. QualType SrcTy = Src.get()->getType();
  5104. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  5105. return CK_NoOp;
  5106. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  5107. case Type::STK_MemberPointer:
  5108. llvm_unreachable("member pointer type in C");
  5109. case Type::STK_CPointer:
  5110. case Type::STK_BlockPointer:
  5111. case Type::STK_ObjCObjectPointer:
  5112. switch (DestTy->getScalarTypeKind()) {
  5113. case Type::STK_CPointer: {
  5114. LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
  5115. LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
  5116. if (SrcAS != DestAS)
  5117. return CK_AddressSpaceConversion;
  5118. return CK_BitCast;
  5119. }
  5120. case Type::STK_BlockPointer:
  5121. return (SrcKind == Type::STK_BlockPointer
  5122. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  5123. case Type::STK_ObjCObjectPointer:
  5124. if (SrcKind == Type::STK_ObjCObjectPointer)
  5125. return CK_BitCast;
  5126. if (SrcKind == Type::STK_CPointer)
  5127. return CK_CPointerToObjCPointerCast;
  5128. maybeExtendBlockObject(Src);
  5129. return CK_BlockPointerToObjCPointerCast;
  5130. case Type::STK_Bool:
  5131. return CK_PointerToBoolean;
  5132. case Type::STK_Integral:
  5133. return CK_PointerToIntegral;
  5134. case Type::STK_Floating:
  5135. case Type::STK_FloatingComplex:
  5136. case Type::STK_IntegralComplex:
  5137. case Type::STK_MemberPointer:
  5138. llvm_unreachable("illegal cast from pointer");
  5139. }
  5140. llvm_unreachable("Should have returned before this");
  5141. case Type::STK_Bool: // casting from bool is like casting from an integer
  5142. case Type::STK_Integral:
  5143. switch (DestTy->getScalarTypeKind()) {
  5144. case Type::STK_CPointer:
  5145. case Type::STK_ObjCObjectPointer:
  5146. case Type::STK_BlockPointer:
  5147. if (Src.get()->isNullPointerConstant(Context,
  5148. Expr::NPC_ValueDependentIsNull))
  5149. return CK_NullToPointer;
  5150. return CK_IntegralToPointer;
  5151. case Type::STK_Bool:
  5152. return CK_IntegralToBoolean;
  5153. case Type::STK_Integral:
  5154. return CK_IntegralCast;
  5155. case Type::STK_Floating:
  5156. return CK_IntegralToFloating;
  5157. case Type::STK_IntegralComplex:
  5158. Src = ImpCastExprToType(Src.get(),
  5159. DestTy->castAs<ComplexType>()->getElementType(),
  5160. CK_IntegralCast);
  5161. return CK_IntegralRealToComplex;
  5162. case Type::STK_FloatingComplex:
  5163. Src = ImpCastExprToType(Src.get(),
  5164. DestTy->castAs<ComplexType>()->getElementType(),
  5165. CK_IntegralToFloating);
  5166. return CK_FloatingRealToComplex;
  5167. case Type::STK_MemberPointer:
  5168. llvm_unreachable("member pointer type in C");
  5169. }
  5170. llvm_unreachable("Should have returned before this");
  5171. case Type::STK_Floating:
  5172. switch (DestTy->getScalarTypeKind()) {
  5173. case Type::STK_Floating:
  5174. return CK_FloatingCast;
  5175. case Type::STK_Bool:
  5176. return CK_FloatingToBoolean;
  5177. case Type::STK_Integral:
  5178. return CK_FloatingToIntegral;
  5179. case Type::STK_FloatingComplex:
  5180. Src = ImpCastExprToType(Src.get(),
  5181. DestTy->castAs<ComplexType>()->getElementType(),
  5182. CK_FloatingCast);
  5183. return CK_FloatingRealToComplex;
  5184. case Type::STK_IntegralComplex:
  5185. Src = ImpCastExprToType(Src.get(),
  5186. DestTy->castAs<ComplexType>()->getElementType(),
  5187. CK_FloatingToIntegral);
  5188. return CK_IntegralRealToComplex;
  5189. case Type::STK_CPointer:
  5190. case Type::STK_ObjCObjectPointer:
  5191. case Type::STK_BlockPointer:
  5192. llvm_unreachable("valid float->pointer cast?");
  5193. case Type::STK_MemberPointer:
  5194. llvm_unreachable("member pointer type in C");
  5195. }
  5196. llvm_unreachable("Should have returned before this");
  5197. case Type::STK_FloatingComplex:
  5198. switch (DestTy->getScalarTypeKind()) {
  5199. case Type::STK_FloatingComplex:
  5200. return CK_FloatingComplexCast;
  5201. case Type::STK_IntegralComplex:
  5202. return CK_FloatingComplexToIntegralComplex;
  5203. case Type::STK_Floating: {
  5204. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5205. if (Context.hasSameType(ET, DestTy))
  5206. return CK_FloatingComplexToReal;
  5207. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  5208. return CK_FloatingCast;
  5209. }
  5210. case Type::STK_Bool:
  5211. return CK_FloatingComplexToBoolean;
  5212. case Type::STK_Integral:
  5213. Src = ImpCastExprToType(Src.get(),
  5214. SrcTy->castAs<ComplexType>()->getElementType(),
  5215. CK_FloatingComplexToReal);
  5216. return CK_FloatingToIntegral;
  5217. case Type::STK_CPointer:
  5218. case Type::STK_ObjCObjectPointer:
  5219. case Type::STK_BlockPointer:
  5220. llvm_unreachable("valid complex float->pointer cast?");
  5221. case Type::STK_MemberPointer:
  5222. llvm_unreachable("member pointer type in C");
  5223. }
  5224. llvm_unreachable("Should have returned before this");
  5225. case Type::STK_IntegralComplex:
  5226. switch (DestTy->getScalarTypeKind()) {
  5227. case Type::STK_FloatingComplex:
  5228. return CK_IntegralComplexToFloatingComplex;
  5229. case Type::STK_IntegralComplex:
  5230. return CK_IntegralComplexCast;
  5231. case Type::STK_Integral: {
  5232. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5233. if (Context.hasSameType(ET, DestTy))
  5234. return CK_IntegralComplexToReal;
  5235. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  5236. return CK_IntegralCast;
  5237. }
  5238. case Type::STK_Bool:
  5239. return CK_IntegralComplexToBoolean;
  5240. case Type::STK_Floating:
  5241. Src = ImpCastExprToType(Src.get(),
  5242. SrcTy->castAs<ComplexType>()->getElementType(),
  5243. CK_IntegralComplexToReal);
  5244. return CK_IntegralToFloating;
  5245. case Type::STK_CPointer:
  5246. case Type::STK_ObjCObjectPointer:
  5247. case Type::STK_BlockPointer:
  5248. llvm_unreachable("valid complex int->pointer cast?");
  5249. case Type::STK_MemberPointer:
  5250. llvm_unreachable("member pointer type in C");
  5251. }
  5252. llvm_unreachable("Should have returned before this");
  5253. }
  5254. llvm_unreachable("Unhandled scalar cast");
  5255. }
  5256. static bool breakDownVectorType(QualType type, uint64_t &len,
  5257. QualType &eltType) {
  5258. // Vectors are simple.
  5259. if (const VectorType *vecType = type->getAs<VectorType>()) {
  5260. len = vecType->getNumElements();
  5261. eltType = vecType->getElementType();
  5262. assert(eltType->isScalarType());
  5263. return true;
  5264. }
  5265. // We allow lax conversion to and from non-vector types, but only if
  5266. // they're real types (i.e. non-complex, non-pointer scalar types).
  5267. if (!type->isRealType()) return false;
  5268. len = 1;
  5269. eltType = type;
  5270. return true;
  5271. }
  5272. /// Are the two types lax-compatible vector types? That is, given
  5273. /// that one of them is a vector, do they have equal storage sizes,
  5274. /// where the storage size is the number of elements times the element
  5275. /// size?
  5276. ///
  5277. /// This will also return false if either of the types is neither a
  5278. /// vector nor a real type.
  5279. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
  5280. assert(destTy->isVectorType() || srcTy->isVectorType());
  5281. // Disallow lax conversions between scalars and ExtVectors (these
  5282. // conversions are allowed for other vector types because common headers
  5283. // depend on them). Most scalar OP ExtVector cases are handled by the
  5284. // splat path anyway, which does what we want (convert, not bitcast).
  5285. // What this rules out for ExtVectors is crazy things like char4*float.
  5286. if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
  5287. if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
  5288. uint64_t srcLen, destLen;
  5289. QualType srcEltTy, destEltTy;
  5290. if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
  5291. if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
  5292. // ASTContext::getTypeSize will return the size rounded up to a
  5293. // power of 2, so instead of using that, we need to use the raw
  5294. // element size multiplied by the element count.
  5295. uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
  5296. uint64_t destEltSize = Context.getTypeSize(destEltTy);
  5297. return (srcLen * srcEltSize == destLen * destEltSize);
  5298. }
  5299. /// Is this a legal conversion between two types, one of which is
  5300. /// known to be a vector type?
  5301. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  5302. assert(destTy->isVectorType() || srcTy->isVectorType());
  5303. if (!Context.getLangOpts().LaxVectorConversions)
  5304. return false;
  5305. return areLaxCompatibleVectorTypes(srcTy, destTy);
  5306. }
  5307. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  5308. CastKind &Kind) {
  5309. assert(VectorTy->isVectorType() && "Not a vector type!");
  5310. if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
  5311. if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
  5312. return Diag(R.getBegin(),
  5313. Ty->isVectorType() ?
  5314. diag::err_invalid_conversion_between_vectors :
  5315. diag::err_invalid_conversion_between_vector_and_integer)
  5316. << VectorTy << Ty << R;
  5317. } else
  5318. return Diag(R.getBegin(),
  5319. diag::err_invalid_conversion_between_vector_and_scalar)
  5320. << VectorTy << Ty << R;
  5321. Kind = CK_BitCast;
  5322. return false;
  5323. }
  5324. ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
  5325. QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
  5326. if (DestElemTy == SplattedExpr->getType())
  5327. return SplattedExpr;
  5328. assert(DestElemTy->isFloatingType() ||
  5329. DestElemTy->isIntegralOrEnumerationType());
  5330. CastKind CK;
  5331. if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
  5332. // OpenCL requires that we convert `true` boolean expressions to -1, but
  5333. // only when splatting vectors.
  5334. if (DestElemTy->isFloatingType()) {
  5335. // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
  5336. // in two steps: boolean to signed integral, then to floating.
  5337. ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
  5338. CK_BooleanToSignedIntegral);
  5339. SplattedExpr = CastExprRes.get();
  5340. CK = CK_IntegralToFloating;
  5341. } else {
  5342. CK = CK_BooleanToSignedIntegral;
  5343. }
  5344. } else {
  5345. ExprResult CastExprRes = SplattedExpr;
  5346. CK = PrepareScalarCast(CastExprRes, DestElemTy);
  5347. if (CastExprRes.isInvalid())
  5348. return ExprError();
  5349. SplattedExpr = CastExprRes.get();
  5350. }
  5351. return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
  5352. }
  5353. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  5354. Expr *CastExpr, CastKind &Kind) {
  5355. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  5356. QualType SrcTy = CastExpr->getType();
  5357. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  5358. // an ExtVectorType.
  5359. // In OpenCL, casts between vectors of different types are not allowed.
  5360. // (See OpenCL 6.2).
  5361. if (SrcTy->isVectorType()) {
  5362. if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
  5363. (getLangOpts().OpenCL &&
  5364. !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
  5365. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  5366. << DestTy << SrcTy << R;
  5367. return ExprError();
  5368. }
  5369. Kind = CK_BitCast;
  5370. return CastExpr;
  5371. }
  5372. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  5373. // conversion will take place first from scalar to elt type, and then
  5374. // splat from elt type to vector.
  5375. if (SrcTy->isPointerType())
  5376. return Diag(R.getBegin(),
  5377. diag::err_invalid_conversion_between_vector_and_scalar)
  5378. << DestTy << SrcTy << R;
  5379. Kind = CK_VectorSplat;
  5380. return prepareVectorSplat(DestTy, CastExpr);
  5381. }
  5382. ExprResult
  5383. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  5384. Declarator &D, ParsedType &Ty,
  5385. SourceLocation RParenLoc, Expr *CastExpr) {
  5386. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  5387. "ActOnCastExpr(): missing type or expr");
  5388. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  5389. if (D.isInvalidType())
  5390. return ExprError();
  5391. if (getLangOpts().CPlusPlus) {
  5392. // Check that there are no default arguments (C++ only).
  5393. CheckExtraCXXDefaultArguments(D);
  5394. } else {
  5395. // Make sure any TypoExprs have been dealt with.
  5396. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  5397. if (!Res.isUsable())
  5398. return ExprError();
  5399. CastExpr = Res.get();
  5400. }
  5401. checkUnusedDeclAttributes(D);
  5402. QualType castType = castTInfo->getType();
  5403. Ty = CreateParsedType(castType, castTInfo);
  5404. bool isVectorLiteral = false;
  5405. // Check for an altivec or OpenCL literal,
  5406. // i.e. all the elements are integer constants.
  5407. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  5408. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  5409. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  5410. && castType->isVectorType() && (PE || PLE)) {
  5411. if (PLE && PLE->getNumExprs() == 0) {
  5412. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  5413. return ExprError();
  5414. }
  5415. if (PE || PLE->getNumExprs() == 1) {
  5416. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  5417. if (!E->getType()->isVectorType())
  5418. isVectorLiteral = true;
  5419. }
  5420. else
  5421. isVectorLiteral = true;
  5422. }
  5423. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  5424. // then handle it as such.
  5425. if (isVectorLiteral)
  5426. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  5427. // If the Expr being casted is a ParenListExpr, handle it specially.
  5428. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  5429. // sequence of BinOp comma operators.
  5430. if (isa<ParenListExpr>(CastExpr)) {
  5431. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  5432. if (Result.isInvalid()) return ExprError();
  5433. CastExpr = Result.get();
  5434. }
  5435. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  5436. !getSourceManager().isInSystemMacro(LParenLoc))
  5437. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  5438. CheckTollFreeBridgeCast(castType, CastExpr);
  5439. CheckObjCBridgeRelatedCast(castType, CastExpr);
  5440. DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
  5441. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  5442. }
  5443. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  5444. SourceLocation RParenLoc, Expr *E,
  5445. TypeSourceInfo *TInfo) {
  5446. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  5447. "Expected paren or paren list expression");
  5448. Expr **exprs;
  5449. unsigned numExprs;
  5450. Expr *subExpr;
  5451. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  5452. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  5453. LiteralLParenLoc = PE->getLParenLoc();
  5454. LiteralRParenLoc = PE->getRParenLoc();
  5455. exprs = PE->getExprs();
  5456. numExprs = PE->getNumExprs();
  5457. } else { // isa<ParenExpr> by assertion at function entrance
  5458. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  5459. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  5460. subExpr = cast<ParenExpr>(E)->getSubExpr();
  5461. exprs = &subExpr;
  5462. numExprs = 1;
  5463. }
  5464. QualType Ty = TInfo->getType();
  5465. assert(Ty->isVectorType() && "Expected vector type");
  5466. SmallVector<Expr *, 8> initExprs;
  5467. const VectorType *VTy = Ty->getAs<VectorType>();
  5468. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  5469. // '(...)' form of vector initialization in AltiVec: the number of
  5470. // initializers must be one or must match the size of the vector.
  5471. // If a single value is specified in the initializer then it will be
  5472. // replicated to all the components of the vector
  5473. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  5474. // The number of initializers must be one or must match the size of the
  5475. // vector. If a single value is specified in the initializer then it will
  5476. // be replicated to all the components of the vector
  5477. if (numExprs == 1) {
  5478. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5479. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5480. if (Literal.isInvalid())
  5481. return ExprError();
  5482. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5483. PrepareScalarCast(Literal, ElemTy));
  5484. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5485. }
  5486. else if (numExprs < numElems) {
  5487. Diag(E->getExprLoc(),
  5488. diag::err_incorrect_number_of_vector_initializers);
  5489. return ExprError();
  5490. }
  5491. else
  5492. initExprs.append(exprs, exprs + numExprs);
  5493. }
  5494. else {
  5495. // For OpenCL, when the number of initializers is a single value,
  5496. // it will be replicated to all components of the vector.
  5497. if (getLangOpts().OpenCL &&
  5498. VTy->getVectorKind() == VectorType::GenericVector &&
  5499. numExprs == 1) {
  5500. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5501. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5502. if (Literal.isInvalid())
  5503. return ExprError();
  5504. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5505. PrepareScalarCast(Literal, ElemTy));
  5506. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5507. }
  5508. initExprs.append(exprs, exprs + numExprs);
  5509. }
  5510. // FIXME: This means that pretty-printing the final AST will produce curly
  5511. // braces instead of the original commas.
  5512. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  5513. initExprs, LiteralRParenLoc);
  5514. initE->setType(Ty);
  5515. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  5516. }
  5517. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  5518. /// the ParenListExpr into a sequence of comma binary operators.
  5519. ExprResult
  5520. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  5521. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  5522. if (!E)
  5523. return OrigExpr;
  5524. ExprResult Result(E->getExpr(0));
  5525. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  5526. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  5527. E->getExpr(i));
  5528. if (Result.isInvalid()) return ExprError();
  5529. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  5530. }
  5531. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  5532. SourceLocation R,
  5533. MultiExprArg Val) {
  5534. Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
  5535. return expr;
  5536. }
  5537. /// Emit a specialized diagnostic when one expression is a null pointer
  5538. /// constant and the other is not a pointer. Returns true if a diagnostic is
  5539. /// emitted.
  5540. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  5541. SourceLocation QuestionLoc) {
  5542. Expr *NullExpr = LHSExpr;
  5543. Expr *NonPointerExpr = RHSExpr;
  5544. Expr::NullPointerConstantKind NullKind =
  5545. NullExpr->isNullPointerConstant(Context,
  5546. Expr::NPC_ValueDependentIsNotNull);
  5547. if (NullKind == Expr::NPCK_NotNull) {
  5548. NullExpr = RHSExpr;
  5549. NonPointerExpr = LHSExpr;
  5550. NullKind =
  5551. NullExpr->isNullPointerConstant(Context,
  5552. Expr::NPC_ValueDependentIsNotNull);
  5553. }
  5554. if (NullKind == Expr::NPCK_NotNull)
  5555. return false;
  5556. if (NullKind == Expr::NPCK_ZeroExpression)
  5557. return false;
  5558. if (NullKind == Expr::NPCK_ZeroLiteral) {
  5559. // In this case, check to make sure that we got here from a "NULL"
  5560. // string in the source code.
  5561. NullExpr = NullExpr->IgnoreParenImpCasts();
  5562. SourceLocation loc = NullExpr->getExprLoc();
  5563. if (!findMacroSpelling(loc, "NULL"))
  5564. return false;
  5565. }
  5566. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  5567. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  5568. << NonPointerExpr->getType() << DiagType
  5569. << NonPointerExpr->getSourceRange();
  5570. return true;
  5571. }
  5572. /// Return false if the condition expression is valid, true otherwise.
  5573. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  5574. QualType CondTy = Cond->getType();
  5575. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  5576. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  5577. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5578. << CondTy << Cond->getSourceRange();
  5579. return true;
  5580. }
  5581. // C99 6.5.15p2
  5582. if (CondTy->isScalarType()) return false;
  5583. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  5584. << CondTy << Cond->getSourceRange();
  5585. return true;
  5586. }
  5587. /// Handle when one or both operands are void type.
  5588. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  5589. ExprResult &RHS) {
  5590. Expr *LHSExpr = LHS.get();
  5591. Expr *RHSExpr = RHS.get();
  5592. if (!LHSExpr->getType()->isVoidType())
  5593. S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5594. << RHSExpr->getSourceRange();
  5595. if (!RHSExpr->getType()->isVoidType())
  5596. S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5597. << LHSExpr->getSourceRange();
  5598. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  5599. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  5600. return S.Context.VoidTy;
  5601. }
  5602. /// Return false if the NullExpr can be promoted to PointerTy,
  5603. /// true otherwise.
  5604. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  5605. QualType PointerTy) {
  5606. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  5607. !NullExpr.get()->isNullPointerConstant(S.Context,
  5608. Expr::NPC_ValueDependentIsNull))
  5609. return true;
  5610. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  5611. return false;
  5612. }
  5613. /// Checks compatibility between two pointers and return the resulting
  5614. /// type.
  5615. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  5616. ExprResult &RHS,
  5617. SourceLocation Loc) {
  5618. QualType LHSTy = LHS.get()->getType();
  5619. QualType RHSTy = RHS.get()->getType();
  5620. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  5621. // Two identical pointers types are always compatible.
  5622. return LHSTy;
  5623. }
  5624. QualType lhptee, rhptee;
  5625. // Get the pointee types.
  5626. bool IsBlockPointer = false;
  5627. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  5628. lhptee = LHSBTy->getPointeeType();
  5629. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  5630. IsBlockPointer = true;
  5631. } else {
  5632. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  5633. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  5634. }
  5635. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  5636. // differently qualified versions of compatible types, the result type is
  5637. // a pointer to an appropriately qualified version of the composite
  5638. // type.
  5639. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  5640. // clause doesn't make sense for our extensions. E.g. address space 2 should
  5641. // be incompatible with address space 3: they may live on different devices or
  5642. // anything.
  5643. Qualifiers lhQual = lhptee.getQualifiers();
  5644. Qualifiers rhQual = rhptee.getQualifiers();
  5645. LangAS ResultAddrSpace = LangAS::Default;
  5646. LangAS LAddrSpace = lhQual.getAddressSpace();
  5647. LangAS RAddrSpace = rhQual.getAddressSpace();
  5648. if (S.getLangOpts().OpenCL) {
  5649. // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
  5650. // spaces is disallowed.
  5651. if (lhQual.isAddressSpaceSupersetOf(rhQual))
  5652. ResultAddrSpace = LAddrSpace;
  5653. else if (rhQual.isAddressSpaceSupersetOf(lhQual))
  5654. ResultAddrSpace = RAddrSpace;
  5655. else {
  5656. S.Diag(Loc,
  5657. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  5658. << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
  5659. << RHS.get()->getSourceRange();
  5660. return QualType();
  5661. }
  5662. }
  5663. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  5664. auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
  5665. lhQual.removeCVRQualifiers();
  5666. rhQual.removeCVRQualifiers();
  5667. // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
  5668. // (C99 6.7.3) for address spaces. We assume that the check should behave in
  5669. // the same manner as it's defined for CVR qualifiers, so for OpenCL two
  5670. // qual types are compatible iff
  5671. // * corresponded types are compatible
  5672. // * CVR qualifiers are equal
  5673. // * address spaces are equal
  5674. // Thus for conditional operator we merge CVR and address space unqualified
  5675. // pointees and if there is a composite type we return a pointer to it with
  5676. // merged qualifiers.
  5677. if (S.getLangOpts().OpenCL) {
  5678. LHSCastKind = LAddrSpace == ResultAddrSpace
  5679. ? CK_BitCast
  5680. : CK_AddressSpaceConversion;
  5681. RHSCastKind = RAddrSpace == ResultAddrSpace
  5682. ? CK_BitCast
  5683. : CK_AddressSpaceConversion;
  5684. lhQual.removeAddressSpace();
  5685. rhQual.removeAddressSpace();
  5686. }
  5687. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  5688. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  5689. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  5690. if (CompositeTy.isNull()) {
  5691. // In this situation, we assume void* type. No especially good
  5692. // reason, but this is what gcc does, and we do have to pick
  5693. // to get a consistent AST.
  5694. QualType incompatTy;
  5695. incompatTy = S.Context.getPointerType(
  5696. S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
  5697. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
  5698. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
  5699. // FIXME: For OpenCL the warning emission and cast to void* leaves a room
  5700. // for casts between types with incompatible address space qualifiers.
  5701. // For the following code the compiler produces casts between global and
  5702. // local address spaces of the corresponded innermost pointees:
  5703. // local int *global *a;
  5704. // global int *global *b;
  5705. // a = (0 ? a : b); // see C99 6.5.16.1.p1.
  5706. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  5707. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5708. << RHS.get()->getSourceRange();
  5709. return incompatTy;
  5710. }
  5711. // The pointer types are compatible.
  5712. // In case of OpenCL ResultTy should have the address space qualifier
  5713. // which is a superset of address spaces of both the 2nd and the 3rd
  5714. // operands of the conditional operator.
  5715. QualType ResultTy = [&, ResultAddrSpace]() {
  5716. if (S.getLangOpts().OpenCL) {
  5717. Qualifiers CompositeQuals = CompositeTy.getQualifiers();
  5718. CompositeQuals.setAddressSpace(ResultAddrSpace);
  5719. return S.Context
  5720. .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
  5721. .withCVRQualifiers(MergedCVRQual);
  5722. }
  5723. return CompositeTy.withCVRQualifiers(MergedCVRQual);
  5724. }();
  5725. if (IsBlockPointer)
  5726. ResultTy = S.Context.getBlockPointerType(ResultTy);
  5727. else
  5728. ResultTy = S.Context.getPointerType(ResultTy);
  5729. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
  5730. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
  5731. return ResultTy;
  5732. }
  5733. /// Return the resulting type when the operands are both block pointers.
  5734. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  5735. ExprResult &LHS,
  5736. ExprResult &RHS,
  5737. SourceLocation Loc) {
  5738. QualType LHSTy = LHS.get()->getType();
  5739. QualType RHSTy = RHS.get()->getType();
  5740. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  5741. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  5742. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  5743. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5744. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5745. return destType;
  5746. }
  5747. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  5748. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5749. << RHS.get()->getSourceRange();
  5750. return QualType();
  5751. }
  5752. // We have 2 block pointer types.
  5753. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5754. }
  5755. /// Return the resulting type when the operands are both pointers.
  5756. static QualType
  5757. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  5758. ExprResult &RHS,
  5759. SourceLocation Loc) {
  5760. // get the pointer types
  5761. QualType LHSTy = LHS.get()->getType();
  5762. QualType RHSTy = RHS.get()->getType();
  5763. // get the "pointed to" types
  5764. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5765. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5766. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  5767. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  5768. // Figure out necessary qualifiers (C99 6.5.15p6)
  5769. QualType destPointee
  5770. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5771. QualType destType = S.Context.getPointerType(destPointee);
  5772. // Add qualifiers if necessary.
  5773. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5774. // Promote to void*.
  5775. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5776. return destType;
  5777. }
  5778. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  5779. QualType destPointee
  5780. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5781. QualType destType = S.Context.getPointerType(destPointee);
  5782. // Add qualifiers if necessary.
  5783. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5784. // Promote to void*.
  5785. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5786. return destType;
  5787. }
  5788. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5789. }
  5790. /// Return false if the first expression is not an integer and the second
  5791. /// expression is not a pointer, true otherwise.
  5792. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  5793. Expr* PointerExpr, SourceLocation Loc,
  5794. bool IsIntFirstExpr) {
  5795. if (!PointerExpr->getType()->isPointerType() ||
  5796. !Int.get()->getType()->isIntegerType())
  5797. return false;
  5798. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  5799. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  5800. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  5801. << Expr1->getType() << Expr2->getType()
  5802. << Expr1->getSourceRange() << Expr2->getSourceRange();
  5803. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  5804. CK_IntegralToPointer);
  5805. return true;
  5806. }
  5807. /// Simple conversion between integer and floating point types.
  5808. ///
  5809. /// Used when handling the OpenCL conditional operator where the
  5810. /// condition is a vector while the other operands are scalar.
  5811. ///
  5812. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  5813. /// types are either integer or floating type. Between the two
  5814. /// operands, the type with the higher rank is defined as the "result
  5815. /// type". The other operand needs to be promoted to the same type. No
  5816. /// other type promotion is allowed. We cannot use
  5817. /// UsualArithmeticConversions() for this purpose, since it always
  5818. /// promotes promotable types.
  5819. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  5820. ExprResult &RHS,
  5821. SourceLocation QuestionLoc) {
  5822. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  5823. if (LHS.isInvalid())
  5824. return QualType();
  5825. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  5826. if (RHS.isInvalid())
  5827. return QualType();
  5828. // For conversion purposes, we ignore any qualifiers.
  5829. // For example, "const float" and "float" are equivalent.
  5830. QualType LHSType =
  5831. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  5832. QualType RHSType =
  5833. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  5834. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  5835. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5836. << LHSType << LHS.get()->getSourceRange();
  5837. return QualType();
  5838. }
  5839. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  5840. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5841. << RHSType << RHS.get()->getSourceRange();
  5842. return QualType();
  5843. }
  5844. // If both types are identical, no conversion is needed.
  5845. if (LHSType == RHSType)
  5846. return LHSType;
  5847. // Now handle "real" floating types (i.e. float, double, long double).
  5848. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  5849. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  5850. /*IsCompAssign = */ false);
  5851. // Finally, we have two differing integer types.
  5852. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  5853. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  5854. }
  5855. /// Convert scalar operands to a vector that matches the
  5856. /// condition in length.
  5857. ///
  5858. /// Used when handling the OpenCL conditional operator where the
  5859. /// condition is a vector while the other operands are scalar.
  5860. ///
  5861. /// We first compute the "result type" for the scalar operands
  5862. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  5863. /// into a vector of that type where the length matches the condition
  5864. /// vector type. s6.11.6 requires that the element types of the result
  5865. /// and the condition must have the same number of bits.
  5866. static QualType
  5867. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  5868. QualType CondTy, SourceLocation QuestionLoc) {
  5869. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  5870. if (ResTy.isNull()) return QualType();
  5871. const VectorType *CV = CondTy->getAs<VectorType>();
  5872. assert(CV);
  5873. // Determine the vector result type
  5874. unsigned NumElements = CV->getNumElements();
  5875. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  5876. // Ensure that all types have the same number of bits
  5877. if (S.Context.getTypeSize(CV->getElementType())
  5878. != S.Context.getTypeSize(ResTy)) {
  5879. // Since VectorTy is created internally, it does not pretty print
  5880. // with an OpenCL name. Instead, we just print a description.
  5881. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  5882. SmallString<64> Str;
  5883. llvm::raw_svector_ostream OS(Str);
  5884. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  5885. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5886. << CondTy << OS.str();
  5887. return QualType();
  5888. }
  5889. // Convert operands to the vector result type
  5890. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  5891. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  5892. return VectorTy;
  5893. }
  5894. /// Return false if this is a valid OpenCL condition vector
  5895. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  5896. SourceLocation QuestionLoc) {
  5897. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  5898. // integral type.
  5899. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  5900. assert(CondTy);
  5901. QualType EleTy = CondTy->getElementType();
  5902. if (EleTy->isIntegerType()) return false;
  5903. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5904. << Cond->getType() << Cond->getSourceRange();
  5905. return true;
  5906. }
  5907. /// Return false if the vector condition type and the vector
  5908. /// result type are compatible.
  5909. ///
  5910. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  5911. /// number of elements, and their element types have the same number
  5912. /// of bits.
  5913. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  5914. SourceLocation QuestionLoc) {
  5915. const VectorType *CV = CondTy->getAs<VectorType>();
  5916. const VectorType *RV = VecResTy->getAs<VectorType>();
  5917. assert(CV && RV);
  5918. if (CV->getNumElements() != RV->getNumElements()) {
  5919. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  5920. << CondTy << VecResTy;
  5921. return true;
  5922. }
  5923. QualType CVE = CV->getElementType();
  5924. QualType RVE = RV->getElementType();
  5925. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  5926. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5927. << CondTy << VecResTy;
  5928. return true;
  5929. }
  5930. return false;
  5931. }
  5932. /// Return the resulting type for the conditional operator in
  5933. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  5934. /// s6.3.i) when the condition is a vector type.
  5935. static QualType
  5936. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  5937. ExprResult &LHS, ExprResult &RHS,
  5938. SourceLocation QuestionLoc) {
  5939. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  5940. if (Cond.isInvalid())
  5941. return QualType();
  5942. QualType CondTy = Cond.get()->getType();
  5943. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  5944. return QualType();
  5945. // If either operand is a vector then find the vector type of the
  5946. // result as specified in OpenCL v1.1 s6.3.i.
  5947. if (LHS.get()->getType()->isVectorType() ||
  5948. RHS.get()->getType()->isVectorType()) {
  5949. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  5950. /*isCompAssign*/false,
  5951. /*AllowBothBool*/true,
  5952. /*AllowBoolConversions*/false);
  5953. if (VecResTy.isNull()) return QualType();
  5954. // The result type must match the condition type as specified in
  5955. // OpenCL v1.1 s6.11.6.
  5956. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  5957. return QualType();
  5958. return VecResTy;
  5959. }
  5960. // Both operands are scalar.
  5961. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  5962. }
  5963. /// Return true if the Expr is block type
  5964. static bool checkBlockType(Sema &S, const Expr *E) {
  5965. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  5966. QualType Ty = CE->getCallee()->getType();
  5967. if (Ty->isBlockPointerType()) {
  5968. S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
  5969. return true;
  5970. }
  5971. }
  5972. return false;
  5973. }
  5974. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  5975. /// In that case, LHS = cond.
  5976. /// C99 6.5.15
  5977. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  5978. ExprResult &RHS, ExprValueKind &VK,
  5979. ExprObjectKind &OK,
  5980. SourceLocation QuestionLoc) {
  5981. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  5982. if (!LHSResult.isUsable()) return QualType();
  5983. LHS = LHSResult;
  5984. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  5985. if (!RHSResult.isUsable()) return QualType();
  5986. RHS = RHSResult;
  5987. // C++ is sufficiently different to merit its own checker.
  5988. if (getLangOpts().CPlusPlus)
  5989. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  5990. VK = VK_RValue;
  5991. OK = OK_Ordinary;
  5992. // The OpenCL operator with a vector condition is sufficiently
  5993. // different to merit its own checker.
  5994. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  5995. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  5996. // First, check the condition.
  5997. Cond = UsualUnaryConversions(Cond.get());
  5998. if (Cond.isInvalid())
  5999. return QualType();
  6000. if (checkCondition(*this, Cond.get(), QuestionLoc))
  6001. return QualType();
  6002. // Now check the two expressions.
  6003. if (LHS.get()->getType()->isVectorType() ||
  6004. RHS.get()->getType()->isVectorType())
  6005. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  6006. /*AllowBothBool*/true,
  6007. /*AllowBoolConversions*/false);
  6008. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  6009. if (LHS.isInvalid() || RHS.isInvalid())
  6010. return QualType();
  6011. QualType LHSTy = LHS.get()->getType();
  6012. QualType RHSTy = RHS.get()->getType();
  6013. // Diagnose attempts to convert between __float128 and long double where
  6014. // such conversions currently can't be handled.
  6015. if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
  6016. Diag(QuestionLoc,
  6017. diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
  6018. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6019. return QualType();
  6020. }
  6021. // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
  6022. // selection operator (?:).
  6023. if (getLangOpts().OpenCL &&
  6024. (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
  6025. return QualType();
  6026. }
  6027. // If both operands have arithmetic type, do the usual arithmetic conversions
  6028. // to find a common type: C99 6.5.15p3,5.
  6029. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  6030. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  6031. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  6032. return ResTy;
  6033. }
  6034. // If both operands are the same structure or union type, the result is that
  6035. // type.
  6036. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  6037. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  6038. if (LHSRT->getDecl() == RHSRT->getDecl())
  6039. // "If both the operands have structure or union type, the result has
  6040. // that type." This implies that CV qualifiers are dropped.
  6041. return LHSTy.getUnqualifiedType();
  6042. // FIXME: Type of conditional expression must be complete in C mode.
  6043. }
  6044. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  6045. // The following || allows only one side to be void (a GCC-ism).
  6046. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  6047. return checkConditionalVoidType(*this, LHS, RHS);
  6048. }
  6049. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  6050. // the type of the other operand."
  6051. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  6052. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  6053. // All objective-c pointer type analysis is done here.
  6054. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  6055. QuestionLoc);
  6056. if (LHS.isInvalid() || RHS.isInvalid())
  6057. return QualType();
  6058. if (!compositeType.isNull())
  6059. return compositeType;
  6060. // Handle block pointer types.
  6061. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  6062. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  6063. QuestionLoc);
  6064. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  6065. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  6066. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  6067. QuestionLoc);
  6068. // GCC compatibility: soften pointer/integer mismatch. Note that
  6069. // null pointers have been filtered out by this point.
  6070. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  6071. /*isIntFirstExpr=*/true))
  6072. return RHSTy;
  6073. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  6074. /*isIntFirstExpr=*/false))
  6075. return LHSTy;
  6076. // Emit a better diagnostic if one of the expressions is a null pointer
  6077. // constant and the other is not a pointer type. In this case, the user most
  6078. // likely forgot to take the address of the other expression.
  6079. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  6080. return QualType();
  6081. // Otherwise, the operands are not compatible.
  6082. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  6083. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6084. << RHS.get()->getSourceRange();
  6085. return QualType();
  6086. }
  6087. /// FindCompositeObjCPointerType - Helper method to find composite type of
  6088. /// two objective-c pointer types of the two input expressions.
  6089. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  6090. SourceLocation QuestionLoc) {
  6091. QualType LHSTy = LHS.get()->getType();
  6092. QualType RHSTy = RHS.get()->getType();
  6093. // Handle things like Class and struct objc_class*. Here we case the result
  6094. // to the pseudo-builtin, because that will be implicitly cast back to the
  6095. // redefinition type if an attempt is made to access its fields.
  6096. if (LHSTy->isObjCClassType() &&
  6097. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  6098. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6099. return LHSTy;
  6100. }
  6101. if (RHSTy->isObjCClassType() &&
  6102. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  6103. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6104. return RHSTy;
  6105. }
  6106. // And the same for struct objc_object* / id
  6107. if (LHSTy->isObjCIdType() &&
  6108. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  6109. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6110. return LHSTy;
  6111. }
  6112. if (RHSTy->isObjCIdType() &&
  6113. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  6114. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6115. return RHSTy;
  6116. }
  6117. // And the same for struct objc_selector* / SEL
  6118. if (Context.isObjCSelType(LHSTy) &&
  6119. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  6120. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  6121. return LHSTy;
  6122. }
  6123. if (Context.isObjCSelType(RHSTy) &&
  6124. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  6125. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  6126. return RHSTy;
  6127. }
  6128. // Check constraints for Objective-C object pointers types.
  6129. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  6130. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  6131. // Two identical object pointer types are always compatible.
  6132. return LHSTy;
  6133. }
  6134. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  6135. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  6136. QualType compositeType = LHSTy;
  6137. // If both operands are interfaces and either operand can be
  6138. // assigned to the other, use that type as the composite
  6139. // type. This allows
  6140. // xxx ? (A*) a : (B*) b
  6141. // where B is a subclass of A.
  6142. //
  6143. // Additionally, as for assignment, if either type is 'id'
  6144. // allow silent coercion. Finally, if the types are
  6145. // incompatible then make sure to use 'id' as the composite
  6146. // type so the result is acceptable for sending messages to.
  6147. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  6148. // It could return the composite type.
  6149. if (!(compositeType =
  6150. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  6151. // Nothing more to do.
  6152. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  6153. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  6154. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  6155. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  6156. } else if ((LHSTy->isObjCQualifiedIdType() ||
  6157. RHSTy->isObjCQualifiedIdType()) &&
  6158. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  6159. // Need to handle "id<xx>" explicitly.
  6160. // GCC allows qualified id and any Objective-C type to devolve to
  6161. // id. Currently localizing to here until clear this should be
  6162. // part of ObjCQualifiedIdTypesAreCompatible.
  6163. compositeType = Context.getObjCIdType();
  6164. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  6165. compositeType = Context.getObjCIdType();
  6166. } else {
  6167. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  6168. << LHSTy << RHSTy
  6169. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6170. QualType incompatTy = Context.getObjCIdType();
  6171. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  6172. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  6173. return incompatTy;
  6174. }
  6175. // The object pointer types are compatible.
  6176. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  6177. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  6178. return compositeType;
  6179. }
  6180. // Check Objective-C object pointer types and 'void *'
  6181. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  6182. if (getLangOpts().ObjCAutoRefCount) {
  6183. // ARC forbids the implicit conversion of object pointers to 'void *',
  6184. // so these types are not compatible.
  6185. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6186. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6187. LHS = RHS = true;
  6188. return QualType();
  6189. }
  6190. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  6191. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6192. QualType destPointee
  6193. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  6194. QualType destType = Context.getPointerType(destPointee);
  6195. // Add qualifiers if necessary.
  6196. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  6197. // Promote to void*.
  6198. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6199. return destType;
  6200. }
  6201. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  6202. if (getLangOpts().ObjCAutoRefCount) {
  6203. // ARC forbids the implicit conversion of object pointers to 'void *',
  6204. // so these types are not compatible.
  6205. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6206. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6207. LHS = RHS = true;
  6208. return QualType();
  6209. }
  6210. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6211. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  6212. QualType destPointee
  6213. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  6214. QualType destType = Context.getPointerType(destPointee);
  6215. // Add qualifiers if necessary.
  6216. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  6217. // Promote to void*.
  6218. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6219. return destType;
  6220. }
  6221. return QualType();
  6222. }
  6223. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  6224. /// ParenRange in parentheses.
  6225. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  6226. const PartialDiagnostic &Note,
  6227. SourceRange ParenRange) {
  6228. SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
  6229. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  6230. EndLoc.isValid()) {
  6231. Self.Diag(Loc, Note)
  6232. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  6233. << FixItHint::CreateInsertion(EndLoc, ")");
  6234. } else {
  6235. // We can't display the parentheses, so just show the bare note.
  6236. Self.Diag(Loc, Note) << ParenRange;
  6237. }
  6238. }
  6239. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  6240. return BinaryOperator::isAdditiveOp(Opc) ||
  6241. BinaryOperator::isMultiplicativeOp(Opc) ||
  6242. BinaryOperator::isShiftOp(Opc);
  6243. }
  6244. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  6245. /// expression, either using a built-in or overloaded operator,
  6246. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  6247. /// expression.
  6248. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  6249. Expr **RHSExprs) {
  6250. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  6251. E = E->IgnoreImpCasts();
  6252. E = E->IgnoreConversionOperator();
  6253. E = E->IgnoreImpCasts();
  6254. // Built-in binary operator.
  6255. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  6256. if (IsArithmeticOp(OP->getOpcode())) {
  6257. *Opcode = OP->getOpcode();
  6258. *RHSExprs = OP->getRHS();
  6259. return true;
  6260. }
  6261. }
  6262. // Overloaded operator.
  6263. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  6264. if (Call->getNumArgs() != 2)
  6265. return false;
  6266. // Make sure this is really a binary operator that is safe to pass into
  6267. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  6268. OverloadedOperatorKind OO = Call->getOperator();
  6269. if (OO < OO_Plus || OO > OO_Arrow ||
  6270. OO == OO_PlusPlus || OO == OO_MinusMinus)
  6271. return false;
  6272. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  6273. if (IsArithmeticOp(OpKind)) {
  6274. *Opcode = OpKind;
  6275. *RHSExprs = Call->getArg(1);
  6276. return true;
  6277. }
  6278. }
  6279. return false;
  6280. }
  6281. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  6282. /// or is a logical expression such as (x==y) which has int type, but is
  6283. /// commonly interpreted as boolean.
  6284. static bool ExprLooksBoolean(Expr *E) {
  6285. E = E->IgnoreParenImpCasts();
  6286. if (E->getType()->isBooleanType())
  6287. return true;
  6288. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  6289. return OP->isComparisonOp() || OP->isLogicalOp();
  6290. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  6291. return OP->getOpcode() == UO_LNot;
  6292. if (E->getType()->isPointerType())
  6293. return true;
  6294. return false;
  6295. }
  6296. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  6297. /// and binary operator are mixed in a way that suggests the programmer assumed
  6298. /// the conditional operator has higher precedence, for example:
  6299. /// "int x = a + someBinaryCondition ? 1 : 2".
  6300. static void DiagnoseConditionalPrecedence(Sema &Self,
  6301. SourceLocation OpLoc,
  6302. Expr *Condition,
  6303. Expr *LHSExpr,
  6304. Expr *RHSExpr) {
  6305. BinaryOperatorKind CondOpcode;
  6306. Expr *CondRHS;
  6307. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  6308. return;
  6309. if (!ExprLooksBoolean(CondRHS))
  6310. return;
  6311. // The condition is an arithmetic binary expression, with a right-
  6312. // hand side that looks boolean, so warn.
  6313. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  6314. << Condition->getSourceRange()
  6315. << BinaryOperator::getOpcodeStr(CondOpcode);
  6316. SuggestParentheses(Self, OpLoc,
  6317. Self.PDiag(diag::note_precedence_silence)
  6318. << BinaryOperator::getOpcodeStr(CondOpcode),
  6319. SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
  6320. SuggestParentheses(Self, OpLoc,
  6321. Self.PDiag(diag::note_precedence_conditional_first),
  6322. SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
  6323. }
  6324. /// Compute the nullability of a conditional expression.
  6325. static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
  6326. QualType LHSTy, QualType RHSTy,
  6327. ASTContext &Ctx) {
  6328. if (!ResTy->isAnyPointerType())
  6329. return ResTy;
  6330. auto GetNullability = [&Ctx](QualType Ty) {
  6331. Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
  6332. if (Kind)
  6333. return *Kind;
  6334. return NullabilityKind::Unspecified;
  6335. };
  6336. auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
  6337. NullabilityKind MergedKind;
  6338. // Compute nullability of a binary conditional expression.
  6339. if (IsBin) {
  6340. if (LHSKind == NullabilityKind::NonNull)
  6341. MergedKind = NullabilityKind::NonNull;
  6342. else
  6343. MergedKind = RHSKind;
  6344. // Compute nullability of a normal conditional expression.
  6345. } else {
  6346. if (LHSKind == NullabilityKind::Nullable ||
  6347. RHSKind == NullabilityKind::Nullable)
  6348. MergedKind = NullabilityKind::Nullable;
  6349. else if (LHSKind == NullabilityKind::NonNull)
  6350. MergedKind = RHSKind;
  6351. else if (RHSKind == NullabilityKind::NonNull)
  6352. MergedKind = LHSKind;
  6353. else
  6354. MergedKind = NullabilityKind::Unspecified;
  6355. }
  6356. // Return if ResTy already has the correct nullability.
  6357. if (GetNullability(ResTy) == MergedKind)
  6358. return ResTy;
  6359. // Strip all nullability from ResTy.
  6360. while (ResTy->getNullability(Ctx))
  6361. ResTy = ResTy.getSingleStepDesugaredType(Ctx);
  6362. // Create a new AttributedType with the new nullability kind.
  6363. auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
  6364. return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
  6365. }
  6366. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  6367. /// in the case of a the GNU conditional expr extension.
  6368. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  6369. SourceLocation ColonLoc,
  6370. Expr *CondExpr, Expr *LHSExpr,
  6371. Expr *RHSExpr) {
  6372. if (!getLangOpts().CPlusPlus) {
  6373. // C cannot handle TypoExpr nodes in the condition because it
  6374. // doesn't handle dependent types properly, so make sure any TypoExprs have
  6375. // been dealt with before checking the operands.
  6376. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  6377. ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
  6378. ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
  6379. if (!CondResult.isUsable())
  6380. return ExprError();
  6381. if (LHSExpr) {
  6382. if (!LHSResult.isUsable())
  6383. return ExprError();
  6384. }
  6385. if (!RHSResult.isUsable())
  6386. return ExprError();
  6387. CondExpr = CondResult.get();
  6388. LHSExpr = LHSResult.get();
  6389. RHSExpr = RHSResult.get();
  6390. }
  6391. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  6392. // was the condition.
  6393. OpaqueValueExpr *opaqueValue = nullptr;
  6394. Expr *commonExpr = nullptr;
  6395. if (!LHSExpr) {
  6396. commonExpr = CondExpr;
  6397. // Lower out placeholder types first. This is important so that we don't
  6398. // try to capture a placeholder. This happens in few cases in C++; such
  6399. // as Objective-C++'s dictionary subscripting syntax.
  6400. if (commonExpr->hasPlaceholderType()) {
  6401. ExprResult result = CheckPlaceholderExpr(commonExpr);
  6402. if (!result.isUsable()) return ExprError();
  6403. commonExpr = result.get();
  6404. }
  6405. // We usually want to apply unary conversions *before* saving, except
  6406. // in the special case of a C++ l-value conditional.
  6407. if (!(getLangOpts().CPlusPlus
  6408. && !commonExpr->isTypeDependent()
  6409. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  6410. && commonExpr->isGLValue()
  6411. && commonExpr->isOrdinaryOrBitFieldObject()
  6412. && RHSExpr->isOrdinaryOrBitFieldObject()
  6413. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  6414. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  6415. if (commonRes.isInvalid())
  6416. return ExprError();
  6417. commonExpr = commonRes.get();
  6418. }
  6419. // If the common expression is a class or array prvalue, materialize it
  6420. // so that we can safely refer to it multiple times.
  6421. if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
  6422. commonExpr->getType()->isArrayType())) {
  6423. ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
  6424. if (MatExpr.isInvalid())
  6425. return ExprError();
  6426. commonExpr = MatExpr.get();
  6427. }
  6428. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  6429. commonExpr->getType(),
  6430. commonExpr->getValueKind(),
  6431. commonExpr->getObjectKind(),
  6432. commonExpr);
  6433. LHSExpr = CondExpr = opaqueValue;
  6434. }
  6435. QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
  6436. ExprValueKind VK = VK_RValue;
  6437. ExprObjectKind OK = OK_Ordinary;
  6438. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  6439. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  6440. VK, OK, QuestionLoc);
  6441. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  6442. RHS.isInvalid())
  6443. return ExprError();
  6444. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  6445. RHS.get());
  6446. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  6447. result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
  6448. Context);
  6449. if (!commonExpr)
  6450. return new (Context)
  6451. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  6452. RHS.get(), result, VK, OK);
  6453. return new (Context) BinaryConditionalOperator(
  6454. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  6455. ColonLoc, result, VK, OK);
  6456. }
  6457. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  6458. // being closely modeled after the C99 spec:-). The odd characteristic of this
  6459. // routine is it effectively iqnores the qualifiers on the top level pointee.
  6460. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  6461. // FIXME: add a couple examples in this comment.
  6462. static Sema::AssignConvertType
  6463. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  6464. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6465. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6466. // get the "pointed to" type (ignoring qualifiers at the top level)
  6467. const Type *lhptee, *rhptee;
  6468. Qualifiers lhq, rhq;
  6469. std::tie(lhptee, lhq) =
  6470. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  6471. std::tie(rhptee, rhq) =
  6472. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  6473. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6474. // C99 6.5.16.1p1: This following citation is common to constraints
  6475. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  6476. // qualifiers of the type *pointed to* by the right;
  6477. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  6478. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  6479. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  6480. // Ignore lifetime for further calculation.
  6481. lhq.removeObjCLifetime();
  6482. rhq.removeObjCLifetime();
  6483. }
  6484. if (!lhq.compatiblyIncludes(rhq)) {
  6485. // Treat address-space mismatches as fatal. TODO: address subspaces
  6486. if (!lhq.isAddressSpaceSupersetOf(rhq))
  6487. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  6488. // It's okay to add or remove GC or lifetime qualifiers when converting to
  6489. // and from void*.
  6490. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  6491. .compatiblyIncludes(
  6492. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  6493. && (lhptee->isVoidType() || rhptee->isVoidType()))
  6494. ; // keep old
  6495. // Treat lifetime mismatches as fatal.
  6496. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  6497. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  6498. // For GCC/MS compatibility, other qualifier mismatches are treated
  6499. // as still compatible in C.
  6500. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6501. }
  6502. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  6503. // incomplete type and the other is a pointer to a qualified or unqualified
  6504. // version of void...
  6505. if (lhptee->isVoidType()) {
  6506. if (rhptee->isIncompleteOrObjectType())
  6507. return ConvTy;
  6508. // As an extension, we allow cast to/from void* to function pointer.
  6509. assert(rhptee->isFunctionType());
  6510. return Sema::FunctionVoidPointer;
  6511. }
  6512. if (rhptee->isVoidType()) {
  6513. if (lhptee->isIncompleteOrObjectType())
  6514. return ConvTy;
  6515. // As an extension, we allow cast to/from void* to function pointer.
  6516. assert(lhptee->isFunctionType());
  6517. return Sema::FunctionVoidPointer;
  6518. }
  6519. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  6520. // unqualified versions of compatible types, ...
  6521. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  6522. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  6523. // Check if the pointee types are compatible ignoring the sign.
  6524. // We explicitly check for char so that we catch "char" vs
  6525. // "unsigned char" on systems where "char" is unsigned.
  6526. if (lhptee->isCharType())
  6527. ltrans = S.Context.UnsignedCharTy;
  6528. else if (lhptee->hasSignedIntegerRepresentation())
  6529. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  6530. if (rhptee->isCharType())
  6531. rtrans = S.Context.UnsignedCharTy;
  6532. else if (rhptee->hasSignedIntegerRepresentation())
  6533. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  6534. if (ltrans == rtrans) {
  6535. // Types are compatible ignoring the sign. Qualifier incompatibility
  6536. // takes priority over sign incompatibility because the sign
  6537. // warning can be disabled.
  6538. if (ConvTy != Sema::Compatible)
  6539. return ConvTy;
  6540. return Sema::IncompatiblePointerSign;
  6541. }
  6542. // If we are a multi-level pointer, it's possible that our issue is simply
  6543. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  6544. // the eventual target type is the same and the pointers have the same
  6545. // level of indirection, this must be the issue.
  6546. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  6547. do {
  6548. lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
  6549. rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
  6550. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  6551. if (lhptee == rhptee)
  6552. return Sema::IncompatibleNestedPointerQualifiers;
  6553. }
  6554. // General pointer incompatibility takes priority over qualifiers.
  6555. return Sema::IncompatiblePointer;
  6556. }
  6557. if (!S.getLangOpts().CPlusPlus &&
  6558. S.IsFunctionConversion(ltrans, rtrans, ltrans))
  6559. return Sema::IncompatiblePointer;
  6560. return ConvTy;
  6561. }
  6562. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  6563. /// block pointer types are compatible or whether a block and normal pointer
  6564. /// are compatible. It is more restrict than comparing two function pointer
  6565. // types.
  6566. static Sema::AssignConvertType
  6567. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  6568. QualType RHSType) {
  6569. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6570. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6571. QualType lhptee, rhptee;
  6572. // get the "pointed to" type (ignoring qualifiers at the top level)
  6573. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  6574. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  6575. // In C++, the types have to match exactly.
  6576. if (S.getLangOpts().CPlusPlus)
  6577. return Sema::IncompatibleBlockPointer;
  6578. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6579. // For blocks we enforce that qualifiers are identical.
  6580. Qualifiers LQuals = lhptee.getLocalQualifiers();
  6581. Qualifiers RQuals = rhptee.getLocalQualifiers();
  6582. if (S.getLangOpts().OpenCL) {
  6583. LQuals.removeAddressSpace();
  6584. RQuals.removeAddressSpace();
  6585. }
  6586. if (LQuals != RQuals)
  6587. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6588. // FIXME: OpenCL doesn't define the exact compile time semantics for a block
  6589. // assignment.
  6590. // The current behavior is similar to C++ lambdas. A block might be
  6591. // assigned to a variable iff its return type and parameters are compatible
  6592. // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
  6593. // an assignment. Presumably it should behave in way that a function pointer
  6594. // assignment does in C, so for each parameter and return type:
  6595. // * CVR and address space of LHS should be a superset of CVR and address
  6596. // space of RHS.
  6597. // * unqualified types should be compatible.
  6598. if (S.getLangOpts().OpenCL) {
  6599. if (!S.Context.typesAreBlockPointerCompatible(
  6600. S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
  6601. S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
  6602. return Sema::IncompatibleBlockPointer;
  6603. } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  6604. return Sema::IncompatibleBlockPointer;
  6605. return ConvTy;
  6606. }
  6607. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  6608. /// for assignment compatibility.
  6609. static Sema::AssignConvertType
  6610. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  6611. QualType RHSType) {
  6612. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  6613. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  6614. if (LHSType->isObjCBuiltinType()) {
  6615. // Class is not compatible with ObjC object pointers.
  6616. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  6617. !RHSType->isObjCQualifiedClassType())
  6618. return Sema::IncompatiblePointer;
  6619. return Sema::Compatible;
  6620. }
  6621. if (RHSType->isObjCBuiltinType()) {
  6622. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  6623. !LHSType->isObjCQualifiedClassType())
  6624. return Sema::IncompatiblePointer;
  6625. return Sema::Compatible;
  6626. }
  6627. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6628. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6629. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  6630. // make an exception for id<P>
  6631. !LHSType->isObjCQualifiedIdType())
  6632. return Sema::CompatiblePointerDiscardsQualifiers;
  6633. if (S.Context.typesAreCompatible(LHSType, RHSType))
  6634. return Sema::Compatible;
  6635. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  6636. return Sema::IncompatibleObjCQualifiedId;
  6637. return Sema::IncompatiblePointer;
  6638. }
  6639. Sema::AssignConvertType
  6640. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  6641. QualType LHSType, QualType RHSType) {
  6642. // Fake up an opaque expression. We don't actually care about what
  6643. // cast operations are required, so if CheckAssignmentConstraints
  6644. // adds casts to this they'll be wasted, but fortunately that doesn't
  6645. // usually happen on valid code.
  6646. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  6647. ExprResult RHSPtr = &RHSExpr;
  6648. CastKind K;
  6649. return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
  6650. }
  6651. /// This helper function returns true if QT is a vector type that has element
  6652. /// type ElementType.
  6653. static bool isVector(QualType QT, QualType ElementType) {
  6654. if (const VectorType *VT = QT->getAs<VectorType>())
  6655. return VT->getElementType() == ElementType;
  6656. return false;
  6657. }
  6658. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  6659. /// has code to accommodate several GCC extensions when type checking
  6660. /// pointers. Here are some objectionable examples that GCC considers warnings:
  6661. ///
  6662. /// int a, *pint;
  6663. /// short *pshort;
  6664. /// struct foo *pfoo;
  6665. ///
  6666. /// pint = pshort; // warning: assignment from incompatible pointer type
  6667. /// a = pint; // warning: assignment makes integer from pointer without a cast
  6668. /// pint = a; // warning: assignment makes pointer from integer without a cast
  6669. /// pint = pfoo; // warning: assignment from incompatible pointer type
  6670. ///
  6671. /// As a result, the code for dealing with pointers is more complex than the
  6672. /// C99 spec dictates.
  6673. ///
  6674. /// Sets 'Kind' for any result kind except Incompatible.
  6675. Sema::AssignConvertType
  6676. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6677. CastKind &Kind, bool ConvertRHS) {
  6678. QualType RHSType = RHS.get()->getType();
  6679. QualType OrigLHSType = LHSType;
  6680. // Get canonical types. We're not formatting these types, just comparing
  6681. // them.
  6682. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  6683. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  6684. // Common case: no conversion required.
  6685. if (LHSType == RHSType) {
  6686. Kind = CK_NoOp;
  6687. return Compatible;
  6688. }
  6689. // If we have an atomic type, try a non-atomic assignment, then just add an
  6690. // atomic qualification step.
  6691. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  6692. Sema::AssignConvertType result =
  6693. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  6694. if (result != Compatible)
  6695. return result;
  6696. if (Kind != CK_NoOp && ConvertRHS)
  6697. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  6698. Kind = CK_NonAtomicToAtomic;
  6699. return Compatible;
  6700. }
  6701. // If the left-hand side is a reference type, then we are in a
  6702. // (rare!) case where we've allowed the use of references in C,
  6703. // e.g., as a parameter type in a built-in function. In this case,
  6704. // just make sure that the type referenced is compatible with the
  6705. // right-hand side type. The caller is responsible for adjusting
  6706. // LHSType so that the resulting expression does not have reference
  6707. // type.
  6708. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  6709. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  6710. Kind = CK_LValueBitCast;
  6711. return Compatible;
  6712. }
  6713. return Incompatible;
  6714. }
  6715. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  6716. // to the same ExtVector type.
  6717. if (LHSType->isExtVectorType()) {
  6718. if (RHSType->isExtVectorType())
  6719. return Incompatible;
  6720. if (RHSType->isArithmeticType()) {
  6721. // CK_VectorSplat does T -> vector T, so first cast to the element type.
  6722. if (ConvertRHS)
  6723. RHS = prepareVectorSplat(LHSType, RHS.get());
  6724. Kind = CK_VectorSplat;
  6725. return Compatible;
  6726. }
  6727. }
  6728. // Conversions to or from vector type.
  6729. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  6730. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  6731. // Allow assignments of an AltiVec vector type to an equivalent GCC
  6732. // vector type and vice versa
  6733. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6734. Kind = CK_BitCast;
  6735. return Compatible;
  6736. }
  6737. // If we are allowing lax vector conversions, and LHS and RHS are both
  6738. // vectors, the total size only needs to be the same. This is a bitcast;
  6739. // no bits are changed but the result type is different.
  6740. if (isLaxVectorConversion(RHSType, LHSType)) {
  6741. Kind = CK_BitCast;
  6742. return IncompatibleVectors;
  6743. }
  6744. }
  6745. // When the RHS comes from another lax conversion (e.g. binops between
  6746. // scalars and vectors) the result is canonicalized as a vector. When the
  6747. // LHS is also a vector, the lax is allowed by the condition above. Handle
  6748. // the case where LHS is a scalar.
  6749. if (LHSType->isScalarType()) {
  6750. const VectorType *VecType = RHSType->getAs<VectorType>();
  6751. if (VecType && VecType->getNumElements() == 1 &&
  6752. isLaxVectorConversion(RHSType, LHSType)) {
  6753. ExprResult *VecExpr = &RHS;
  6754. *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
  6755. Kind = CK_BitCast;
  6756. return Compatible;
  6757. }
  6758. }
  6759. return Incompatible;
  6760. }
  6761. // Diagnose attempts to convert between __float128 and long double where
  6762. // such conversions currently can't be handled.
  6763. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  6764. return Incompatible;
  6765. // Disallow assigning a _Complex to a real type in C++ mode since it simply
  6766. // discards the imaginary part.
  6767. if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
  6768. !LHSType->getAs<ComplexType>())
  6769. return Incompatible;
  6770. // Arithmetic conversions.
  6771. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  6772. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  6773. if (ConvertRHS)
  6774. Kind = PrepareScalarCast(RHS, LHSType);
  6775. return Compatible;
  6776. }
  6777. // Conversions to normal pointers.
  6778. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  6779. // U* -> T*
  6780. if (isa<PointerType>(RHSType)) {
  6781. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  6782. LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  6783. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6784. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  6785. }
  6786. // int -> T*
  6787. if (RHSType->isIntegerType()) {
  6788. Kind = CK_IntegralToPointer; // FIXME: null?
  6789. return IntToPointer;
  6790. }
  6791. // C pointers are not compatible with ObjC object pointers,
  6792. // with two exceptions:
  6793. if (isa<ObjCObjectPointerType>(RHSType)) {
  6794. // - conversions to void*
  6795. if (LHSPointer->getPointeeType()->isVoidType()) {
  6796. Kind = CK_BitCast;
  6797. return Compatible;
  6798. }
  6799. // - conversions from 'Class' to the redefinition type
  6800. if (RHSType->isObjCClassType() &&
  6801. Context.hasSameType(LHSType,
  6802. Context.getObjCClassRedefinitionType())) {
  6803. Kind = CK_BitCast;
  6804. return Compatible;
  6805. }
  6806. Kind = CK_BitCast;
  6807. return IncompatiblePointer;
  6808. }
  6809. // U^ -> void*
  6810. if (RHSType->getAs<BlockPointerType>()) {
  6811. if (LHSPointer->getPointeeType()->isVoidType()) {
  6812. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  6813. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  6814. ->getPointeeType()
  6815. .getAddressSpace();
  6816. Kind =
  6817. AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6818. return Compatible;
  6819. }
  6820. }
  6821. return Incompatible;
  6822. }
  6823. // Conversions to block pointers.
  6824. if (isa<BlockPointerType>(LHSType)) {
  6825. // U^ -> T^
  6826. if (RHSType->isBlockPointerType()) {
  6827. LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
  6828. ->getPointeeType()
  6829. .getAddressSpace();
  6830. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  6831. ->getPointeeType()
  6832. .getAddressSpace();
  6833. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6834. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  6835. }
  6836. // int or null -> T^
  6837. if (RHSType->isIntegerType()) {
  6838. Kind = CK_IntegralToPointer; // FIXME: null
  6839. return IntToBlockPointer;
  6840. }
  6841. // id -> T^
  6842. if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
  6843. Kind = CK_AnyPointerToBlockPointerCast;
  6844. return Compatible;
  6845. }
  6846. // void* -> T^
  6847. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  6848. if (RHSPT->getPointeeType()->isVoidType()) {
  6849. Kind = CK_AnyPointerToBlockPointerCast;
  6850. return Compatible;
  6851. }
  6852. return Incompatible;
  6853. }
  6854. // Conversions to Objective-C pointers.
  6855. if (isa<ObjCObjectPointerType>(LHSType)) {
  6856. // A* -> B*
  6857. if (RHSType->isObjCObjectPointerType()) {
  6858. Kind = CK_BitCast;
  6859. Sema::AssignConvertType result =
  6860. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  6861. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  6862. result == Compatible &&
  6863. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  6864. result = IncompatibleObjCWeakRef;
  6865. return result;
  6866. }
  6867. // int or null -> A*
  6868. if (RHSType->isIntegerType()) {
  6869. Kind = CK_IntegralToPointer; // FIXME: null
  6870. return IntToPointer;
  6871. }
  6872. // In general, C pointers are not compatible with ObjC object pointers,
  6873. // with two exceptions:
  6874. if (isa<PointerType>(RHSType)) {
  6875. Kind = CK_CPointerToObjCPointerCast;
  6876. // - conversions from 'void*'
  6877. if (RHSType->isVoidPointerType()) {
  6878. return Compatible;
  6879. }
  6880. // - conversions to 'Class' from its redefinition type
  6881. if (LHSType->isObjCClassType() &&
  6882. Context.hasSameType(RHSType,
  6883. Context.getObjCClassRedefinitionType())) {
  6884. return Compatible;
  6885. }
  6886. return IncompatiblePointer;
  6887. }
  6888. // Only under strict condition T^ is compatible with an Objective-C pointer.
  6889. if (RHSType->isBlockPointerType() &&
  6890. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  6891. if (ConvertRHS)
  6892. maybeExtendBlockObject(RHS);
  6893. Kind = CK_BlockPointerToObjCPointerCast;
  6894. return Compatible;
  6895. }
  6896. return Incompatible;
  6897. }
  6898. // Conversions from pointers that are not covered by the above.
  6899. if (isa<PointerType>(RHSType)) {
  6900. // T* -> _Bool
  6901. if (LHSType == Context.BoolTy) {
  6902. Kind = CK_PointerToBoolean;
  6903. return Compatible;
  6904. }
  6905. // T* -> int
  6906. if (LHSType->isIntegerType()) {
  6907. Kind = CK_PointerToIntegral;
  6908. return PointerToInt;
  6909. }
  6910. return Incompatible;
  6911. }
  6912. // Conversions from Objective-C pointers that are not covered by the above.
  6913. if (isa<ObjCObjectPointerType>(RHSType)) {
  6914. // T* -> _Bool
  6915. if (LHSType == Context.BoolTy) {
  6916. Kind = CK_PointerToBoolean;
  6917. return Compatible;
  6918. }
  6919. // T* -> int
  6920. if (LHSType->isIntegerType()) {
  6921. Kind = CK_PointerToIntegral;
  6922. return PointerToInt;
  6923. }
  6924. return Incompatible;
  6925. }
  6926. // struct A -> struct B
  6927. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  6928. if (Context.typesAreCompatible(LHSType, RHSType)) {
  6929. Kind = CK_NoOp;
  6930. return Compatible;
  6931. }
  6932. }
  6933. if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
  6934. Kind = CK_IntToOCLSampler;
  6935. return Compatible;
  6936. }
  6937. return Incompatible;
  6938. }
  6939. /// Constructs a transparent union from an expression that is
  6940. /// used to initialize the transparent union.
  6941. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  6942. ExprResult &EResult, QualType UnionType,
  6943. FieldDecl *Field) {
  6944. // Build an initializer list that designates the appropriate member
  6945. // of the transparent union.
  6946. Expr *E = EResult.get();
  6947. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  6948. E, SourceLocation());
  6949. Initializer->setType(UnionType);
  6950. Initializer->setInitializedFieldInUnion(Field);
  6951. // Build a compound literal constructing a value of the transparent
  6952. // union type from this initializer list.
  6953. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  6954. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  6955. VK_RValue, Initializer, false);
  6956. }
  6957. Sema::AssignConvertType
  6958. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  6959. ExprResult &RHS) {
  6960. QualType RHSType = RHS.get()->getType();
  6961. // If the ArgType is a Union type, we want to handle a potential
  6962. // transparent_union GCC extension.
  6963. const RecordType *UT = ArgType->getAsUnionType();
  6964. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  6965. return Incompatible;
  6966. // The field to initialize within the transparent union.
  6967. RecordDecl *UD = UT->getDecl();
  6968. FieldDecl *InitField = nullptr;
  6969. // It's compatible if the expression matches any of the fields.
  6970. for (auto *it : UD->fields()) {
  6971. if (it->getType()->isPointerType()) {
  6972. // If the transparent union contains a pointer type, we allow:
  6973. // 1) void pointer
  6974. // 2) null pointer constant
  6975. if (RHSType->isPointerType())
  6976. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  6977. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  6978. InitField = it;
  6979. break;
  6980. }
  6981. if (RHS.get()->isNullPointerConstant(Context,
  6982. Expr::NPC_ValueDependentIsNull)) {
  6983. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  6984. CK_NullToPointer);
  6985. InitField = it;
  6986. break;
  6987. }
  6988. }
  6989. CastKind Kind;
  6990. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  6991. == Compatible) {
  6992. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  6993. InitField = it;
  6994. break;
  6995. }
  6996. }
  6997. if (!InitField)
  6998. return Incompatible;
  6999. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  7000. return Compatible;
  7001. }
  7002. Sema::AssignConvertType
  7003. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
  7004. bool Diagnose,
  7005. bool DiagnoseCFAudited,
  7006. bool ConvertRHS) {
  7007. // We need to be able to tell the caller whether we diagnosed a problem, if
  7008. // they ask us to issue diagnostics.
  7009. assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
  7010. // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
  7011. // we can't avoid *all* modifications at the moment, so we need some somewhere
  7012. // to put the updated value.
  7013. ExprResult LocalRHS = CallerRHS;
  7014. ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
  7015. if (getLangOpts().CPlusPlus) {
  7016. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  7017. // C++ 5.17p3: If the left operand is not of class type, the
  7018. // expression is implicitly converted (C++ 4) to the
  7019. // cv-unqualified type of the left operand.
  7020. QualType RHSType = RHS.get()->getType();
  7021. if (Diagnose) {
  7022. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7023. AA_Assigning);
  7024. } else {
  7025. ImplicitConversionSequence ICS =
  7026. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7027. /*SuppressUserConversions=*/false,
  7028. /*AllowExplicit=*/false,
  7029. /*InOverloadResolution=*/false,
  7030. /*CStyle=*/false,
  7031. /*AllowObjCWritebackConversion=*/false);
  7032. if (ICS.isFailure())
  7033. return Incompatible;
  7034. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7035. ICS, AA_Assigning);
  7036. }
  7037. if (RHS.isInvalid())
  7038. return Incompatible;
  7039. Sema::AssignConvertType result = Compatible;
  7040. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7041. !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
  7042. result = IncompatibleObjCWeakRef;
  7043. return result;
  7044. }
  7045. // FIXME: Currently, we fall through and treat C++ classes like C
  7046. // structures.
  7047. // FIXME: We also fall through for atomics; not sure what should
  7048. // happen there, though.
  7049. } else if (RHS.get()->getType() == Context.OverloadTy) {
  7050. // As a set of extensions to C, we support overloading on functions. These
  7051. // functions need to be resolved here.
  7052. DeclAccessPair DAP;
  7053. if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
  7054. RHS.get(), LHSType, /*Complain=*/false, DAP))
  7055. RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
  7056. else
  7057. return Incompatible;
  7058. }
  7059. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  7060. // a null pointer constant.
  7061. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  7062. LHSType->isBlockPointerType()) &&
  7063. RHS.get()->isNullPointerConstant(Context,
  7064. Expr::NPC_ValueDependentIsNull)) {
  7065. if (Diagnose || ConvertRHS) {
  7066. CastKind Kind;
  7067. CXXCastPath Path;
  7068. CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
  7069. /*IgnoreBaseAccess=*/false, Diagnose);
  7070. if (ConvertRHS)
  7071. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  7072. }
  7073. return Compatible;
  7074. }
  7075. // This check seems unnatural, however it is necessary to ensure the proper
  7076. // conversion of functions/arrays. If the conversion were done for all
  7077. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  7078. // expressions that suppress this implicit conversion (&, sizeof).
  7079. //
  7080. // Suppress this for references: C++ 8.5.3p5.
  7081. if (!LHSType->isReferenceType()) {
  7082. // FIXME: We potentially allocate here even if ConvertRHS is false.
  7083. RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
  7084. if (RHS.isInvalid())
  7085. return Incompatible;
  7086. }
  7087. Expr *PRE = RHS.get()->IgnoreParenCasts();
  7088. if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
  7089. ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
  7090. if (PDecl && !PDecl->hasDefinition()) {
  7091. Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl;
  7092. Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
  7093. }
  7094. }
  7095. CastKind Kind;
  7096. Sema::AssignConvertType result =
  7097. CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
  7098. // C99 6.5.16.1p2: The value of the right operand is converted to the
  7099. // type of the assignment expression.
  7100. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  7101. // so that we can use references in built-in functions even in C.
  7102. // The getNonReferenceType() call makes sure that the resulting expression
  7103. // does not have reference type.
  7104. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  7105. QualType Ty = LHSType.getNonLValueExprType(Context);
  7106. Expr *E = RHS.get();
  7107. // Check for various Objective-C errors. If we are not reporting
  7108. // diagnostics and just checking for errors, e.g., during overload
  7109. // resolution, return Incompatible to indicate the failure.
  7110. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7111. CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  7112. Diagnose, DiagnoseCFAudited) != ACR_okay) {
  7113. if (!Diagnose)
  7114. return Incompatible;
  7115. }
  7116. if (getLangOpts().ObjC1 &&
  7117. (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
  7118. E->getType(), E, Diagnose) ||
  7119. ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
  7120. if (!Diagnose)
  7121. return Incompatible;
  7122. // Replace the expression with a corrected version and continue so we
  7123. // can find further errors.
  7124. RHS = E;
  7125. return Compatible;
  7126. }
  7127. if (ConvertRHS)
  7128. RHS = ImpCastExprToType(E, Ty, Kind);
  7129. }
  7130. return result;
  7131. }
  7132. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  7133. ExprResult &RHS) {
  7134. Diag(Loc, diag::err_typecheck_invalid_operands)
  7135. << LHS.get()->getType() << RHS.get()->getType()
  7136. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7137. return QualType();
  7138. }
  7139. // Diagnose cases where a scalar was implicitly converted to a vector and
  7140. // diagnose the underlying types. Otherwise, diagnose the error
  7141. // as invalid vector logical operands for non-C++ cases.
  7142. QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
  7143. ExprResult &RHS) {
  7144. QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
  7145. QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
  7146. bool LHSNatVec = LHSType->isVectorType();
  7147. bool RHSNatVec = RHSType->isVectorType();
  7148. if (!(LHSNatVec && RHSNatVec)) {
  7149. Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
  7150. Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
  7151. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7152. << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
  7153. << Vector->getSourceRange();
  7154. return QualType();
  7155. }
  7156. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7157. << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
  7158. << RHS.get()->getSourceRange();
  7159. return QualType();
  7160. }
  7161. /// Try to convert a value of non-vector type to a vector type by converting
  7162. /// the type to the element type of the vector and then performing a splat.
  7163. /// If the language is OpenCL, we only use conversions that promote scalar
  7164. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  7165. /// for float->int.
  7166. ///
  7167. /// OpenCL V2.0 6.2.6.p2:
  7168. /// An error shall occur if any scalar operand type has greater rank
  7169. /// than the type of the vector element.
  7170. ///
  7171. /// \param scalar - if non-null, actually perform the conversions
  7172. /// \return true if the operation fails (but without diagnosing the failure)
  7173. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  7174. QualType scalarTy,
  7175. QualType vectorEltTy,
  7176. QualType vectorTy,
  7177. unsigned &DiagID) {
  7178. // The conversion to apply to the scalar before splatting it,
  7179. // if necessary.
  7180. CastKind scalarCast = CK_NoOp;
  7181. if (vectorEltTy->isIntegralType(S.Context)) {
  7182. if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
  7183. (scalarTy->isIntegerType() &&
  7184. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
  7185. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7186. return true;
  7187. }
  7188. if (!scalarTy->isIntegralType(S.Context))
  7189. return true;
  7190. scalarCast = CK_IntegralCast;
  7191. } else if (vectorEltTy->isRealFloatingType()) {
  7192. if (scalarTy->isRealFloatingType()) {
  7193. if (S.getLangOpts().OpenCL &&
  7194. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
  7195. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7196. return true;
  7197. }
  7198. scalarCast = CK_FloatingCast;
  7199. }
  7200. else if (scalarTy->isIntegralType(S.Context))
  7201. scalarCast = CK_IntegralToFloating;
  7202. else
  7203. return true;
  7204. } else {
  7205. return true;
  7206. }
  7207. // Adjust scalar if desired.
  7208. if (scalar) {
  7209. if (scalarCast != CK_NoOp)
  7210. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  7211. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  7212. }
  7213. return false;
  7214. }
  7215. /// Convert vector E to a vector with the same number of elements but different
  7216. /// element type.
  7217. static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
  7218. const auto *VecTy = E->getType()->getAs<VectorType>();
  7219. assert(VecTy && "Expression E must be a vector");
  7220. QualType NewVecTy = S.Context.getVectorType(ElementType,
  7221. VecTy->getNumElements(),
  7222. VecTy->getVectorKind());
  7223. // Look through the implicit cast. Return the subexpression if its type is
  7224. // NewVecTy.
  7225. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  7226. if (ICE->getSubExpr()->getType() == NewVecTy)
  7227. return ICE->getSubExpr();
  7228. auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
  7229. return S.ImpCastExprToType(E, NewVecTy, Cast);
  7230. }
  7231. /// Test if a (constant) integer Int can be casted to another integer type
  7232. /// IntTy without losing precision.
  7233. static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
  7234. QualType OtherIntTy) {
  7235. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7236. // Reject cases where the value of the Int is unknown as that would
  7237. // possibly cause truncation, but accept cases where the scalar can be
  7238. // demoted without loss of precision.
  7239. llvm::APSInt Result;
  7240. bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
  7241. int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
  7242. bool IntSigned = IntTy->hasSignedIntegerRepresentation();
  7243. bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
  7244. if (CstInt) {
  7245. // If the scalar is constant and is of a higher order and has more active
  7246. // bits that the vector element type, reject it.
  7247. unsigned NumBits = IntSigned
  7248. ? (Result.isNegative() ? Result.getMinSignedBits()
  7249. : Result.getActiveBits())
  7250. : Result.getActiveBits();
  7251. if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
  7252. return true;
  7253. // If the signedness of the scalar type and the vector element type
  7254. // differs and the number of bits is greater than that of the vector
  7255. // element reject it.
  7256. return (IntSigned != OtherIntSigned &&
  7257. NumBits > S.Context.getIntWidth(OtherIntTy));
  7258. }
  7259. // Reject cases where the value of the scalar is not constant and it's
  7260. // order is greater than that of the vector element type.
  7261. return (Order < 0);
  7262. }
  7263. /// Test if a (constant) integer Int can be casted to floating point type
  7264. /// FloatTy without losing precision.
  7265. static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
  7266. QualType FloatTy) {
  7267. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7268. // Determine if the integer constant can be expressed as a floating point
  7269. // number of the appropriate type.
  7270. llvm::APSInt Result;
  7271. bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
  7272. uint64_t Bits = 0;
  7273. if (CstInt) {
  7274. // Reject constants that would be truncated if they were converted to
  7275. // the floating point type. Test by simple to/from conversion.
  7276. // FIXME: Ideally the conversion to an APFloat and from an APFloat
  7277. // could be avoided if there was a convertFromAPInt method
  7278. // which could signal back if implicit truncation occurred.
  7279. llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
  7280. Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
  7281. llvm::APFloat::rmTowardZero);
  7282. llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
  7283. !IntTy->hasSignedIntegerRepresentation());
  7284. bool Ignored = false;
  7285. Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
  7286. &Ignored);
  7287. if (Result != ConvertBack)
  7288. return true;
  7289. } else {
  7290. // Reject types that cannot be fully encoded into the mantissa of
  7291. // the float.
  7292. Bits = S.Context.getTypeSize(IntTy);
  7293. unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
  7294. S.Context.getFloatTypeSemantics(FloatTy));
  7295. if (Bits > FloatPrec)
  7296. return true;
  7297. }
  7298. return false;
  7299. }
  7300. /// Attempt to convert and splat Scalar into a vector whose types matches
  7301. /// Vector following GCC conversion rules. The rule is that implicit
  7302. /// conversion can occur when Scalar can be casted to match Vector's element
  7303. /// type without causing truncation of Scalar.
  7304. static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
  7305. ExprResult *Vector) {
  7306. QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
  7307. QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
  7308. const VectorType *VT = VectorTy->getAs<VectorType>();
  7309. assert(!isa<ExtVectorType>(VT) &&
  7310. "ExtVectorTypes should not be handled here!");
  7311. QualType VectorEltTy = VT->getElementType();
  7312. // Reject cases where the vector element type or the scalar element type are
  7313. // not integral or floating point types.
  7314. if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
  7315. return true;
  7316. // The conversion to apply to the scalar before splatting it,
  7317. // if necessary.
  7318. CastKind ScalarCast = CK_NoOp;
  7319. // Accept cases where the vector elements are integers and the scalar is
  7320. // an integer.
  7321. // FIXME: Notionally if the scalar was a floating point value with a precise
  7322. // integral representation, we could cast it to an appropriate integer
  7323. // type and then perform the rest of the checks here. GCC will perform
  7324. // this conversion in some cases as determined by the input language.
  7325. // We should accept it on a language independent basis.
  7326. if (VectorEltTy->isIntegralType(S.Context) &&
  7327. ScalarTy->isIntegralType(S.Context) &&
  7328. S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
  7329. if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
  7330. return true;
  7331. ScalarCast = CK_IntegralCast;
  7332. } else if (VectorEltTy->isRealFloatingType()) {
  7333. if (ScalarTy->isRealFloatingType()) {
  7334. // Reject cases where the scalar type is not a constant and has a higher
  7335. // Order than the vector element type.
  7336. llvm::APFloat Result(0.0);
  7337. bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
  7338. int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
  7339. if (!CstScalar && Order < 0)
  7340. return true;
  7341. // If the scalar cannot be safely casted to the vector element type,
  7342. // reject it.
  7343. if (CstScalar) {
  7344. bool Truncated = false;
  7345. Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
  7346. llvm::APFloat::rmNearestTiesToEven, &Truncated);
  7347. if (Truncated)
  7348. return true;
  7349. }
  7350. ScalarCast = CK_FloatingCast;
  7351. } else if (ScalarTy->isIntegralType(S.Context)) {
  7352. if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
  7353. return true;
  7354. ScalarCast = CK_IntegralToFloating;
  7355. } else
  7356. return true;
  7357. }
  7358. // Adjust scalar if desired.
  7359. if (Scalar) {
  7360. if (ScalarCast != CK_NoOp)
  7361. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
  7362. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
  7363. }
  7364. return false;
  7365. }
  7366. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  7367. SourceLocation Loc, bool IsCompAssign,
  7368. bool AllowBothBool,
  7369. bool AllowBoolConversions) {
  7370. if (!IsCompAssign) {
  7371. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  7372. if (LHS.isInvalid())
  7373. return QualType();
  7374. }
  7375. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  7376. if (RHS.isInvalid())
  7377. return QualType();
  7378. // For conversion purposes, we ignore any qualifiers.
  7379. // For example, "const float" and "float" are equivalent.
  7380. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  7381. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  7382. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  7383. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  7384. assert(LHSVecType || RHSVecType);
  7385. // AltiVec-style "vector bool op vector bool" combinations are allowed
  7386. // for some operators but not others.
  7387. if (!AllowBothBool &&
  7388. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7389. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7390. return InvalidOperands(Loc, LHS, RHS);
  7391. // If the vector types are identical, return.
  7392. if (Context.hasSameType(LHSType, RHSType))
  7393. return LHSType;
  7394. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  7395. if (LHSVecType && RHSVecType &&
  7396. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7397. if (isa<ExtVectorType>(LHSVecType)) {
  7398. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7399. return LHSType;
  7400. }
  7401. if (!IsCompAssign)
  7402. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7403. return RHSType;
  7404. }
  7405. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  7406. // can be mixed, with the result being the non-bool type. The non-bool
  7407. // operand must have integer element type.
  7408. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  7409. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  7410. (Context.getTypeSize(LHSVecType->getElementType()) ==
  7411. Context.getTypeSize(RHSVecType->getElementType()))) {
  7412. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7413. LHSVecType->getElementType()->isIntegerType() &&
  7414. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  7415. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7416. return LHSType;
  7417. }
  7418. if (!IsCompAssign &&
  7419. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7420. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7421. RHSVecType->getElementType()->isIntegerType()) {
  7422. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7423. return RHSType;
  7424. }
  7425. }
  7426. // If there's a vector type and a scalar, try to convert the scalar to
  7427. // the vector element type and splat.
  7428. unsigned DiagID = diag::err_typecheck_vector_not_convertable;
  7429. if (!RHSVecType) {
  7430. if (isa<ExtVectorType>(LHSVecType)) {
  7431. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  7432. LHSVecType->getElementType(), LHSType,
  7433. DiagID))
  7434. return LHSType;
  7435. } else {
  7436. if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
  7437. return LHSType;
  7438. }
  7439. }
  7440. if (!LHSVecType) {
  7441. if (isa<ExtVectorType>(RHSVecType)) {
  7442. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  7443. LHSType, RHSVecType->getElementType(),
  7444. RHSType, DiagID))
  7445. return RHSType;
  7446. } else {
  7447. if (LHS.get()->getValueKind() == VK_LValue ||
  7448. !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
  7449. return RHSType;
  7450. }
  7451. }
  7452. // FIXME: The code below also handles conversion between vectors and
  7453. // non-scalars, we should break this down into fine grained specific checks
  7454. // and emit proper diagnostics.
  7455. QualType VecType = LHSVecType ? LHSType : RHSType;
  7456. const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
  7457. QualType OtherType = LHSVecType ? RHSType : LHSType;
  7458. ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
  7459. if (isLaxVectorConversion(OtherType, VecType)) {
  7460. // If we're allowing lax vector conversions, only the total (data) size
  7461. // needs to be the same. For non compound assignment, if one of the types is
  7462. // scalar, the result is always the vector type.
  7463. if (!IsCompAssign) {
  7464. *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
  7465. return VecType;
  7466. // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
  7467. // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
  7468. // type. Note that this is already done by non-compound assignments in
  7469. // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
  7470. // <1 x T> -> T. The result is also a vector type.
  7471. } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
  7472. (OtherType->isScalarType() && VT->getNumElements() == 1)) {
  7473. ExprResult *RHSExpr = &RHS;
  7474. *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
  7475. return VecType;
  7476. }
  7477. }
  7478. // Okay, the expression is invalid.
  7479. // If there's a non-vector, non-real operand, diagnose that.
  7480. if ((!RHSVecType && !RHSType->isRealType()) ||
  7481. (!LHSVecType && !LHSType->isRealType())) {
  7482. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  7483. << LHSType << RHSType
  7484. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7485. return QualType();
  7486. }
  7487. // OpenCL V1.1 6.2.6.p1:
  7488. // If the operands are of more than one vector type, then an error shall
  7489. // occur. Implicit conversions between vector types are not permitted, per
  7490. // section 6.2.1.
  7491. if (getLangOpts().OpenCL &&
  7492. RHSVecType && isa<ExtVectorType>(RHSVecType) &&
  7493. LHSVecType && isa<ExtVectorType>(LHSVecType)) {
  7494. Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
  7495. << RHSType;
  7496. return QualType();
  7497. }
  7498. // If there is a vector type that is not a ExtVector and a scalar, we reach
  7499. // this point if scalar could not be converted to the vector's element type
  7500. // without truncation.
  7501. if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
  7502. (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
  7503. QualType Scalar = LHSVecType ? RHSType : LHSType;
  7504. QualType Vector = LHSVecType ? LHSType : RHSType;
  7505. unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
  7506. Diag(Loc,
  7507. diag::err_typecheck_vector_not_convertable_implict_truncation)
  7508. << ScalarOrVector << Scalar << Vector;
  7509. return QualType();
  7510. }
  7511. // Otherwise, use the generic diagnostic.
  7512. Diag(Loc, DiagID)
  7513. << LHSType << RHSType
  7514. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7515. return QualType();
  7516. }
  7517. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  7518. // expression. These are mainly cases where the null pointer is used as an
  7519. // integer instead of a pointer.
  7520. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  7521. SourceLocation Loc, bool IsCompare) {
  7522. // The canonical way to check for a GNU null is with isNullPointerConstant,
  7523. // but we use a bit of a hack here for speed; this is a relatively
  7524. // hot path, and isNullPointerConstant is slow.
  7525. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  7526. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  7527. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  7528. // Avoid analyzing cases where the result will either be invalid (and
  7529. // diagnosed as such) or entirely valid and not something to warn about.
  7530. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  7531. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  7532. return;
  7533. // Comparison operations would not make sense with a null pointer no matter
  7534. // what the other expression is.
  7535. if (!IsCompare) {
  7536. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  7537. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  7538. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  7539. return;
  7540. }
  7541. // The rest of the operations only make sense with a null pointer
  7542. // if the other expression is a pointer.
  7543. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  7544. NonNullType->canDecayToPointerType())
  7545. return;
  7546. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  7547. << LHSNull /* LHS is NULL */ << NonNullType
  7548. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7549. }
  7550. static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
  7551. ExprResult &RHS,
  7552. SourceLocation Loc, bool IsDiv) {
  7553. // Check for division/remainder by zero.
  7554. llvm::APSInt RHSValue;
  7555. if (!RHS.get()->isValueDependent() &&
  7556. RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
  7557. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7558. S.PDiag(diag::warn_remainder_division_by_zero)
  7559. << IsDiv << RHS.get()->getSourceRange());
  7560. }
  7561. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  7562. SourceLocation Loc,
  7563. bool IsCompAssign, bool IsDiv) {
  7564. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7565. if (LHS.get()->getType()->isVectorType() ||
  7566. RHS.get()->getType()->isVectorType())
  7567. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7568. /*AllowBothBool*/getLangOpts().AltiVec,
  7569. /*AllowBoolConversions*/false);
  7570. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  7571. if (LHS.isInvalid() || RHS.isInvalid())
  7572. return QualType();
  7573. if (compType.isNull() || !compType->isArithmeticType())
  7574. return InvalidOperands(Loc, LHS, RHS);
  7575. if (IsDiv)
  7576. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
  7577. return compType;
  7578. }
  7579. QualType Sema::CheckRemainderOperands(
  7580. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  7581. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7582. if (LHS.get()->getType()->isVectorType() ||
  7583. RHS.get()->getType()->isVectorType()) {
  7584. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  7585. RHS.get()->getType()->hasIntegerRepresentation())
  7586. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7587. /*AllowBothBool*/getLangOpts().AltiVec,
  7588. /*AllowBoolConversions*/false);
  7589. return InvalidOperands(Loc, LHS, RHS);
  7590. }
  7591. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  7592. if (LHS.isInvalid() || RHS.isInvalid())
  7593. return QualType();
  7594. if (compType.isNull() || !compType->isIntegerType())
  7595. return InvalidOperands(Loc, LHS, RHS);
  7596. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
  7597. return compType;
  7598. }
  7599. /// Diagnose invalid arithmetic on two void pointers.
  7600. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  7601. Expr *LHSExpr, Expr *RHSExpr) {
  7602. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7603. ? diag::err_typecheck_pointer_arith_void_type
  7604. : diag::ext_gnu_void_ptr)
  7605. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  7606. << RHSExpr->getSourceRange();
  7607. }
  7608. /// Diagnose invalid arithmetic on a void pointer.
  7609. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  7610. Expr *Pointer) {
  7611. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7612. ? diag::err_typecheck_pointer_arith_void_type
  7613. : diag::ext_gnu_void_ptr)
  7614. << 0 /* one pointer */ << Pointer->getSourceRange();
  7615. }
  7616. /// Diagnose invalid arithmetic on a null pointer.
  7617. ///
  7618. /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
  7619. /// idiom, which we recognize as a GNU extension.
  7620. ///
  7621. static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
  7622. Expr *Pointer, bool IsGNUIdiom) {
  7623. if (IsGNUIdiom)
  7624. S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
  7625. << Pointer->getSourceRange();
  7626. else
  7627. S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
  7628. << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
  7629. }
  7630. /// Diagnose invalid arithmetic on two function pointers.
  7631. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  7632. Expr *LHS, Expr *RHS) {
  7633. assert(LHS->getType()->isAnyPointerType());
  7634. assert(RHS->getType()->isAnyPointerType());
  7635. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7636. ? diag::err_typecheck_pointer_arith_function_type
  7637. : diag::ext_gnu_ptr_func_arith)
  7638. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  7639. // We only show the second type if it differs from the first.
  7640. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  7641. RHS->getType())
  7642. << RHS->getType()->getPointeeType()
  7643. << LHS->getSourceRange() << RHS->getSourceRange();
  7644. }
  7645. /// Diagnose invalid arithmetic on a function pointer.
  7646. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  7647. Expr *Pointer) {
  7648. assert(Pointer->getType()->isAnyPointerType());
  7649. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7650. ? diag::err_typecheck_pointer_arith_function_type
  7651. : diag::ext_gnu_ptr_func_arith)
  7652. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  7653. << 0 /* one pointer, so only one type */
  7654. << Pointer->getSourceRange();
  7655. }
  7656. /// Emit error if Operand is incomplete pointer type
  7657. ///
  7658. /// \returns True if pointer has incomplete type
  7659. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  7660. Expr *Operand) {
  7661. QualType ResType = Operand->getType();
  7662. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  7663. ResType = ResAtomicType->getValueType();
  7664. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  7665. QualType PointeeTy = ResType->getPointeeType();
  7666. return S.RequireCompleteType(Loc, PointeeTy,
  7667. diag::err_typecheck_arithmetic_incomplete_type,
  7668. PointeeTy, Operand->getSourceRange());
  7669. }
  7670. /// Check the validity of an arithmetic pointer operand.
  7671. ///
  7672. /// If the operand has pointer type, this code will check for pointer types
  7673. /// which are invalid in arithmetic operations. These will be diagnosed
  7674. /// appropriately, including whether or not the use is supported as an
  7675. /// extension.
  7676. ///
  7677. /// \returns True when the operand is valid to use (even if as an extension).
  7678. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  7679. Expr *Operand) {
  7680. QualType ResType = Operand->getType();
  7681. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  7682. ResType = ResAtomicType->getValueType();
  7683. if (!ResType->isAnyPointerType()) return true;
  7684. QualType PointeeTy = ResType->getPointeeType();
  7685. if (PointeeTy->isVoidType()) {
  7686. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  7687. return !S.getLangOpts().CPlusPlus;
  7688. }
  7689. if (PointeeTy->isFunctionType()) {
  7690. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  7691. return !S.getLangOpts().CPlusPlus;
  7692. }
  7693. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  7694. return true;
  7695. }
  7696. /// Check the validity of a binary arithmetic operation w.r.t. pointer
  7697. /// operands.
  7698. ///
  7699. /// This routine will diagnose any invalid arithmetic on pointer operands much
  7700. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  7701. /// for emitting a single diagnostic even for operations where both LHS and RHS
  7702. /// are (potentially problematic) pointers.
  7703. ///
  7704. /// \returns True when the operand is valid to use (even if as an extension).
  7705. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  7706. Expr *LHSExpr, Expr *RHSExpr) {
  7707. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  7708. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  7709. if (!isLHSPointer && !isRHSPointer) return true;
  7710. QualType LHSPointeeTy, RHSPointeeTy;
  7711. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  7712. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  7713. // if both are pointers check if operation is valid wrt address spaces
  7714. if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
  7715. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  7716. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  7717. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  7718. S.Diag(Loc,
  7719. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  7720. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  7721. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  7722. return false;
  7723. }
  7724. }
  7725. // Check for arithmetic on pointers to incomplete types.
  7726. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  7727. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  7728. if (isLHSVoidPtr || isRHSVoidPtr) {
  7729. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  7730. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  7731. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  7732. return !S.getLangOpts().CPlusPlus;
  7733. }
  7734. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  7735. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  7736. if (isLHSFuncPtr || isRHSFuncPtr) {
  7737. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  7738. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  7739. RHSExpr);
  7740. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  7741. return !S.getLangOpts().CPlusPlus;
  7742. }
  7743. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  7744. return false;
  7745. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  7746. return false;
  7747. return true;
  7748. }
  7749. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  7750. /// literal.
  7751. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  7752. Expr *LHSExpr, Expr *RHSExpr) {
  7753. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  7754. Expr* IndexExpr = RHSExpr;
  7755. if (!StrExpr) {
  7756. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  7757. IndexExpr = LHSExpr;
  7758. }
  7759. bool IsStringPlusInt = StrExpr &&
  7760. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  7761. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  7762. return;
  7763. llvm::APSInt index;
  7764. if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
  7765. unsigned StrLenWithNull = StrExpr->getLength() + 1;
  7766. if (index.isNonNegative() &&
  7767. index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
  7768. index.isUnsigned()))
  7769. return;
  7770. }
  7771. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  7772. Self.Diag(OpLoc, diag::warn_string_plus_int)
  7773. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  7774. // Only print a fixit for "str" + int, not for int + "str".
  7775. if (IndexExpr == RHSExpr) {
  7776. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
  7777. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  7778. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  7779. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  7780. << FixItHint::CreateInsertion(EndLoc, "]");
  7781. } else
  7782. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  7783. }
  7784. /// Emit a warning when adding a char literal to a string.
  7785. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  7786. Expr *LHSExpr, Expr *RHSExpr) {
  7787. const Expr *StringRefExpr = LHSExpr;
  7788. const CharacterLiteral *CharExpr =
  7789. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  7790. if (!CharExpr) {
  7791. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  7792. StringRefExpr = RHSExpr;
  7793. }
  7794. if (!CharExpr || !StringRefExpr)
  7795. return;
  7796. const QualType StringType = StringRefExpr->getType();
  7797. // Return if not a PointerType.
  7798. if (!StringType->isAnyPointerType())
  7799. return;
  7800. // Return if not a CharacterType.
  7801. if (!StringType->getPointeeType()->isAnyCharacterType())
  7802. return;
  7803. ASTContext &Ctx = Self.getASTContext();
  7804. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  7805. const QualType CharType = CharExpr->getType();
  7806. if (!CharType->isAnyCharacterType() &&
  7807. CharType->isIntegerType() &&
  7808. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  7809. Self.Diag(OpLoc, diag::warn_string_plus_char)
  7810. << DiagRange << Ctx.CharTy;
  7811. } else {
  7812. Self.Diag(OpLoc, diag::warn_string_plus_char)
  7813. << DiagRange << CharExpr->getType();
  7814. }
  7815. // Only print a fixit for str + char, not for char + str.
  7816. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  7817. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
  7818. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  7819. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  7820. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  7821. << FixItHint::CreateInsertion(EndLoc, "]");
  7822. } else {
  7823. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  7824. }
  7825. }
  7826. /// Emit error when two pointers are incompatible.
  7827. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  7828. Expr *LHSExpr, Expr *RHSExpr) {
  7829. assert(LHSExpr->getType()->isAnyPointerType());
  7830. assert(RHSExpr->getType()->isAnyPointerType());
  7831. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  7832. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  7833. << RHSExpr->getSourceRange();
  7834. }
  7835. // C99 6.5.6
  7836. QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
  7837. SourceLocation Loc, BinaryOperatorKind Opc,
  7838. QualType* CompLHSTy) {
  7839. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7840. if (LHS.get()->getType()->isVectorType() ||
  7841. RHS.get()->getType()->isVectorType()) {
  7842. QualType compType = CheckVectorOperands(
  7843. LHS, RHS, Loc, CompLHSTy,
  7844. /*AllowBothBool*/getLangOpts().AltiVec,
  7845. /*AllowBoolConversions*/getLangOpts().ZVector);
  7846. if (CompLHSTy) *CompLHSTy = compType;
  7847. return compType;
  7848. }
  7849. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  7850. if (LHS.isInvalid() || RHS.isInvalid())
  7851. return QualType();
  7852. // Diagnose "string literal" '+' int and string '+' "char literal".
  7853. if (Opc == BO_Add) {
  7854. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  7855. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  7856. }
  7857. // handle the common case first (both operands are arithmetic).
  7858. if (!compType.isNull() && compType->isArithmeticType()) {
  7859. if (CompLHSTy) *CompLHSTy = compType;
  7860. return compType;
  7861. }
  7862. // Type-checking. Ultimately the pointer's going to be in PExp;
  7863. // note that we bias towards the LHS being the pointer.
  7864. Expr *PExp = LHS.get(), *IExp = RHS.get();
  7865. bool isObjCPointer;
  7866. if (PExp->getType()->isPointerType()) {
  7867. isObjCPointer = false;
  7868. } else if (PExp->getType()->isObjCObjectPointerType()) {
  7869. isObjCPointer = true;
  7870. } else {
  7871. std::swap(PExp, IExp);
  7872. if (PExp->getType()->isPointerType()) {
  7873. isObjCPointer = false;
  7874. } else if (PExp->getType()->isObjCObjectPointerType()) {
  7875. isObjCPointer = true;
  7876. } else {
  7877. return InvalidOperands(Loc, LHS, RHS);
  7878. }
  7879. }
  7880. assert(PExp->getType()->isAnyPointerType());
  7881. if (!IExp->getType()->isIntegerType())
  7882. return InvalidOperands(Loc, LHS, RHS);
  7883. // Adding to a null pointer results in undefined behavior.
  7884. if (PExp->IgnoreParenCasts()->isNullPointerConstant(
  7885. Context, Expr::NPC_ValueDependentIsNotNull)) {
  7886. // In C++ adding zero to a null pointer is defined.
  7887. llvm::APSInt KnownVal;
  7888. if (!getLangOpts().CPlusPlus ||
  7889. (!IExp->isValueDependent() &&
  7890. (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
  7891. // Check the conditions to see if this is the 'p = nullptr + n' idiom.
  7892. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
  7893. Context, BO_Add, PExp, IExp);
  7894. diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
  7895. }
  7896. }
  7897. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  7898. return QualType();
  7899. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  7900. return QualType();
  7901. // Check array bounds for pointer arithemtic
  7902. CheckArrayAccess(PExp, IExp);
  7903. if (CompLHSTy) {
  7904. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  7905. if (LHSTy.isNull()) {
  7906. LHSTy = LHS.get()->getType();
  7907. if (LHSTy->isPromotableIntegerType())
  7908. LHSTy = Context.getPromotedIntegerType(LHSTy);
  7909. }
  7910. *CompLHSTy = LHSTy;
  7911. }
  7912. return PExp->getType();
  7913. }
  7914. // C99 6.5.6
  7915. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  7916. SourceLocation Loc,
  7917. QualType* CompLHSTy) {
  7918. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7919. if (LHS.get()->getType()->isVectorType() ||
  7920. RHS.get()->getType()->isVectorType()) {
  7921. QualType compType = CheckVectorOperands(
  7922. LHS, RHS, Loc, CompLHSTy,
  7923. /*AllowBothBool*/getLangOpts().AltiVec,
  7924. /*AllowBoolConversions*/getLangOpts().ZVector);
  7925. if (CompLHSTy) *CompLHSTy = compType;
  7926. return compType;
  7927. }
  7928. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  7929. if (LHS.isInvalid() || RHS.isInvalid())
  7930. return QualType();
  7931. // Enforce type constraints: C99 6.5.6p3.
  7932. // Handle the common case first (both operands are arithmetic).
  7933. if (!compType.isNull() && compType->isArithmeticType()) {
  7934. if (CompLHSTy) *CompLHSTy = compType;
  7935. return compType;
  7936. }
  7937. // Either ptr - int or ptr - ptr.
  7938. if (LHS.get()->getType()->isAnyPointerType()) {
  7939. QualType lpointee = LHS.get()->getType()->getPointeeType();
  7940. // Diagnose bad cases where we step over interface counts.
  7941. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  7942. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  7943. return QualType();
  7944. // The result type of a pointer-int computation is the pointer type.
  7945. if (RHS.get()->getType()->isIntegerType()) {
  7946. // Subtracting from a null pointer should produce a warning.
  7947. // The last argument to the diagnose call says this doesn't match the
  7948. // GNU int-to-pointer idiom.
  7949. if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
  7950. Expr::NPC_ValueDependentIsNotNull)) {
  7951. // In C++ adding zero to a null pointer is defined.
  7952. llvm::APSInt KnownVal;
  7953. if (!getLangOpts().CPlusPlus ||
  7954. (!RHS.get()->isValueDependent() &&
  7955. (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
  7956. diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
  7957. }
  7958. }
  7959. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  7960. return QualType();
  7961. // Check array bounds for pointer arithemtic
  7962. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  7963. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  7964. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  7965. return LHS.get()->getType();
  7966. }
  7967. // Handle pointer-pointer subtractions.
  7968. if (const PointerType *RHSPTy
  7969. = RHS.get()->getType()->getAs<PointerType>()) {
  7970. QualType rpointee = RHSPTy->getPointeeType();
  7971. if (getLangOpts().CPlusPlus) {
  7972. // Pointee types must be the same: C++ [expr.add]
  7973. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  7974. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  7975. }
  7976. } else {
  7977. // Pointee types must be compatible C99 6.5.6p3
  7978. if (!Context.typesAreCompatible(
  7979. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  7980. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  7981. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  7982. return QualType();
  7983. }
  7984. }
  7985. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  7986. LHS.get(), RHS.get()))
  7987. return QualType();
  7988. // FIXME: Add warnings for nullptr - ptr.
  7989. // The pointee type may have zero size. As an extension, a structure or
  7990. // union may have zero size or an array may have zero length. In this
  7991. // case subtraction does not make sense.
  7992. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  7993. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  7994. if (ElementSize.isZero()) {
  7995. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  7996. << rpointee.getUnqualifiedType()
  7997. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7998. }
  7999. }
  8000. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8001. return Context.getPointerDiffType();
  8002. }
  8003. }
  8004. return InvalidOperands(Loc, LHS, RHS);
  8005. }
  8006. static bool isScopedEnumerationType(QualType T) {
  8007. if (const EnumType *ET = T->getAs<EnumType>())
  8008. return ET->getDecl()->isScoped();
  8009. return false;
  8010. }
  8011. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  8012. SourceLocation Loc, BinaryOperatorKind Opc,
  8013. QualType LHSType) {
  8014. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  8015. // so skip remaining warnings as we don't want to modify values within Sema.
  8016. if (S.getLangOpts().OpenCL)
  8017. return;
  8018. llvm::APSInt Right;
  8019. // Check right/shifter operand
  8020. if (RHS.get()->isValueDependent() ||
  8021. !RHS.get()->EvaluateAsInt(Right, S.Context))
  8022. return;
  8023. if (Right.isNegative()) {
  8024. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8025. S.PDiag(diag::warn_shift_negative)
  8026. << RHS.get()->getSourceRange());
  8027. return;
  8028. }
  8029. llvm::APInt LeftBits(Right.getBitWidth(),
  8030. S.Context.getTypeSize(LHS.get()->getType()));
  8031. if (Right.uge(LeftBits)) {
  8032. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8033. S.PDiag(diag::warn_shift_gt_typewidth)
  8034. << RHS.get()->getSourceRange());
  8035. return;
  8036. }
  8037. if (Opc != BO_Shl)
  8038. return;
  8039. // When left shifting an ICE which is signed, we can check for overflow which
  8040. // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
  8041. // integers have defined behavior modulo one more than the maximum value
  8042. // representable in the result type, so never warn for those.
  8043. llvm::APSInt Left;
  8044. if (LHS.get()->isValueDependent() ||
  8045. LHSType->hasUnsignedIntegerRepresentation() ||
  8046. !LHS.get()->EvaluateAsInt(Left, S.Context))
  8047. return;
  8048. // If LHS does not have a signed type and non-negative value
  8049. // then, the behavior is undefined. Warn about it.
  8050. if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
  8051. S.DiagRuntimeBehavior(Loc, LHS.get(),
  8052. S.PDiag(diag::warn_shift_lhs_negative)
  8053. << LHS.get()->getSourceRange());
  8054. return;
  8055. }
  8056. llvm::APInt ResultBits =
  8057. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  8058. if (LeftBits.uge(ResultBits))
  8059. return;
  8060. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  8061. Result = Result.shl(Right);
  8062. // Print the bit representation of the signed integer as an unsigned
  8063. // hexadecimal number.
  8064. SmallString<40> HexResult;
  8065. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  8066. // If we are only missing a sign bit, this is less likely to result in actual
  8067. // bugs -- if the result is cast back to an unsigned type, it will have the
  8068. // expected value. Thus we place this behind a different warning that can be
  8069. // turned off separately if needed.
  8070. if (LeftBits == ResultBits - 1) {
  8071. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  8072. << HexResult << LHSType
  8073. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8074. return;
  8075. }
  8076. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  8077. << HexResult.str() << Result.getMinSignedBits() << LHSType
  8078. << Left.getBitWidth() << LHS.get()->getSourceRange()
  8079. << RHS.get()->getSourceRange();
  8080. }
  8081. /// Return the resulting type when a vector is shifted
  8082. /// by a scalar or vector shift amount.
  8083. static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8084. SourceLocation Loc, bool IsCompAssign) {
  8085. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  8086. if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
  8087. !LHS.get()->getType()->isVectorType()) {
  8088. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  8089. << RHS.get()->getType() << LHS.get()->getType()
  8090. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8091. return QualType();
  8092. }
  8093. if (!IsCompAssign) {
  8094. LHS = S.UsualUnaryConversions(LHS.get());
  8095. if (LHS.isInvalid()) return QualType();
  8096. }
  8097. RHS = S.UsualUnaryConversions(RHS.get());
  8098. if (RHS.isInvalid()) return QualType();
  8099. QualType LHSType = LHS.get()->getType();
  8100. // Note that LHS might be a scalar because the routine calls not only in
  8101. // OpenCL case.
  8102. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  8103. QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
  8104. // Note that RHS might not be a vector.
  8105. QualType RHSType = RHS.get()->getType();
  8106. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  8107. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  8108. // The operands need to be integers.
  8109. if (!LHSEleType->isIntegerType()) {
  8110. S.Diag(Loc, diag::err_typecheck_expect_int)
  8111. << LHS.get()->getType() << LHS.get()->getSourceRange();
  8112. return QualType();
  8113. }
  8114. if (!RHSEleType->isIntegerType()) {
  8115. S.Diag(Loc, diag::err_typecheck_expect_int)
  8116. << RHS.get()->getType() << RHS.get()->getSourceRange();
  8117. return QualType();
  8118. }
  8119. if (!LHSVecTy) {
  8120. assert(RHSVecTy);
  8121. if (IsCompAssign)
  8122. return RHSType;
  8123. if (LHSEleType != RHSEleType) {
  8124. LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
  8125. LHSEleType = RHSEleType;
  8126. }
  8127. QualType VecTy =
  8128. S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
  8129. LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
  8130. LHSType = VecTy;
  8131. } else if (RHSVecTy) {
  8132. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  8133. // are applied component-wise. So if RHS is a vector, then ensure
  8134. // that the number of elements is the same as LHS...
  8135. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  8136. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  8137. << LHS.get()->getType() << RHS.get()->getType()
  8138. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8139. return QualType();
  8140. }
  8141. if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
  8142. const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
  8143. const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
  8144. if (LHSBT != RHSBT &&
  8145. S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
  8146. S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
  8147. << LHS.get()->getType() << RHS.get()->getType()
  8148. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8149. }
  8150. }
  8151. } else {
  8152. // ...else expand RHS to match the number of elements in LHS.
  8153. QualType VecTy =
  8154. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  8155. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  8156. }
  8157. return LHSType;
  8158. }
  8159. // C99 6.5.7
  8160. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  8161. SourceLocation Loc, BinaryOperatorKind Opc,
  8162. bool IsCompAssign) {
  8163. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  8164. // Vector shifts promote their scalar inputs to vector type.
  8165. if (LHS.get()->getType()->isVectorType() ||
  8166. RHS.get()->getType()->isVectorType()) {
  8167. if (LangOpts.ZVector) {
  8168. // The shift operators for the z vector extensions work basically
  8169. // like general shifts, except that neither the LHS nor the RHS is
  8170. // allowed to be a "vector bool".
  8171. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  8172. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8173. return InvalidOperands(Loc, LHS, RHS);
  8174. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  8175. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8176. return InvalidOperands(Loc, LHS, RHS);
  8177. }
  8178. return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  8179. }
  8180. // Shifts don't perform usual arithmetic conversions, they just do integer
  8181. // promotions on each operand. C99 6.5.7p3
  8182. // For the LHS, do usual unary conversions, but then reset them away
  8183. // if this is a compound assignment.
  8184. ExprResult OldLHS = LHS;
  8185. LHS = UsualUnaryConversions(LHS.get());
  8186. if (LHS.isInvalid())
  8187. return QualType();
  8188. QualType LHSType = LHS.get()->getType();
  8189. if (IsCompAssign) LHS = OldLHS;
  8190. // The RHS is simpler.
  8191. RHS = UsualUnaryConversions(RHS.get());
  8192. if (RHS.isInvalid())
  8193. return QualType();
  8194. QualType RHSType = RHS.get()->getType();
  8195. // C99 6.5.7p2: Each of the operands shall have integer type.
  8196. if (!LHSType->hasIntegerRepresentation() ||
  8197. !RHSType->hasIntegerRepresentation())
  8198. return InvalidOperands(Loc, LHS, RHS);
  8199. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  8200. // hasIntegerRepresentation() above instead of this.
  8201. if (isScopedEnumerationType(LHSType) ||
  8202. isScopedEnumerationType(RHSType)) {
  8203. return InvalidOperands(Loc, LHS, RHS);
  8204. }
  8205. // Sanity-check shift operands
  8206. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  8207. // "The type of the result is that of the promoted left operand."
  8208. return LHSType;
  8209. }
  8210. /// If two different enums are compared, raise a warning.
  8211. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  8212. Expr *RHS) {
  8213. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  8214. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  8215. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  8216. if (!LHSEnumType)
  8217. return;
  8218. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  8219. if (!RHSEnumType)
  8220. return;
  8221. // Ignore anonymous enums.
  8222. if (!LHSEnumType->getDecl()->getIdentifier() &&
  8223. !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8224. return;
  8225. if (!RHSEnumType->getDecl()->getIdentifier() &&
  8226. !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8227. return;
  8228. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  8229. return;
  8230. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  8231. << LHSStrippedType << RHSStrippedType
  8232. << LHS->getSourceRange() << RHS->getSourceRange();
  8233. }
  8234. /// Diagnose bad pointer comparisons.
  8235. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  8236. ExprResult &LHS, ExprResult &RHS,
  8237. bool IsError) {
  8238. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  8239. : diag::ext_typecheck_comparison_of_distinct_pointers)
  8240. << LHS.get()->getType() << RHS.get()->getType()
  8241. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8242. }
  8243. /// Returns false if the pointers are converted to a composite type,
  8244. /// true otherwise.
  8245. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  8246. ExprResult &LHS, ExprResult &RHS) {
  8247. // C++ [expr.rel]p2:
  8248. // [...] Pointer conversions (4.10) and qualification
  8249. // conversions (4.4) are performed on pointer operands (or on
  8250. // a pointer operand and a null pointer constant) to bring
  8251. // them to their composite pointer type. [...]
  8252. //
  8253. // C++ [expr.eq]p1 uses the same notion for (in)equality
  8254. // comparisons of pointers.
  8255. QualType LHSType = LHS.get()->getType();
  8256. QualType RHSType = RHS.get()->getType();
  8257. assert(LHSType->isPointerType() || RHSType->isPointerType() ||
  8258. LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
  8259. QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
  8260. if (T.isNull()) {
  8261. if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
  8262. (RHSType->isPointerType() || RHSType->isMemberPointerType()))
  8263. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  8264. else
  8265. S.InvalidOperands(Loc, LHS, RHS);
  8266. return true;
  8267. }
  8268. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  8269. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  8270. return false;
  8271. }
  8272. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  8273. ExprResult &LHS,
  8274. ExprResult &RHS,
  8275. bool IsError) {
  8276. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  8277. : diag::ext_typecheck_comparison_of_fptr_to_void)
  8278. << LHS.get()->getType() << RHS.get()->getType()
  8279. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8280. }
  8281. static bool isObjCObjectLiteral(ExprResult &E) {
  8282. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  8283. case Stmt::ObjCArrayLiteralClass:
  8284. case Stmt::ObjCDictionaryLiteralClass:
  8285. case Stmt::ObjCStringLiteralClass:
  8286. case Stmt::ObjCBoxedExprClass:
  8287. return true;
  8288. default:
  8289. // Note that ObjCBoolLiteral is NOT an object literal!
  8290. return false;
  8291. }
  8292. }
  8293. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  8294. const ObjCObjectPointerType *Type =
  8295. LHS->getType()->getAs<ObjCObjectPointerType>();
  8296. // If this is not actually an Objective-C object, bail out.
  8297. if (!Type)
  8298. return false;
  8299. // Get the LHS object's interface type.
  8300. QualType InterfaceType = Type->getPointeeType();
  8301. // If the RHS isn't an Objective-C object, bail out.
  8302. if (!RHS->getType()->isObjCObjectPointerType())
  8303. return false;
  8304. // Try to find the -isEqual: method.
  8305. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  8306. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  8307. InterfaceType,
  8308. /*instance=*/true);
  8309. if (!Method) {
  8310. if (Type->isObjCIdType()) {
  8311. // For 'id', just check the global pool.
  8312. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  8313. /*receiverId=*/true);
  8314. } else {
  8315. // Check protocols.
  8316. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  8317. /*instance=*/true);
  8318. }
  8319. }
  8320. if (!Method)
  8321. return false;
  8322. QualType T = Method->parameters()[0]->getType();
  8323. if (!T->isObjCObjectPointerType())
  8324. return false;
  8325. QualType R = Method->getReturnType();
  8326. if (!R->isScalarType())
  8327. return false;
  8328. return true;
  8329. }
  8330. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  8331. FromE = FromE->IgnoreParenImpCasts();
  8332. switch (FromE->getStmtClass()) {
  8333. default:
  8334. break;
  8335. case Stmt::ObjCStringLiteralClass:
  8336. // "string literal"
  8337. return LK_String;
  8338. case Stmt::ObjCArrayLiteralClass:
  8339. // "array literal"
  8340. return LK_Array;
  8341. case Stmt::ObjCDictionaryLiteralClass:
  8342. // "dictionary literal"
  8343. return LK_Dictionary;
  8344. case Stmt::BlockExprClass:
  8345. return LK_Block;
  8346. case Stmt::ObjCBoxedExprClass: {
  8347. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  8348. switch (Inner->getStmtClass()) {
  8349. case Stmt::IntegerLiteralClass:
  8350. case Stmt::FloatingLiteralClass:
  8351. case Stmt::CharacterLiteralClass:
  8352. case Stmt::ObjCBoolLiteralExprClass:
  8353. case Stmt::CXXBoolLiteralExprClass:
  8354. // "numeric literal"
  8355. return LK_Numeric;
  8356. case Stmt::ImplicitCastExprClass: {
  8357. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  8358. // Boolean literals can be represented by implicit casts.
  8359. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  8360. return LK_Numeric;
  8361. break;
  8362. }
  8363. default:
  8364. break;
  8365. }
  8366. return LK_Boxed;
  8367. }
  8368. }
  8369. return LK_None;
  8370. }
  8371. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  8372. ExprResult &LHS, ExprResult &RHS,
  8373. BinaryOperator::Opcode Opc){
  8374. Expr *Literal;
  8375. Expr *Other;
  8376. if (isObjCObjectLiteral(LHS)) {
  8377. Literal = LHS.get();
  8378. Other = RHS.get();
  8379. } else {
  8380. Literal = RHS.get();
  8381. Other = LHS.get();
  8382. }
  8383. // Don't warn on comparisons against nil.
  8384. Other = Other->IgnoreParenCasts();
  8385. if (Other->isNullPointerConstant(S.getASTContext(),
  8386. Expr::NPC_ValueDependentIsNotNull))
  8387. return;
  8388. // This should be kept in sync with warn_objc_literal_comparison.
  8389. // LK_String should always be after the other literals, since it has its own
  8390. // warning flag.
  8391. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  8392. assert(LiteralKind != Sema::LK_Block);
  8393. if (LiteralKind == Sema::LK_None) {
  8394. llvm_unreachable("Unknown Objective-C object literal kind");
  8395. }
  8396. if (LiteralKind == Sema::LK_String)
  8397. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  8398. << Literal->getSourceRange();
  8399. else
  8400. S.Diag(Loc, diag::warn_objc_literal_comparison)
  8401. << LiteralKind << Literal->getSourceRange();
  8402. if (BinaryOperator::isEqualityOp(Opc) &&
  8403. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  8404. SourceLocation Start = LHS.get()->getLocStart();
  8405. SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
  8406. CharSourceRange OpRange =
  8407. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  8408. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  8409. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  8410. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  8411. << FixItHint::CreateInsertion(End, "]");
  8412. }
  8413. }
  8414. /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
  8415. static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
  8416. ExprResult &RHS, SourceLocation Loc,
  8417. BinaryOperatorKind Opc) {
  8418. // Check that left hand side is !something.
  8419. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  8420. if (!UO || UO->getOpcode() != UO_LNot) return;
  8421. // Only check if the right hand side is non-bool arithmetic type.
  8422. if (RHS.get()->isKnownToHaveBooleanValue()) return;
  8423. // Make sure that the something in !something is not bool.
  8424. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  8425. if (SubExpr->isKnownToHaveBooleanValue()) return;
  8426. // Emit warning.
  8427. bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
  8428. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
  8429. << Loc << IsBitwiseOp;
  8430. // First note suggest !(x < y)
  8431. SourceLocation FirstOpen = SubExpr->getLocStart();
  8432. SourceLocation FirstClose = RHS.get()->getLocEnd();
  8433. FirstClose = S.getLocForEndOfToken(FirstClose);
  8434. if (FirstClose.isInvalid())
  8435. FirstOpen = SourceLocation();
  8436. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  8437. << IsBitwiseOp
  8438. << FixItHint::CreateInsertion(FirstOpen, "(")
  8439. << FixItHint::CreateInsertion(FirstClose, ")");
  8440. // Second note suggests (!x) < y
  8441. SourceLocation SecondOpen = LHS.get()->getLocStart();
  8442. SourceLocation SecondClose = LHS.get()->getLocEnd();
  8443. SecondClose = S.getLocForEndOfToken(SecondClose);
  8444. if (SecondClose.isInvalid())
  8445. SecondOpen = SourceLocation();
  8446. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  8447. << FixItHint::CreateInsertion(SecondOpen, "(")
  8448. << FixItHint::CreateInsertion(SecondClose, ")");
  8449. }
  8450. // Get the decl for a simple expression: a reference to a variable,
  8451. // an implicit C++ field reference, or an implicit ObjC ivar reference.
  8452. static ValueDecl *getCompareDecl(Expr *E) {
  8453. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
  8454. return DR->getDecl();
  8455. if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
  8456. if (Ivar->isFreeIvar())
  8457. return Ivar->getDecl();
  8458. }
  8459. if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
  8460. if (Mem->isImplicitAccess())
  8461. return Mem->getMemberDecl();
  8462. }
  8463. return nullptr;
  8464. }
  8465. /// Diagnose some forms of syntactically-obvious tautological comparison.
  8466. static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
  8467. Expr *LHS, Expr *RHS,
  8468. BinaryOperatorKind Opc) {
  8469. Expr *LHSStripped = LHS->IgnoreParenImpCasts();
  8470. Expr *RHSStripped = RHS->IgnoreParenImpCasts();
  8471. QualType LHSType = LHS->getType();
  8472. QualType RHSType = RHS->getType();
  8473. if (LHSType->hasFloatingRepresentation() ||
  8474. (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
  8475. LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() ||
  8476. S.inTemplateInstantiation())
  8477. return;
  8478. // Comparisons between two array types are ill-formed for operator<=>, so
  8479. // we shouldn't emit any additional warnings about it.
  8480. if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
  8481. return;
  8482. // For non-floating point types, check for self-comparisons of the form
  8483. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  8484. // often indicate logic errors in the program.
  8485. //
  8486. // NOTE: Don't warn about comparison expressions resulting from macro
  8487. // expansion. Also don't warn about comparisons which are only self
  8488. // comparisons within a template instantiation. The warnings should catch
  8489. // obvious cases in the definition of the template anyways. The idea is to
  8490. // warn when the typed comparison operator will always evaluate to the same
  8491. // result.
  8492. ValueDecl *DL = getCompareDecl(LHSStripped);
  8493. ValueDecl *DR = getCompareDecl(RHSStripped);
  8494. if (DL && DR && declaresSameEntity(DL, DR)) {
  8495. StringRef Result;
  8496. switch (Opc) {
  8497. case BO_EQ: case BO_LE: case BO_GE:
  8498. Result = "true";
  8499. break;
  8500. case BO_NE: case BO_LT: case BO_GT:
  8501. Result = "false";
  8502. break;
  8503. case BO_Cmp:
  8504. Result = "'std::strong_ordering::equal'";
  8505. break;
  8506. default:
  8507. break;
  8508. }
  8509. S.DiagRuntimeBehavior(Loc, nullptr,
  8510. S.PDiag(diag::warn_comparison_always)
  8511. << 0 /*self-comparison*/ << !Result.empty()
  8512. << Result);
  8513. } else if (DL && DR &&
  8514. DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
  8515. !DL->isWeak() && !DR->isWeak()) {
  8516. // What is it always going to evaluate to?
  8517. StringRef Result;
  8518. switch(Opc) {
  8519. case BO_EQ: // e.g. array1 == array2
  8520. Result = "false";
  8521. break;
  8522. case BO_NE: // e.g. array1 != array2
  8523. Result = "true";
  8524. break;
  8525. default: // e.g. array1 <= array2
  8526. // The best we can say is 'a constant'
  8527. break;
  8528. }
  8529. S.DiagRuntimeBehavior(Loc, nullptr,
  8530. S.PDiag(diag::warn_comparison_always)
  8531. << 1 /*array comparison*/
  8532. << !Result.empty() << Result);
  8533. }
  8534. if (isa<CastExpr>(LHSStripped))
  8535. LHSStripped = LHSStripped->IgnoreParenCasts();
  8536. if (isa<CastExpr>(RHSStripped))
  8537. RHSStripped = RHSStripped->IgnoreParenCasts();
  8538. // Warn about comparisons against a string constant (unless the other
  8539. // operand is null); the user probably wants strcmp.
  8540. Expr *LiteralString = nullptr;
  8541. Expr *LiteralStringStripped = nullptr;
  8542. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  8543. !RHSStripped->isNullPointerConstant(S.Context,
  8544. Expr::NPC_ValueDependentIsNull)) {
  8545. LiteralString = LHS;
  8546. LiteralStringStripped = LHSStripped;
  8547. } else if ((isa<StringLiteral>(RHSStripped) ||
  8548. isa<ObjCEncodeExpr>(RHSStripped)) &&
  8549. !LHSStripped->isNullPointerConstant(S.Context,
  8550. Expr::NPC_ValueDependentIsNull)) {
  8551. LiteralString = RHS;
  8552. LiteralStringStripped = RHSStripped;
  8553. }
  8554. if (LiteralString) {
  8555. S.DiagRuntimeBehavior(Loc, nullptr,
  8556. S.PDiag(diag::warn_stringcompare)
  8557. << isa<ObjCEncodeExpr>(LiteralStringStripped)
  8558. << LiteralString->getSourceRange());
  8559. }
  8560. }
  8561. static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
  8562. switch (CK) {
  8563. default: {
  8564. #ifndef NDEBUG
  8565. llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
  8566. << "\n";
  8567. #endif
  8568. llvm_unreachable("unhandled cast kind");
  8569. }
  8570. case CK_UserDefinedConversion:
  8571. return ICK_Identity;
  8572. case CK_LValueToRValue:
  8573. return ICK_Lvalue_To_Rvalue;
  8574. case CK_ArrayToPointerDecay:
  8575. return ICK_Array_To_Pointer;
  8576. case CK_FunctionToPointerDecay:
  8577. return ICK_Function_To_Pointer;
  8578. case CK_IntegralCast:
  8579. return ICK_Integral_Conversion;
  8580. case CK_FloatingCast:
  8581. return ICK_Floating_Conversion;
  8582. case CK_IntegralToFloating:
  8583. case CK_FloatingToIntegral:
  8584. return ICK_Floating_Integral;
  8585. case CK_IntegralComplexCast:
  8586. case CK_FloatingComplexCast:
  8587. case CK_FloatingComplexToIntegralComplex:
  8588. case CK_IntegralComplexToFloatingComplex:
  8589. return ICK_Complex_Conversion;
  8590. case CK_FloatingComplexToReal:
  8591. case CK_FloatingRealToComplex:
  8592. case CK_IntegralComplexToReal:
  8593. case CK_IntegralRealToComplex:
  8594. return ICK_Complex_Real;
  8595. }
  8596. }
  8597. static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
  8598. QualType FromType,
  8599. SourceLocation Loc) {
  8600. // Check for a narrowing implicit conversion.
  8601. StandardConversionSequence SCS;
  8602. SCS.setAsIdentityConversion();
  8603. SCS.setToType(0, FromType);
  8604. SCS.setToType(1, ToType);
  8605. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  8606. SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
  8607. APValue PreNarrowingValue;
  8608. QualType PreNarrowingType;
  8609. switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
  8610. PreNarrowingType,
  8611. /*IgnoreFloatToIntegralConversion*/ true)) {
  8612. case NK_Dependent_Narrowing:
  8613. // Implicit conversion to a narrower type, but the expression is
  8614. // value-dependent so we can't tell whether it's actually narrowing.
  8615. case NK_Not_Narrowing:
  8616. return false;
  8617. case NK_Constant_Narrowing:
  8618. // Implicit conversion to a narrower type, and the value is not a constant
  8619. // expression.
  8620. S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
  8621. << /*Constant*/ 1
  8622. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
  8623. return true;
  8624. case NK_Variable_Narrowing:
  8625. // Implicit conversion to a narrower type, and the value is not a constant
  8626. // expression.
  8627. case NK_Type_Narrowing:
  8628. S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
  8629. << /*Constant*/ 0 << FromType << ToType;
  8630. // TODO: It's not a constant expression, but what if the user intended it
  8631. // to be? Can we produce notes to help them figure out why it isn't?
  8632. return true;
  8633. }
  8634. llvm_unreachable("unhandled case in switch");
  8635. }
  8636. static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
  8637. ExprResult &LHS,
  8638. ExprResult &RHS,
  8639. SourceLocation Loc) {
  8640. using CCT = ComparisonCategoryType;
  8641. QualType LHSType = LHS.get()->getType();
  8642. QualType RHSType = RHS.get()->getType();
  8643. // Dig out the original argument type and expression before implicit casts
  8644. // were applied. These are the types/expressions we need to check the
  8645. // [expr.spaceship] requirements against.
  8646. ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
  8647. ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
  8648. QualType LHSStrippedType = LHSStripped.get()->getType();
  8649. QualType RHSStrippedType = RHSStripped.get()->getType();
  8650. // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
  8651. // other is not, the program is ill-formed.
  8652. if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
  8653. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  8654. return QualType();
  8655. }
  8656. int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
  8657. RHSStrippedType->isEnumeralType();
  8658. if (NumEnumArgs == 1) {
  8659. bool LHSIsEnum = LHSStrippedType->isEnumeralType();
  8660. QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
  8661. if (OtherTy->hasFloatingRepresentation()) {
  8662. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  8663. return QualType();
  8664. }
  8665. }
  8666. if (NumEnumArgs == 2) {
  8667. // C++2a [expr.spaceship]p5: If both operands have the same enumeration
  8668. // type E, the operator yields the result of converting the operands
  8669. // to the underlying type of E and applying <=> to the converted operands.
  8670. if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
  8671. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  8672. return QualType();
  8673. }
  8674. QualType IntType =
  8675. LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
  8676. assert(IntType->isArithmeticType());
  8677. // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
  8678. // promote the boolean type, and all other promotable integer types, to
  8679. // avoid this.
  8680. if (IntType->isPromotableIntegerType())
  8681. IntType = S.Context.getPromotedIntegerType(IntType);
  8682. LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
  8683. RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
  8684. LHSType = RHSType = IntType;
  8685. }
  8686. // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
  8687. // usual arithmetic conversions are applied to the operands.
  8688. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  8689. if (LHS.isInvalid() || RHS.isInvalid())
  8690. return QualType();
  8691. if (Type.isNull())
  8692. return S.InvalidOperands(Loc, LHS, RHS);
  8693. assert(Type->isArithmeticType() || Type->isEnumeralType());
  8694. bool HasNarrowing = checkThreeWayNarrowingConversion(
  8695. S, Type, LHS.get(), LHSType, LHS.get()->getLocStart());
  8696. HasNarrowing |= checkThreeWayNarrowingConversion(
  8697. S, Type, RHS.get(), RHSType, RHS.get()->getLocStart());
  8698. if (HasNarrowing)
  8699. return QualType();
  8700. assert(!Type.isNull() && "composite type for <=> has not been set");
  8701. auto TypeKind = [&]() {
  8702. if (const ComplexType *CT = Type->getAs<ComplexType>()) {
  8703. if (CT->getElementType()->hasFloatingRepresentation())
  8704. return CCT::WeakEquality;
  8705. return CCT::StrongEquality;
  8706. }
  8707. if (Type->isIntegralOrEnumerationType())
  8708. return CCT::StrongOrdering;
  8709. if (Type->hasFloatingRepresentation())
  8710. return CCT::PartialOrdering;
  8711. llvm_unreachable("other types are unimplemented");
  8712. }();
  8713. return S.CheckComparisonCategoryType(TypeKind, Loc);
  8714. }
  8715. static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
  8716. ExprResult &RHS,
  8717. SourceLocation Loc,
  8718. BinaryOperatorKind Opc) {
  8719. if (Opc == BO_Cmp)
  8720. return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
  8721. // C99 6.5.8p3 / C99 6.5.9p4
  8722. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  8723. if (LHS.isInvalid() || RHS.isInvalid())
  8724. return QualType();
  8725. if (Type.isNull())
  8726. return S.InvalidOperands(Loc, LHS, RHS);
  8727. assert(Type->isArithmeticType() || Type->isEnumeralType());
  8728. checkEnumComparison(S, Loc, LHS.get(), RHS.get());
  8729. if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
  8730. return S.InvalidOperands(Loc, LHS, RHS);
  8731. // Check for comparisons of floating point operands using != and ==.
  8732. if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
  8733. S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
  8734. // The result of comparisons is 'bool' in C++, 'int' in C.
  8735. return S.Context.getLogicalOperationType();
  8736. }
  8737. // C99 6.5.8, C++ [expr.rel]
  8738. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  8739. SourceLocation Loc,
  8740. BinaryOperatorKind Opc) {
  8741. bool IsRelational = BinaryOperator::isRelationalOp(Opc);
  8742. bool IsThreeWay = Opc == BO_Cmp;
  8743. auto IsAnyPointerType = [](ExprResult E) {
  8744. QualType Ty = E.get()->getType();
  8745. return Ty->isPointerType() || Ty->isMemberPointerType();
  8746. };
  8747. // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
  8748. // type, array-to-pointer, ..., conversions are performed on both operands to
  8749. // bring them to their composite type.
  8750. // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
  8751. // any type-related checks.
  8752. if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
  8753. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  8754. if (LHS.isInvalid())
  8755. return QualType();
  8756. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  8757. if (RHS.isInvalid())
  8758. return QualType();
  8759. } else {
  8760. LHS = DefaultLvalueConversion(LHS.get());
  8761. if (LHS.isInvalid())
  8762. return QualType();
  8763. RHS = DefaultLvalueConversion(RHS.get());
  8764. if (RHS.isInvalid())
  8765. return QualType();
  8766. }
  8767. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
  8768. // Handle vector comparisons separately.
  8769. if (LHS.get()->getType()->isVectorType() ||
  8770. RHS.get()->getType()->isVectorType())
  8771. return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
  8772. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  8773. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  8774. QualType LHSType = LHS.get()->getType();
  8775. QualType RHSType = RHS.get()->getType();
  8776. if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
  8777. (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
  8778. return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
  8779. const Expr::NullPointerConstantKind LHSNullKind =
  8780. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  8781. const Expr::NullPointerConstantKind RHSNullKind =
  8782. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  8783. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  8784. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  8785. auto computeResultTy = [&]() {
  8786. if (Opc != BO_Cmp)
  8787. return Context.getLogicalOperationType();
  8788. assert(getLangOpts().CPlusPlus);
  8789. assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
  8790. QualType CompositeTy = LHS.get()->getType();
  8791. assert(!CompositeTy->isReferenceType());
  8792. auto buildResultTy = [&](ComparisonCategoryType Kind) {
  8793. return CheckComparisonCategoryType(Kind, Loc);
  8794. };
  8795. // C++2a [expr.spaceship]p7: If the composite pointer type is a function
  8796. // pointer type, a pointer-to-member type, or std::nullptr_t, the
  8797. // result is of type std::strong_equality
  8798. if (CompositeTy->isFunctionPointerType() ||
  8799. CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
  8800. // FIXME: consider making the function pointer case produce
  8801. // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
  8802. // and direction polls
  8803. return buildResultTy(ComparisonCategoryType::StrongEquality);
  8804. // C++2a [expr.spaceship]p8: If the composite pointer type is an object
  8805. // pointer type, p <=> q is of type std::strong_ordering.
  8806. if (CompositeTy->isPointerType()) {
  8807. // P0946R0: Comparisons between a null pointer constant and an object
  8808. // pointer result in std::strong_equality
  8809. if (LHSIsNull != RHSIsNull)
  8810. return buildResultTy(ComparisonCategoryType::StrongEquality);
  8811. return buildResultTy(ComparisonCategoryType::StrongOrdering);
  8812. }
  8813. // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
  8814. // TODO: Extend support for operator<=> to ObjC types.
  8815. return InvalidOperands(Loc, LHS, RHS);
  8816. };
  8817. if (!IsRelational && LHSIsNull != RHSIsNull) {
  8818. bool IsEquality = Opc == BO_EQ;
  8819. if (RHSIsNull)
  8820. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  8821. RHS.get()->getSourceRange());
  8822. else
  8823. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  8824. LHS.get()->getSourceRange());
  8825. }
  8826. if ((LHSType->isIntegerType() && !LHSIsNull) ||
  8827. (RHSType->isIntegerType() && !RHSIsNull)) {
  8828. // Skip normal pointer conversion checks in this case; we have better
  8829. // diagnostics for this below.
  8830. } else if (getLangOpts().CPlusPlus) {
  8831. // Equality comparison of a function pointer to a void pointer is invalid,
  8832. // but we allow it as an extension.
  8833. // FIXME: If we really want to allow this, should it be part of composite
  8834. // pointer type computation so it works in conditionals too?
  8835. if (!IsRelational &&
  8836. ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
  8837. (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
  8838. // This is a gcc extension compatibility comparison.
  8839. // In a SFINAE context, we treat this as a hard error to maintain
  8840. // conformance with the C++ standard.
  8841. diagnoseFunctionPointerToVoidComparison(
  8842. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  8843. if (isSFINAEContext())
  8844. return QualType();
  8845. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  8846. return computeResultTy();
  8847. }
  8848. // C++ [expr.eq]p2:
  8849. // If at least one operand is a pointer [...] bring them to their
  8850. // composite pointer type.
  8851. // C++ [expr.spaceship]p6
  8852. // If at least one of the operands is of pointer type, [...] bring them
  8853. // to their composite pointer type.
  8854. // C++ [expr.rel]p2:
  8855. // If both operands are pointers, [...] bring them to their composite
  8856. // pointer type.
  8857. if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
  8858. (IsRelational ? 2 : 1) &&
  8859. (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
  8860. RHSType->isObjCObjectPointerType()))) {
  8861. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  8862. return QualType();
  8863. return computeResultTy();
  8864. }
  8865. } else if (LHSType->isPointerType() &&
  8866. RHSType->isPointerType()) { // C99 6.5.8p2
  8867. // All of the following pointer-related warnings are GCC extensions, except
  8868. // when handling null pointer constants.
  8869. QualType LCanPointeeTy =
  8870. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  8871. QualType RCanPointeeTy =
  8872. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  8873. // C99 6.5.9p2 and C99 6.5.8p2
  8874. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  8875. RCanPointeeTy.getUnqualifiedType())) {
  8876. // Valid unless a relational comparison of function pointers
  8877. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  8878. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  8879. << LHSType << RHSType << LHS.get()->getSourceRange()
  8880. << RHS.get()->getSourceRange();
  8881. }
  8882. } else if (!IsRelational &&
  8883. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  8884. // Valid unless comparison between non-null pointer and function pointer
  8885. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  8886. && !LHSIsNull && !RHSIsNull)
  8887. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  8888. /*isError*/false);
  8889. } else {
  8890. // Invalid
  8891. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  8892. }
  8893. if (LCanPointeeTy != RCanPointeeTy) {
  8894. // Treat NULL constant as a special case in OpenCL.
  8895. if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
  8896. const PointerType *LHSPtr = LHSType->getAs<PointerType>();
  8897. if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  8898. Diag(Loc,
  8899. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  8900. << LHSType << RHSType << 0 /* comparison */
  8901. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8902. }
  8903. }
  8904. LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
  8905. LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
  8906. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  8907. : CK_BitCast;
  8908. if (LHSIsNull && !RHSIsNull)
  8909. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  8910. else
  8911. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  8912. }
  8913. return computeResultTy();
  8914. }
  8915. if (getLangOpts().CPlusPlus) {
  8916. // C++ [expr.eq]p4:
  8917. // Two operands of type std::nullptr_t or one operand of type
  8918. // std::nullptr_t and the other a null pointer constant compare equal.
  8919. if (!IsRelational && LHSIsNull && RHSIsNull) {
  8920. if (LHSType->isNullPtrType()) {
  8921. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  8922. return computeResultTy();
  8923. }
  8924. if (RHSType->isNullPtrType()) {
  8925. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  8926. return computeResultTy();
  8927. }
  8928. }
  8929. // Comparison of Objective-C pointers and block pointers against nullptr_t.
  8930. // These aren't covered by the composite pointer type rules.
  8931. if (!IsRelational && RHSType->isNullPtrType() &&
  8932. (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
  8933. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  8934. return computeResultTy();
  8935. }
  8936. if (!IsRelational && LHSType->isNullPtrType() &&
  8937. (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
  8938. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  8939. return computeResultTy();
  8940. }
  8941. if (IsRelational &&
  8942. ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
  8943. (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
  8944. // HACK: Relational comparison of nullptr_t against a pointer type is
  8945. // invalid per DR583, but we allow it within std::less<> and friends,
  8946. // since otherwise common uses of it break.
  8947. // FIXME: Consider removing this hack once LWG fixes std::less<> and
  8948. // friends to have std::nullptr_t overload candidates.
  8949. DeclContext *DC = CurContext;
  8950. if (isa<FunctionDecl>(DC))
  8951. DC = DC->getParent();
  8952. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  8953. if (CTSD->isInStdNamespace() &&
  8954. llvm::StringSwitch<bool>(CTSD->getName())
  8955. .Cases("less", "less_equal", "greater", "greater_equal", true)
  8956. .Default(false)) {
  8957. if (RHSType->isNullPtrType())
  8958. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  8959. else
  8960. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  8961. return computeResultTy();
  8962. }
  8963. }
  8964. }
  8965. // C++ [expr.eq]p2:
  8966. // If at least one operand is a pointer to member, [...] bring them to
  8967. // their composite pointer type.
  8968. if (!IsRelational &&
  8969. (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
  8970. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  8971. return QualType();
  8972. else
  8973. return computeResultTy();
  8974. }
  8975. }
  8976. // Handle block pointer types.
  8977. if (!IsRelational && LHSType->isBlockPointerType() &&
  8978. RHSType->isBlockPointerType()) {
  8979. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  8980. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  8981. if (!LHSIsNull && !RHSIsNull &&
  8982. !Context.typesAreCompatible(lpointee, rpointee)) {
  8983. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  8984. << LHSType << RHSType << LHS.get()->getSourceRange()
  8985. << RHS.get()->getSourceRange();
  8986. }
  8987. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  8988. return computeResultTy();
  8989. }
  8990. // Allow block pointers to be compared with null pointer constants.
  8991. if (!IsRelational
  8992. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  8993. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  8994. if (!LHSIsNull && !RHSIsNull) {
  8995. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  8996. ->getPointeeType()->isVoidType())
  8997. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  8998. ->getPointeeType()->isVoidType())))
  8999. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9000. << LHSType << RHSType << LHS.get()->getSourceRange()
  9001. << RHS.get()->getSourceRange();
  9002. }
  9003. if (LHSIsNull && !RHSIsNull)
  9004. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9005. RHSType->isPointerType() ? CK_BitCast
  9006. : CK_AnyPointerToBlockPointerCast);
  9007. else
  9008. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9009. LHSType->isPointerType() ? CK_BitCast
  9010. : CK_AnyPointerToBlockPointerCast);
  9011. return computeResultTy();
  9012. }
  9013. if (LHSType->isObjCObjectPointerType() ||
  9014. RHSType->isObjCObjectPointerType()) {
  9015. const PointerType *LPT = LHSType->getAs<PointerType>();
  9016. const PointerType *RPT = RHSType->getAs<PointerType>();
  9017. if (LPT || RPT) {
  9018. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  9019. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  9020. if (!LPtrToVoid && !RPtrToVoid &&
  9021. !Context.typesAreCompatible(LHSType, RHSType)) {
  9022. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9023. /*isError*/false);
  9024. }
  9025. if (LHSIsNull && !RHSIsNull) {
  9026. Expr *E = LHS.get();
  9027. if (getLangOpts().ObjCAutoRefCount)
  9028. CheckObjCConversion(SourceRange(), RHSType, E,
  9029. CCK_ImplicitConversion);
  9030. LHS = ImpCastExprToType(E, RHSType,
  9031. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9032. }
  9033. else {
  9034. Expr *E = RHS.get();
  9035. if (getLangOpts().ObjCAutoRefCount)
  9036. CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
  9037. /*Diagnose=*/true,
  9038. /*DiagnoseCFAudited=*/false, Opc);
  9039. RHS = ImpCastExprToType(E, LHSType,
  9040. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9041. }
  9042. return computeResultTy();
  9043. }
  9044. if (LHSType->isObjCObjectPointerType() &&
  9045. RHSType->isObjCObjectPointerType()) {
  9046. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  9047. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9048. /*isError*/false);
  9049. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  9050. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  9051. if (LHSIsNull && !RHSIsNull)
  9052. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  9053. else
  9054. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9055. return computeResultTy();
  9056. }
  9057. if (!IsRelational && LHSType->isBlockPointerType() &&
  9058. RHSType->isBlockCompatibleObjCPointerType(Context)) {
  9059. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9060. CK_BlockPointerToObjCPointerCast);
  9061. return computeResultTy();
  9062. } else if (!IsRelational &&
  9063. LHSType->isBlockCompatibleObjCPointerType(Context) &&
  9064. RHSType->isBlockPointerType()) {
  9065. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9066. CK_BlockPointerToObjCPointerCast);
  9067. return computeResultTy();
  9068. }
  9069. }
  9070. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  9071. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  9072. unsigned DiagID = 0;
  9073. bool isError = false;
  9074. if (LangOpts.DebuggerSupport) {
  9075. // Under a debugger, allow the comparison of pointers to integers,
  9076. // since users tend to want to compare addresses.
  9077. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  9078. (RHSIsNull && RHSType->isIntegerType())) {
  9079. if (IsRelational) {
  9080. isError = getLangOpts().CPlusPlus;
  9081. DiagID =
  9082. isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
  9083. : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  9084. }
  9085. } else if (getLangOpts().CPlusPlus) {
  9086. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  9087. isError = true;
  9088. } else if (IsRelational)
  9089. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  9090. else
  9091. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  9092. if (DiagID) {
  9093. Diag(Loc, DiagID)
  9094. << LHSType << RHSType << LHS.get()->getSourceRange()
  9095. << RHS.get()->getSourceRange();
  9096. if (isError)
  9097. return QualType();
  9098. }
  9099. if (LHSType->isIntegerType())
  9100. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9101. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9102. else
  9103. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9104. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9105. return computeResultTy();
  9106. }
  9107. // Handle block pointers.
  9108. if (!IsRelational && RHSIsNull
  9109. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  9110. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9111. return computeResultTy();
  9112. }
  9113. if (!IsRelational && LHSIsNull
  9114. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  9115. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9116. return computeResultTy();
  9117. }
  9118. if (getLangOpts().OpenCLVersion >= 200) {
  9119. if (LHSIsNull && RHSType->isQueueT()) {
  9120. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9121. return computeResultTy();
  9122. }
  9123. if (LHSType->isQueueT() && RHSIsNull) {
  9124. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9125. return computeResultTy();
  9126. }
  9127. }
  9128. return InvalidOperands(Loc, LHS, RHS);
  9129. }
  9130. // Return a signed ext_vector_type that is of identical size and number of
  9131. // elements. For floating point vectors, return an integer type of identical
  9132. // size and number of elements. In the non ext_vector_type case, search from
  9133. // the largest type to the smallest type to avoid cases where long long == long,
  9134. // where long gets picked over long long.
  9135. QualType Sema::GetSignedVectorType(QualType V) {
  9136. const VectorType *VTy = V->getAs<VectorType>();
  9137. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  9138. if (isa<ExtVectorType>(VTy)) {
  9139. if (TypeSize == Context.getTypeSize(Context.CharTy))
  9140. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  9141. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9142. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  9143. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9144. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  9145. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9146. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  9147. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  9148. "Unhandled vector element size in vector compare");
  9149. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  9150. }
  9151. if (TypeSize == Context.getTypeSize(Context.LongLongTy))
  9152. return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
  9153. VectorType::GenericVector);
  9154. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9155. return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
  9156. VectorType::GenericVector);
  9157. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9158. return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
  9159. VectorType::GenericVector);
  9160. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9161. return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
  9162. VectorType::GenericVector);
  9163. assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
  9164. "Unhandled vector element size in vector compare");
  9165. return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
  9166. VectorType::GenericVector);
  9167. }
  9168. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  9169. /// operates on extended vector types. Instead of producing an IntTy result,
  9170. /// like a scalar comparison, a vector comparison produces a vector of integer
  9171. /// types.
  9172. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9173. SourceLocation Loc,
  9174. BinaryOperatorKind Opc) {
  9175. // Check to make sure we're operating on vectors of the same type and width,
  9176. // Allowing one side to be a scalar of element type.
  9177. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  9178. /*AllowBothBool*/true,
  9179. /*AllowBoolConversions*/getLangOpts().ZVector);
  9180. if (vType.isNull())
  9181. return vType;
  9182. QualType LHSType = LHS.get()->getType();
  9183. // If AltiVec, the comparison results in a numeric type, i.e.
  9184. // bool for C++, int for C
  9185. if (getLangOpts().AltiVec &&
  9186. vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  9187. return Context.getLogicalOperationType();
  9188. // For non-floating point types, check for self-comparisons of the form
  9189. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  9190. // often indicate logic errors in the program.
  9191. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9192. // Check for comparisons of floating point operands using != and ==.
  9193. if (BinaryOperator::isEqualityOp(Opc) &&
  9194. LHSType->hasFloatingRepresentation()) {
  9195. assert(RHS.get()->getType()->hasFloatingRepresentation());
  9196. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9197. }
  9198. // Return a signed type for the vector.
  9199. return GetSignedVectorType(vType);
  9200. }
  9201. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9202. SourceLocation Loc) {
  9203. // Ensure that either both operands are of the same vector type, or
  9204. // one operand is of a vector type and the other is of its element type.
  9205. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  9206. /*AllowBothBool*/true,
  9207. /*AllowBoolConversions*/false);
  9208. if (vType.isNull())
  9209. return InvalidOperands(Loc, LHS, RHS);
  9210. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  9211. vType->hasFloatingRepresentation())
  9212. return InvalidOperands(Loc, LHS, RHS);
  9213. // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
  9214. // usage of the logical operators && and || with vectors in C. This
  9215. // check could be notionally dropped.
  9216. if (!getLangOpts().CPlusPlus &&
  9217. !(isa<ExtVectorType>(vType->getAs<VectorType>())))
  9218. return InvalidLogicalVectorOperands(Loc, LHS, RHS);
  9219. return GetSignedVectorType(LHS.get()->getType());
  9220. }
  9221. inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
  9222. SourceLocation Loc,
  9223. BinaryOperatorKind Opc) {
  9224. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  9225. bool IsCompAssign =
  9226. Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
  9227. if (LHS.get()->getType()->isVectorType() ||
  9228. RHS.get()->getType()->isVectorType()) {
  9229. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  9230. RHS.get()->getType()->hasIntegerRepresentation())
  9231. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9232. /*AllowBothBool*/true,
  9233. /*AllowBoolConversions*/getLangOpts().ZVector);
  9234. return InvalidOperands(Loc, LHS, RHS);
  9235. }
  9236. if (Opc == BO_And)
  9237. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9238. ExprResult LHSResult = LHS, RHSResult = RHS;
  9239. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  9240. IsCompAssign);
  9241. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  9242. return QualType();
  9243. LHS = LHSResult.get();
  9244. RHS = RHSResult.get();
  9245. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  9246. return compType;
  9247. return InvalidOperands(Loc, LHS, RHS);
  9248. }
  9249. // C99 6.5.[13,14]
  9250. inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9251. SourceLocation Loc,
  9252. BinaryOperatorKind Opc) {
  9253. // Check vector operands differently.
  9254. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  9255. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  9256. // Diagnose cases where the user write a logical and/or but probably meant a
  9257. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  9258. // is a constant.
  9259. if (LHS.get()->getType()->isIntegerType() &&
  9260. !LHS.get()->getType()->isBooleanType() &&
  9261. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  9262. // Don't warn in macros or template instantiations.
  9263. !Loc.isMacroID() && !inTemplateInstantiation()) {
  9264. // If the RHS can be constant folded, and if it constant folds to something
  9265. // that isn't 0 or 1 (which indicate a potential logical operation that
  9266. // happened to fold to true/false) then warn.
  9267. // Parens on the RHS are ignored.
  9268. llvm::APSInt Result;
  9269. if (RHS.get()->EvaluateAsInt(Result, Context))
  9270. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  9271. !RHS.get()->getExprLoc().isMacroID()) ||
  9272. (Result != 0 && Result != 1)) {
  9273. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  9274. << RHS.get()->getSourceRange()
  9275. << (Opc == BO_LAnd ? "&&" : "||");
  9276. // Suggest replacing the logical operator with the bitwise version
  9277. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  9278. << (Opc == BO_LAnd ? "&" : "|")
  9279. << FixItHint::CreateReplacement(SourceRange(
  9280. Loc, getLocForEndOfToken(Loc)),
  9281. Opc == BO_LAnd ? "&" : "|");
  9282. if (Opc == BO_LAnd)
  9283. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  9284. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  9285. << FixItHint::CreateRemoval(
  9286. SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
  9287. RHS.get()->getLocEnd()));
  9288. }
  9289. }
  9290. if (!Context.getLangOpts().CPlusPlus) {
  9291. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  9292. // not operate on the built-in scalar and vector float types.
  9293. if (Context.getLangOpts().OpenCL &&
  9294. Context.getLangOpts().OpenCLVersion < 120) {
  9295. if (LHS.get()->getType()->isFloatingType() ||
  9296. RHS.get()->getType()->isFloatingType())
  9297. return InvalidOperands(Loc, LHS, RHS);
  9298. }
  9299. LHS = UsualUnaryConversions(LHS.get());
  9300. if (LHS.isInvalid())
  9301. return QualType();
  9302. RHS = UsualUnaryConversions(RHS.get());
  9303. if (RHS.isInvalid())
  9304. return QualType();
  9305. if (!LHS.get()->getType()->isScalarType() ||
  9306. !RHS.get()->getType()->isScalarType())
  9307. return InvalidOperands(Loc, LHS, RHS);
  9308. return Context.IntTy;
  9309. }
  9310. // The following is safe because we only use this method for
  9311. // non-overloadable operands.
  9312. // C++ [expr.log.and]p1
  9313. // C++ [expr.log.or]p1
  9314. // The operands are both contextually converted to type bool.
  9315. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  9316. if (LHSRes.isInvalid())
  9317. return InvalidOperands(Loc, LHS, RHS);
  9318. LHS = LHSRes;
  9319. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  9320. if (RHSRes.isInvalid())
  9321. return InvalidOperands(Loc, LHS, RHS);
  9322. RHS = RHSRes;
  9323. // C++ [expr.log.and]p2
  9324. // C++ [expr.log.or]p2
  9325. // The result is a bool.
  9326. return Context.BoolTy;
  9327. }
  9328. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  9329. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  9330. if (!ME) return false;
  9331. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  9332. ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
  9333. ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
  9334. if (!Base) return false;
  9335. return Base->getMethodDecl() != nullptr;
  9336. }
  9337. /// Is the given expression (which must be 'const') a reference to a
  9338. /// variable which was originally non-const, but which has become
  9339. /// 'const' due to being captured within a block?
  9340. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  9341. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  9342. assert(E->isLValue() && E->getType().isConstQualified());
  9343. E = E->IgnoreParens();
  9344. // Must be a reference to a declaration from an enclosing scope.
  9345. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  9346. if (!DRE) return NCCK_None;
  9347. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  9348. // The declaration must be a variable which is not declared 'const'.
  9349. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  9350. if (!var) return NCCK_None;
  9351. if (var->getType().isConstQualified()) return NCCK_None;
  9352. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  9353. // Decide whether the first capture was for a block or a lambda.
  9354. DeclContext *DC = S.CurContext, *Prev = nullptr;
  9355. // Decide whether the first capture was for a block or a lambda.
  9356. while (DC) {
  9357. // For init-capture, it is possible that the variable belongs to the
  9358. // template pattern of the current context.
  9359. if (auto *FD = dyn_cast<FunctionDecl>(DC))
  9360. if (var->isInitCapture() &&
  9361. FD->getTemplateInstantiationPattern() == var->getDeclContext())
  9362. break;
  9363. if (DC == var->getDeclContext())
  9364. break;
  9365. Prev = DC;
  9366. DC = DC->getParent();
  9367. }
  9368. // Unless we have an init-capture, we've gone one step too far.
  9369. if (!var->isInitCapture())
  9370. DC = Prev;
  9371. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  9372. }
  9373. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  9374. Ty = Ty.getNonReferenceType();
  9375. if (IsDereference && Ty->isPointerType())
  9376. Ty = Ty->getPointeeType();
  9377. return !Ty.isConstQualified();
  9378. }
  9379. // Update err_typecheck_assign_const and note_typecheck_assign_const
  9380. // when this enum is changed.
  9381. enum {
  9382. ConstFunction,
  9383. ConstVariable,
  9384. ConstMember,
  9385. ConstMethod,
  9386. NestedConstMember,
  9387. ConstUnknown, // Keep as last element
  9388. };
  9389. /// Emit the "read-only variable not assignable" error and print notes to give
  9390. /// more information about why the variable is not assignable, such as pointing
  9391. /// to the declaration of a const variable, showing that a method is const, or
  9392. /// that the function is returning a const reference.
  9393. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  9394. SourceLocation Loc) {
  9395. SourceRange ExprRange = E->getSourceRange();
  9396. // Only emit one error on the first const found. All other consts will emit
  9397. // a note to the error.
  9398. bool DiagnosticEmitted = false;
  9399. // Track if the current expression is the result of a dereference, and if the
  9400. // next checked expression is the result of a dereference.
  9401. bool IsDereference = false;
  9402. bool NextIsDereference = false;
  9403. // Loop to process MemberExpr chains.
  9404. while (true) {
  9405. IsDereference = NextIsDereference;
  9406. E = E->IgnoreImplicit()->IgnoreParenImpCasts();
  9407. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  9408. NextIsDereference = ME->isArrow();
  9409. const ValueDecl *VD = ME->getMemberDecl();
  9410. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  9411. // Mutable fields can be modified even if the class is const.
  9412. if (Field->isMutable()) {
  9413. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  9414. break;
  9415. }
  9416. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  9417. if (!DiagnosticEmitted) {
  9418. S.Diag(Loc, diag::err_typecheck_assign_const)
  9419. << ExprRange << ConstMember << false /*static*/ << Field
  9420. << Field->getType();
  9421. DiagnosticEmitted = true;
  9422. }
  9423. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9424. << ConstMember << false /*static*/ << Field << Field->getType()
  9425. << Field->getSourceRange();
  9426. }
  9427. E = ME->getBase();
  9428. continue;
  9429. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  9430. if (VDecl->getType().isConstQualified()) {
  9431. if (!DiagnosticEmitted) {
  9432. S.Diag(Loc, diag::err_typecheck_assign_const)
  9433. << ExprRange << ConstMember << true /*static*/ << VDecl
  9434. << VDecl->getType();
  9435. DiagnosticEmitted = true;
  9436. }
  9437. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9438. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  9439. << VDecl->getSourceRange();
  9440. }
  9441. // Static fields do not inherit constness from parents.
  9442. break;
  9443. }
  9444. break; // End MemberExpr
  9445. } else if (const ArraySubscriptExpr *ASE =
  9446. dyn_cast<ArraySubscriptExpr>(E)) {
  9447. E = ASE->getBase()->IgnoreParenImpCasts();
  9448. continue;
  9449. } else if (const ExtVectorElementExpr *EVE =
  9450. dyn_cast<ExtVectorElementExpr>(E)) {
  9451. E = EVE->getBase()->IgnoreParenImpCasts();
  9452. continue;
  9453. }
  9454. break;
  9455. }
  9456. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  9457. // Function calls
  9458. const FunctionDecl *FD = CE->getDirectCallee();
  9459. if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  9460. if (!DiagnosticEmitted) {
  9461. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  9462. << ConstFunction << FD;
  9463. DiagnosticEmitted = true;
  9464. }
  9465. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  9466. diag::note_typecheck_assign_const)
  9467. << ConstFunction << FD << FD->getReturnType()
  9468. << FD->getReturnTypeSourceRange();
  9469. }
  9470. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9471. // Point to variable declaration.
  9472. if (const ValueDecl *VD = DRE->getDecl()) {
  9473. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  9474. if (!DiagnosticEmitted) {
  9475. S.Diag(Loc, diag::err_typecheck_assign_const)
  9476. << ExprRange << ConstVariable << VD << VD->getType();
  9477. DiagnosticEmitted = true;
  9478. }
  9479. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9480. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  9481. }
  9482. }
  9483. } else if (isa<CXXThisExpr>(E)) {
  9484. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  9485. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  9486. if (MD->isConst()) {
  9487. if (!DiagnosticEmitted) {
  9488. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  9489. << ConstMethod << MD;
  9490. DiagnosticEmitted = true;
  9491. }
  9492. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  9493. << ConstMethod << MD << MD->getSourceRange();
  9494. }
  9495. }
  9496. }
  9497. }
  9498. if (DiagnosticEmitted)
  9499. return;
  9500. // Can't determine a more specific message, so display the generic error.
  9501. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  9502. }
  9503. enum OriginalExprKind {
  9504. OEK_Variable,
  9505. OEK_Member,
  9506. OEK_LValue
  9507. };
  9508. static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
  9509. const RecordType *Ty,
  9510. SourceLocation Loc, SourceRange Range,
  9511. OriginalExprKind OEK,
  9512. bool &DiagnosticEmitted,
  9513. bool IsNested = false) {
  9514. // We walk the record hierarchy breadth-first to ensure that we print
  9515. // diagnostics in field nesting order.
  9516. // First, check every field for constness.
  9517. for (const FieldDecl *Field : Ty->getDecl()->fields()) {
  9518. if (Field->getType().isConstQualified()) {
  9519. if (!DiagnosticEmitted) {
  9520. S.Diag(Loc, diag::err_typecheck_assign_const)
  9521. << Range << NestedConstMember << OEK << VD
  9522. << IsNested << Field;
  9523. DiagnosticEmitted = true;
  9524. }
  9525. S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
  9526. << NestedConstMember << IsNested << Field
  9527. << Field->getType() << Field->getSourceRange();
  9528. }
  9529. }
  9530. // Then, recurse.
  9531. for (const FieldDecl *Field : Ty->getDecl()->fields()) {
  9532. QualType FTy = Field->getType();
  9533. if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
  9534. DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
  9535. OEK, DiagnosticEmitted, true);
  9536. }
  9537. }
  9538. /// Emit an error for the case where a record we are trying to assign to has a
  9539. /// const-qualified field somewhere in its hierarchy.
  9540. static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
  9541. SourceLocation Loc) {
  9542. QualType Ty = E->getType();
  9543. assert(Ty->isRecordType() && "lvalue was not record?");
  9544. SourceRange Range = E->getSourceRange();
  9545. const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
  9546. bool DiagEmitted = false;
  9547. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  9548. DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
  9549. Range, OEK_Member, DiagEmitted);
  9550. else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  9551. DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
  9552. Range, OEK_Variable, DiagEmitted);
  9553. else
  9554. DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
  9555. Range, OEK_LValue, DiagEmitted);
  9556. if (!DiagEmitted)
  9557. DiagnoseConstAssignment(S, E, Loc);
  9558. }
  9559. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  9560. /// emit an error and return true. If so, return false.
  9561. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  9562. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  9563. S.CheckShadowingDeclModification(E, Loc);
  9564. SourceLocation OrigLoc = Loc;
  9565. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  9566. &Loc);
  9567. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  9568. IsLV = Expr::MLV_InvalidMessageExpression;
  9569. if (IsLV == Expr::MLV_Valid)
  9570. return false;
  9571. unsigned DiagID = 0;
  9572. bool NeedType = false;
  9573. switch (IsLV) { // C99 6.5.16p2
  9574. case Expr::MLV_ConstQualified:
  9575. // Use a specialized diagnostic when we're assigning to an object
  9576. // from an enclosing function or block.
  9577. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  9578. if (NCCK == NCCK_Block)
  9579. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  9580. else
  9581. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  9582. break;
  9583. }
  9584. // In ARC, use some specialized diagnostics for occasions where we
  9585. // infer 'const'. These are always pseudo-strong variables.
  9586. if (S.getLangOpts().ObjCAutoRefCount) {
  9587. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  9588. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  9589. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  9590. // Use the normal diagnostic if it's pseudo-__strong but the
  9591. // user actually wrote 'const'.
  9592. if (var->isARCPseudoStrong() &&
  9593. (!var->getTypeSourceInfo() ||
  9594. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  9595. // There are two pseudo-strong cases:
  9596. // - self
  9597. ObjCMethodDecl *method = S.getCurMethodDecl();
  9598. if (method && var == method->getSelfDecl())
  9599. DiagID = method->isClassMethod()
  9600. ? diag::err_typecheck_arc_assign_self_class_method
  9601. : diag::err_typecheck_arc_assign_self;
  9602. // - fast enumeration variables
  9603. else
  9604. DiagID = diag::err_typecheck_arr_assign_enumeration;
  9605. SourceRange Assign;
  9606. if (Loc != OrigLoc)
  9607. Assign = SourceRange(OrigLoc, OrigLoc);
  9608. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  9609. // We need to preserve the AST regardless, so migration tool
  9610. // can do its job.
  9611. return false;
  9612. }
  9613. }
  9614. }
  9615. // If none of the special cases above are triggered, then this is a
  9616. // simple const assignment.
  9617. if (DiagID == 0) {
  9618. DiagnoseConstAssignment(S, E, Loc);
  9619. return true;
  9620. }
  9621. break;
  9622. case Expr::MLV_ConstAddrSpace:
  9623. DiagnoseConstAssignment(S, E, Loc);
  9624. return true;
  9625. case Expr::MLV_ConstQualifiedField:
  9626. DiagnoseRecursiveConstFields(S, E, Loc);
  9627. return true;
  9628. case Expr::MLV_ArrayType:
  9629. case Expr::MLV_ArrayTemporary:
  9630. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  9631. NeedType = true;
  9632. break;
  9633. case Expr::MLV_NotObjectType:
  9634. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  9635. NeedType = true;
  9636. break;
  9637. case Expr::MLV_LValueCast:
  9638. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  9639. break;
  9640. case Expr::MLV_Valid:
  9641. llvm_unreachable("did not take early return for MLV_Valid");
  9642. case Expr::MLV_InvalidExpression:
  9643. case Expr::MLV_MemberFunction:
  9644. case Expr::MLV_ClassTemporary:
  9645. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  9646. break;
  9647. case Expr::MLV_IncompleteType:
  9648. case Expr::MLV_IncompleteVoidType:
  9649. return S.RequireCompleteType(Loc, E->getType(),
  9650. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  9651. case Expr::MLV_DuplicateVectorComponents:
  9652. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  9653. break;
  9654. case Expr::MLV_NoSetterProperty:
  9655. llvm_unreachable("readonly properties should be processed differently");
  9656. case Expr::MLV_InvalidMessageExpression:
  9657. DiagID = diag::err_readonly_message_assignment;
  9658. break;
  9659. case Expr::MLV_SubObjCPropertySetting:
  9660. DiagID = diag::err_no_subobject_property_setting;
  9661. break;
  9662. }
  9663. SourceRange Assign;
  9664. if (Loc != OrigLoc)
  9665. Assign = SourceRange(OrigLoc, OrigLoc);
  9666. if (NeedType)
  9667. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  9668. else
  9669. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  9670. return true;
  9671. }
  9672. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  9673. SourceLocation Loc,
  9674. Sema &Sema) {
  9675. if (Sema.inTemplateInstantiation())
  9676. return;
  9677. if (Sema.isUnevaluatedContext())
  9678. return;
  9679. if (Loc.isInvalid() || Loc.isMacroID())
  9680. return;
  9681. if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
  9682. return;
  9683. // C / C++ fields
  9684. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  9685. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  9686. if (ML && MR) {
  9687. if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
  9688. return;
  9689. const ValueDecl *LHSDecl =
  9690. cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
  9691. const ValueDecl *RHSDecl =
  9692. cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
  9693. if (LHSDecl != RHSDecl)
  9694. return;
  9695. if (LHSDecl->getType().isVolatileQualified())
  9696. return;
  9697. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  9698. if (RefTy->getPointeeType().isVolatileQualified())
  9699. return;
  9700. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  9701. }
  9702. // Objective-C instance variables
  9703. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  9704. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  9705. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  9706. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  9707. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  9708. if (RL && RR && RL->getDecl() == RR->getDecl())
  9709. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  9710. }
  9711. }
  9712. // C99 6.5.16.1
  9713. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  9714. SourceLocation Loc,
  9715. QualType CompoundType) {
  9716. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  9717. // Verify that LHS is a modifiable lvalue, and emit error if not.
  9718. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  9719. return QualType();
  9720. QualType LHSType = LHSExpr->getType();
  9721. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  9722. CompoundType;
  9723. // OpenCL v1.2 s6.1.1.1 p2:
  9724. // The half data type can only be used to declare a pointer to a buffer that
  9725. // contains half values
  9726. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  9727. LHSType->isHalfType()) {
  9728. Diag(Loc, diag::err_opencl_half_load_store) << 1
  9729. << LHSType.getUnqualifiedType();
  9730. return QualType();
  9731. }
  9732. AssignConvertType ConvTy;
  9733. if (CompoundType.isNull()) {
  9734. Expr *RHSCheck = RHS.get();
  9735. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  9736. QualType LHSTy(LHSType);
  9737. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  9738. if (RHS.isInvalid())
  9739. return QualType();
  9740. // Special case of NSObject attributes on c-style pointer types.
  9741. if (ConvTy == IncompatiblePointer &&
  9742. ((Context.isObjCNSObjectType(LHSType) &&
  9743. RHSType->isObjCObjectPointerType()) ||
  9744. (Context.isObjCNSObjectType(RHSType) &&
  9745. LHSType->isObjCObjectPointerType())))
  9746. ConvTy = Compatible;
  9747. if (ConvTy == Compatible &&
  9748. LHSType->isObjCObjectType())
  9749. Diag(Loc, diag::err_objc_object_assignment)
  9750. << LHSType;
  9751. // If the RHS is a unary plus or minus, check to see if they = and + are
  9752. // right next to each other. If so, the user may have typo'd "x =+ 4"
  9753. // instead of "x += 4".
  9754. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  9755. RHSCheck = ICE->getSubExpr();
  9756. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  9757. if ((UO->getOpcode() == UO_Plus ||
  9758. UO->getOpcode() == UO_Minus) &&
  9759. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  9760. // Only if the two operators are exactly adjacent.
  9761. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  9762. // And there is a space or other character before the subexpr of the
  9763. // unary +/-. We don't want to warn on "x=-1".
  9764. Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
  9765. UO->getSubExpr()->getLocStart().isFileID()) {
  9766. Diag(Loc, diag::warn_not_compound_assign)
  9767. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  9768. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  9769. }
  9770. }
  9771. if (ConvTy == Compatible) {
  9772. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  9773. // Warn about retain cycles where a block captures the LHS, but
  9774. // not if the LHS is a simple variable into which the block is
  9775. // being stored...unless that variable can be captured by reference!
  9776. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  9777. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  9778. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  9779. checkRetainCycles(LHSExpr, RHS.get());
  9780. }
  9781. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  9782. LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
  9783. // It is safe to assign a weak reference into a strong variable.
  9784. // Although this code can still have problems:
  9785. // id x = self.weakProp;
  9786. // id y = self.weakProp;
  9787. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  9788. // paths through the function. This should be revisited if
  9789. // -Wrepeated-use-of-weak is made flow-sensitive.
  9790. // For ObjCWeak only, we do not warn if the assign is to a non-weak
  9791. // variable, which will be valid for the current autorelease scope.
  9792. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  9793. RHS.get()->getLocStart()))
  9794. getCurFunction()->markSafeWeakUse(RHS.get());
  9795. } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
  9796. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  9797. }
  9798. }
  9799. } else {
  9800. // Compound assignment "x += y"
  9801. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  9802. }
  9803. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  9804. RHS.get(), AA_Assigning))
  9805. return QualType();
  9806. CheckForNullPointerDereference(*this, LHSExpr);
  9807. // C99 6.5.16p3: The type of an assignment expression is the type of the
  9808. // left operand unless the left operand has qualified type, in which case
  9809. // it is the unqualified version of the type of the left operand.
  9810. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  9811. // is converted to the type of the assignment expression (above).
  9812. // C++ 5.17p1: the type of the assignment expression is that of its left
  9813. // operand.
  9814. return (getLangOpts().CPlusPlus
  9815. ? LHSType : LHSType.getUnqualifiedType());
  9816. }
  9817. // Only ignore explicit casts to void.
  9818. static bool IgnoreCommaOperand(const Expr *E) {
  9819. E = E->IgnoreParens();
  9820. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  9821. if (CE->getCastKind() == CK_ToVoid) {
  9822. return true;
  9823. }
  9824. }
  9825. return false;
  9826. }
  9827. // Look for instances where it is likely the comma operator is confused with
  9828. // another operator. There is a whitelist of acceptable expressions for the
  9829. // left hand side of the comma operator, otherwise emit a warning.
  9830. void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
  9831. // No warnings in macros
  9832. if (Loc.isMacroID())
  9833. return;
  9834. // Don't warn in template instantiations.
  9835. if (inTemplateInstantiation())
  9836. return;
  9837. // Scope isn't fine-grained enough to whitelist the specific cases, so
  9838. // instead, skip more than needed, then call back into here with the
  9839. // CommaVisitor in SemaStmt.cpp.
  9840. // The whitelisted locations are the initialization and increment portions
  9841. // of a for loop. The additional checks are on the condition of
  9842. // if statements, do/while loops, and for loops.
  9843. const unsigned ForIncrementFlags =
  9844. Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
  9845. const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
  9846. const unsigned ScopeFlags = getCurScope()->getFlags();
  9847. if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
  9848. (ScopeFlags & ForInitFlags) == ForInitFlags)
  9849. return;
  9850. // If there are multiple comma operators used together, get the RHS of the
  9851. // of the comma operator as the LHS.
  9852. while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
  9853. if (BO->getOpcode() != BO_Comma)
  9854. break;
  9855. LHS = BO->getRHS();
  9856. }
  9857. // Only allow some expressions on LHS to not warn.
  9858. if (IgnoreCommaOperand(LHS))
  9859. return;
  9860. Diag(Loc, diag::warn_comma_operator);
  9861. Diag(LHS->getLocStart(), diag::note_cast_to_void)
  9862. << LHS->getSourceRange()
  9863. << FixItHint::CreateInsertion(LHS->getLocStart(),
  9864. LangOpts.CPlusPlus ? "static_cast<void>("
  9865. : "(void)(")
  9866. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
  9867. ")");
  9868. }
  9869. // C99 6.5.17
  9870. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  9871. SourceLocation Loc) {
  9872. LHS = S.CheckPlaceholderExpr(LHS.get());
  9873. RHS = S.CheckPlaceholderExpr(RHS.get());
  9874. if (LHS.isInvalid() || RHS.isInvalid())
  9875. return QualType();
  9876. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  9877. // operands, but not unary promotions.
  9878. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  9879. // So we treat the LHS as a ignored value, and in C++ we allow the
  9880. // containing site to determine what should be done with the RHS.
  9881. LHS = S.IgnoredValueConversions(LHS.get());
  9882. if (LHS.isInvalid())
  9883. return QualType();
  9884. S.DiagnoseUnusedExprResult(LHS.get());
  9885. if (!S.getLangOpts().CPlusPlus) {
  9886. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  9887. if (RHS.isInvalid())
  9888. return QualType();
  9889. if (!RHS.get()->getType()->isVoidType())
  9890. S.RequireCompleteType(Loc, RHS.get()->getType(),
  9891. diag::err_incomplete_type);
  9892. }
  9893. if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
  9894. S.DiagnoseCommaOperator(LHS.get(), Loc);
  9895. return RHS.get()->getType();
  9896. }
  9897. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  9898. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  9899. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  9900. ExprValueKind &VK,
  9901. ExprObjectKind &OK,
  9902. SourceLocation OpLoc,
  9903. bool IsInc, bool IsPrefix) {
  9904. if (Op->isTypeDependent())
  9905. return S.Context.DependentTy;
  9906. QualType ResType = Op->getType();
  9907. // Atomic types can be used for increment / decrement where the non-atomic
  9908. // versions can, so ignore the _Atomic() specifier for the purpose of
  9909. // checking.
  9910. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  9911. ResType = ResAtomicType->getValueType();
  9912. assert(!ResType.isNull() && "no type for increment/decrement expression");
  9913. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  9914. // Decrement of bool is not allowed.
  9915. if (!IsInc) {
  9916. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  9917. return QualType();
  9918. }
  9919. // Increment of bool sets it to true, but is deprecated.
  9920. S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
  9921. : diag::warn_increment_bool)
  9922. << Op->getSourceRange();
  9923. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  9924. // Error on enum increments and decrements in C++ mode
  9925. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  9926. return QualType();
  9927. } else if (ResType->isRealType()) {
  9928. // OK!
  9929. } else if (ResType->isPointerType()) {
  9930. // C99 6.5.2.4p2, 6.5.6p2
  9931. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  9932. return QualType();
  9933. } else if (ResType->isObjCObjectPointerType()) {
  9934. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  9935. // Otherwise, we just need a complete type.
  9936. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  9937. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  9938. return QualType();
  9939. } else if (ResType->isAnyComplexType()) {
  9940. // C99 does not support ++/-- on complex types, we allow as an extension.
  9941. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  9942. << ResType << Op->getSourceRange();
  9943. } else if (ResType->isPlaceholderType()) {
  9944. ExprResult PR = S.CheckPlaceholderExpr(Op);
  9945. if (PR.isInvalid()) return QualType();
  9946. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  9947. IsInc, IsPrefix);
  9948. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  9949. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  9950. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  9951. (ResType->getAs<VectorType>()->getVectorKind() !=
  9952. VectorType::AltiVecBool)) {
  9953. // The z vector extensions allow ++ and -- for non-bool vectors.
  9954. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  9955. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  9956. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  9957. } else {
  9958. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  9959. << ResType << int(IsInc) << Op->getSourceRange();
  9960. return QualType();
  9961. }
  9962. // At this point, we know we have a real, complex or pointer type.
  9963. // Now make sure the operand is a modifiable lvalue.
  9964. if (CheckForModifiableLvalue(Op, OpLoc, S))
  9965. return QualType();
  9966. // In C++, a prefix increment is the same type as the operand. Otherwise
  9967. // (in C or with postfix), the increment is the unqualified type of the
  9968. // operand.
  9969. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  9970. VK = VK_LValue;
  9971. OK = Op->getObjectKind();
  9972. return ResType;
  9973. } else {
  9974. VK = VK_RValue;
  9975. return ResType.getUnqualifiedType();
  9976. }
  9977. }
  9978. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  9979. /// This routine allows us to typecheck complex/recursive expressions
  9980. /// where the declaration is needed for type checking. We only need to
  9981. /// handle cases when the expression references a function designator
  9982. /// or is an lvalue. Here are some examples:
  9983. /// - &(x) => x
  9984. /// - &*****f => f for f a function designator.
  9985. /// - &s.xx => s
  9986. /// - &s.zz[1].yy -> s, if zz is an array
  9987. /// - *(x + 1) -> x, if x is an array
  9988. /// - &"123"[2] -> 0
  9989. /// - & __real__ x -> x
  9990. static ValueDecl *getPrimaryDecl(Expr *E) {
  9991. switch (E->getStmtClass()) {
  9992. case Stmt::DeclRefExprClass:
  9993. return cast<DeclRefExpr>(E)->getDecl();
  9994. case Stmt::MemberExprClass:
  9995. // If this is an arrow operator, the address is an offset from
  9996. // the base's value, so the object the base refers to is
  9997. // irrelevant.
  9998. if (cast<MemberExpr>(E)->isArrow())
  9999. return nullptr;
  10000. // Otherwise, the expression refers to a part of the base
  10001. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  10002. case Stmt::ArraySubscriptExprClass: {
  10003. // FIXME: This code shouldn't be necessary! We should catch the implicit
  10004. // promotion of register arrays earlier.
  10005. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  10006. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  10007. if (ICE->getSubExpr()->getType()->isArrayType())
  10008. return getPrimaryDecl(ICE->getSubExpr());
  10009. }
  10010. return nullptr;
  10011. }
  10012. case Stmt::UnaryOperatorClass: {
  10013. UnaryOperator *UO = cast<UnaryOperator>(E);
  10014. switch(UO->getOpcode()) {
  10015. case UO_Real:
  10016. case UO_Imag:
  10017. case UO_Extension:
  10018. return getPrimaryDecl(UO->getSubExpr());
  10019. default:
  10020. return nullptr;
  10021. }
  10022. }
  10023. case Stmt::ParenExprClass:
  10024. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  10025. case Stmt::ImplicitCastExprClass:
  10026. // If the result of an implicit cast is an l-value, we care about
  10027. // the sub-expression; otherwise, the result here doesn't matter.
  10028. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  10029. default:
  10030. return nullptr;
  10031. }
  10032. }
  10033. namespace {
  10034. enum {
  10035. AO_Bit_Field = 0,
  10036. AO_Vector_Element = 1,
  10037. AO_Property_Expansion = 2,
  10038. AO_Register_Variable = 3,
  10039. AO_No_Error = 4
  10040. };
  10041. }
  10042. /// Diagnose invalid operand for address of operations.
  10043. ///
  10044. /// \param Type The type of operand which cannot have its address taken.
  10045. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  10046. Expr *E, unsigned Type) {
  10047. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  10048. }
  10049. /// CheckAddressOfOperand - The operand of & must be either a function
  10050. /// designator or an lvalue designating an object. If it is an lvalue, the
  10051. /// object cannot be declared with storage class register or be a bit field.
  10052. /// Note: The usual conversions are *not* applied to the operand of the &
  10053. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  10054. /// In C++, the operand might be an overloaded function name, in which case
  10055. /// we allow the '&' but retain the overloaded-function type.
  10056. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  10057. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  10058. if (PTy->getKind() == BuiltinType::Overload) {
  10059. Expr *E = OrigOp.get()->IgnoreParens();
  10060. if (!isa<OverloadExpr>(E)) {
  10061. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  10062. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  10063. << OrigOp.get()->getSourceRange();
  10064. return QualType();
  10065. }
  10066. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  10067. if (isa<UnresolvedMemberExpr>(Ovl))
  10068. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  10069. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10070. << OrigOp.get()->getSourceRange();
  10071. return QualType();
  10072. }
  10073. return Context.OverloadTy;
  10074. }
  10075. if (PTy->getKind() == BuiltinType::UnknownAny)
  10076. return Context.UnknownAnyTy;
  10077. if (PTy->getKind() == BuiltinType::BoundMember) {
  10078. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10079. << OrigOp.get()->getSourceRange();
  10080. return QualType();
  10081. }
  10082. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  10083. if (OrigOp.isInvalid()) return QualType();
  10084. }
  10085. if (OrigOp.get()->isTypeDependent())
  10086. return Context.DependentTy;
  10087. assert(!OrigOp.get()->getType()->isPlaceholderType());
  10088. // Make sure to ignore parentheses in subsequent checks
  10089. Expr *op = OrigOp.get()->IgnoreParens();
  10090. // In OpenCL captures for blocks called as lambda functions
  10091. // are located in the private address space. Blocks used in
  10092. // enqueue_kernel can be located in a different address space
  10093. // depending on a vendor implementation. Thus preventing
  10094. // taking an address of the capture to avoid invalid AS casts.
  10095. if (LangOpts.OpenCL) {
  10096. auto* VarRef = dyn_cast<DeclRefExpr>(op);
  10097. if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
  10098. Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
  10099. return QualType();
  10100. }
  10101. }
  10102. if (getLangOpts().C99) {
  10103. // Implement C99-only parts of addressof rules.
  10104. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  10105. if (uOp->getOpcode() == UO_Deref)
  10106. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  10107. // (assuming the deref expression is valid).
  10108. return uOp->getSubExpr()->getType();
  10109. }
  10110. // Technically, there should be a check for array subscript
  10111. // expressions here, but the result of one is always an lvalue anyway.
  10112. }
  10113. ValueDecl *dcl = getPrimaryDecl(op);
  10114. if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
  10115. if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  10116. op->getLocStart()))
  10117. return QualType();
  10118. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  10119. unsigned AddressOfError = AO_No_Error;
  10120. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  10121. bool sfinae = (bool)isSFINAEContext();
  10122. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  10123. : diag::ext_typecheck_addrof_temporary)
  10124. << op->getType() << op->getSourceRange();
  10125. if (sfinae)
  10126. return QualType();
  10127. // Materialize the temporary as an lvalue so that we can take its address.
  10128. OrigOp = op =
  10129. CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  10130. } else if (isa<ObjCSelectorExpr>(op)) {
  10131. return Context.getPointerType(op->getType());
  10132. } else if (lval == Expr::LV_MemberFunction) {
  10133. // If it's an instance method, make a member pointer.
  10134. // The expression must have exactly the form &A::foo.
  10135. // If the underlying expression isn't a decl ref, give up.
  10136. if (!isa<DeclRefExpr>(op)) {
  10137. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10138. << OrigOp.get()->getSourceRange();
  10139. return QualType();
  10140. }
  10141. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  10142. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  10143. // The id-expression was parenthesized.
  10144. if (OrigOp.get() != DRE) {
  10145. Diag(OpLoc, diag::err_parens_pointer_member_function)
  10146. << OrigOp.get()->getSourceRange();
  10147. // The method was named without a qualifier.
  10148. } else if (!DRE->getQualifier()) {
  10149. if (MD->getParent()->getName().empty())
  10150. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10151. << op->getSourceRange();
  10152. else {
  10153. SmallString<32> Str;
  10154. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  10155. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10156. << op->getSourceRange()
  10157. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  10158. }
  10159. }
  10160. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  10161. if (isa<CXXDestructorDecl>(MD))
  10162. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  10163. QualType MPTy = Context.getMemberPointerType(
  10164. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  10165. // Under the MS ABI, lock down the inheritance model now.
  10166. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10167. (void)isCompleteType(OpLoc, MPTy);
  10168. return MPTy;
  10169. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  10170. // C99 6.5.3.2p1
  10171. // The operand must be either an l-value or a function designator
  10172. if (!op->getType()->isFunctionType()) {
  10173. // Use a special diagnostic for loads from property references.
  10174. if (isa<PseudoObjectExpr>(op)) {
  10175. AddressOfError = AO_Property_Expansion;
  10176. } else {
  10177. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  10178. << op->getType() << op->getSourceRange();
  10179. return QualType();
  10180. }
  10181. }
  10182. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  10183. // The operand cannot be a bit-field
  10184. AddressOfError = AO_Bit_Field;
  10185. } else if (op->getObjectKind() == OK_VectorComponent) {
  10186. // The operand cannot be an element of a vector
  10187. AddressOfError = AO_Vector_Element;
  10188. } else if (dcl) { // C99 6.5.3.2p1
  10189. // We have an lvalue with a decl. Make sure the decl is not declared
  10190. // with the register storage-class specifier.
  10191. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  10192. // in C++ it is not error to take address of a register
  10193. // variable (c++03 7.1.1P3)
  10194. if (vd->getStorageClass() == SC_Register &&
  10195. !getLangOpts().CPlusPlus) {
  10196. AddressOfError = AO_Register_Variable;
  10197. }
  10198. } else if (isa<MSPropertyDecl>(dcl)) {
  10199. AddressOfError = AO_Property_Expansion;
  10200. } else if (isa<FunctionTemplateDecl>(dcl)) {
  10201. return Context.OverloadTy;
  10202. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  10203. // Okay: we can take the address of a field.
  10204. // Could be a pointer to member, though, if there is an explicit
  10205. // scope qualifier for the class.
  10206. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  10207. DeclContext *Ctx = dcl->getDeclContext();
  10208. if (Ctx && Ctx->isRecord()) {
  10209. if (dcl->getType()->isReferenceType()) {
  10210. Diag(OpLoc,
  10211. diag::err_cannot_form_pointer_to_member_of_reference_type)
  10212. << dcl->getDeclName() << dcl->getType();
  10213. return QualType();
  10214. }
  10215. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  10216. Ctx = Ctx->getParent();
  10217. QualType MPTy = Context.getMemberPointerType(
  10218. op->getType(),
  10219. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  10220. // Under the MS ABI, lock down the inheritance model now.
  10221. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10222. (void)isCompleteType(OpLoc, MPTy);
  10223. return MPTy;
  10224. }
  10225. }
  10226. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
  10227. !isa<BindingDecl>(dcl))
  10228. llvm_unreachable("Unknown/unexpected decl type");
  10229. }
  10230. if (AddressOfError != AO_No_Error) {
  10231. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  10232. return QualType();
  10233. }
  10234. if (lval == Expr::LV_IncompleteVoidType) {
  10235. // Taking the address of a void variable is technically illegal, but we
  10236. // allow it in cases which are otherwise valid.
  10237. // Example: "extern void x; void* y = &x;".
  10238. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  10239. }
  10240. // If the operand has type "type", the result has type "pointer to type".
  10241. if (op->getType()->isObjCObjectType())
  10242. return Context.getObjCObjectPointerType(op->getType());
  10243. CheckAddressOfPackedMember(op);
  10244. return Context.getPointerType(op->getType());
  10245. }
  10246. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  10247. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  10248. if (!DRE)
  10249. return;
  10250. const Decl *D = DRE->getDecl();
  10251. if (!D)
  10252. return;
  10253. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  10254. if (!Param)
  10255. return;
  10256. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  10257. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  10258. return;
  10259. if (FunctionScopeInfo *FD = S.getCurFunction())
  10260. if (!FD->ModifiedNonNullParams.count(Param))
  10261. FD->ModifiedNonNullParams.insert(Param);
  10262. }
  10263. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  10264. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  10265. SourceLocation OpLoc) {
  10266. if (Op->isTypeDependent())
  10267. return S.Context.DependentTy;
  10268. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  10269. if (ConvResult.isInvalid())
  10270. return QualType();
  10271. Op = ConvResult.get();
  10272. QualType OpTy = Op->getType();
  10273. QualType Result;
  10274. if (isa<CXXReinterpretCastExpr>(Op)) {
  10275. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  10276. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  10277. Op->getSourceRange());
  10278. }
  10279. if (const PointerType *PT = OpTy->getAs<PointerType>())
  10280. {
  10281. Result = PT->getPointeeType();
  10282. }
  10283. else if (const ObjCObjectPointerType *OPT =
  10284. OpTy->getAs<ObjCObjectPointerType>())
  10285. Result = OPT->getPointeeType();
  10286. else {
  10287. ExprResult PR = S.CheckPlaceholderExpr(Op);
  10288. if (PR.isInvalid()) return QualType();
  10289. if (PR.get() != Op)
  10290. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  10291. }
  10292. if (Result.isNull()) {
  10293. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  10294. << OpTy << Op->getSourceRange();
  10295. return QualType();
  10296. }
  10297. // Note that per both C89 and C99, indirection is always legal, even if Result
  10298. // is an incomplete type or void. It would be possible to warn about
  10299. // dereferencing a void pointer, but it's completely well-defined, and such a
  10300. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  10301. // for pointers to 'void' but is fine for any other pointer type:
  10302. //
  10303. // C++ [expr.unary.op]p1:
  10304. // [...] the expression to which [the unary * operator] is applied shall
  10305. // be a pointer to an object type, or a pointer to a function type
  10306. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  10307. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  10308. << OpTy << Op->getSourceRange();
  10309. // Dereferences are usually l-values...
  10310. VK = VK_LValue;
  10311. // ...except that certain expressions are never l-values in C.
  10312. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  10313. VK = VK_RValue;
  10314. return Result;
  10315. }
  10316. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  10317. BinaryOperatorKind Opc;
  10318. switch (Kind) {
  10319. default: llvm_unreachable("Unknown binop!");
  10320. case tok::periodstar: Opc = BO_PtrMemD; break;
  10321. case tok::arrowstar: Opc = BO_PtrMemI; break;
  10322. case tok::star: Opc = BO_Mul; break;
  10323. case tok::slash: Opc = BO_Div; break;
  10324. case tok::percent: Opc = BO_Rem; break;
  10325. case tok::plus: Opc = BO_Add; break;
  10326. case tok::minus: Opc = BO_Sub; break;
  10327. case tok::lessless: Opc = BO_Shl; break;
  10328. case tok::greatergreater: Opc = BO_Shr; break;
  10329. case tok::lessequal: Opc = BO_LE; break;
  10330. case tok::less: Opc = BO_LT; break;
  10331. case tok::greaterequal: Opc = BO_GE; break;
  10332. case tok::greater: Opc = BO_GT; break;
  10333. case tok::exclaimequal: Opc = BO_NE; break;
  10334. case tok::equalequal: Opc = BO_EQ; break;
  10335. case tok::spaceship: Opc = BO_Cmp; break;
  10336. case tok::amp: Opc = BO_And; break;
  10337. case tok::caret: Opc = BO_Xor; break;
  10338. case tok::pipe: Opc = BO_Or; break;
  10339. case tok::ampamp: Opc = BO_LAnd; break;
  10340. case tok::pipepipe: Opc = BO_LOr; break;
  10341. case tok::equal: Opc = BO_Assign; break;
  10342. case tok::starequal: Opc = BO_MulAssign; break;
  10343. case tok::slashequal: Opc = BO_DivAssign; break;
  10344. case tok::percentequal: Opc = BO_RemAssign; break;
  10345. case tok::plusequal: Opc = BO_AddAssign; break;
  10346. case tok::minusequal: Opc = BO_SubAssign; break;
  10347. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  10348. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  10349. case tok::ampequal: Opc = BO_AndAssign; break;
  10350. case tok::caretequal: Opc = BO_XorAssign; break;
  10351. case tok::pipeequal: Opc = BO_OrAssign; break;
  10352. case tok::comma: Opc = BO_Comma; break;
  10353. }
  10354. return Opc;
  10355. }
  10356. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  10357. tok::TokenKind Kind) {
  10358. UnaryOperatorKind Opc;
  10359. switch (Kind) {
  10360. default: llvm_unreachable("Unknown unary op!");
  10361. case tok::plusplus: Opc = UO_PreInc; break;
  10362. case tok::minusminus: Opc = UO_PreDec; break;
  10363. case tok::amp: Opc = UO_AddrOf; break;
  10364. case tok::star: Opc = UO_Deref; break;
  10365. case tok::plus: Opc = UO_Plus; break;
  10366. case tok::minus: Opc = UO_Minus; break;
  10367. case tok::tilde: Opc = UO_Not; break;
  10368. case tok::exclaim: Opc = UO_LNot; break;
  10369. case tok::kw___real: Opc = UO_Real; break;
  10370. case tok::kw___imag: Opc = UO_Imag; break;
  10371. case tok::kw___extension__: Opc = UO_Extension; break;
  10372. }
  10373. return Opc;
  10374. }
  10375. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  10376. /// This warning suppressed in the event of macro expansions.
  10377. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  10378. SourceLocation OpLoc, bool IsBuiltin) {
  10379. if (S.inTemplateInstantiation())
  10380. return;
  10381. if (S.isUnevaluatedContext())
  10382. return;
  10383. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  10384. return;
  10385. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  10386. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  10387. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  10388. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  10389. if (!LHSDeclRef || !RHSDeclRef ||
  10390. LHSDeclRef->getLocation().isMacroID() ||
  10391. RHSDeclRef->getLocation().isMacroID())
  10392. return;
  10393. const ValueDecl *LHSDecl =
  10394. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  10395. const ValueDecl *RHSDecl =
  10396. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  10397. if (LHSDecl != RHSDecl)
  10398. return;
  10399. if (LHSDecl->getType().isVolatileQualified())
  10400. return;
  10401. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  10402. if (RefTy->getPointeeType().isVolatileQualified())
  10403. return;
  10404. S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
  10405. : diag::warn_self_assignment_overloaded)
  10406. << LHSDeclRef->getType() << LHSExpr->getSourceRange()
  10407. << RHSExpr->getSourceRange();
  10408. }
  10409. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  10410. /// is usually indicative of introspection within the Objective-C pointer.
  10411. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  10412. SourceLocation OpLoc) {
  10413. if (!S.getLangOpts().ObjC1)
  10414. return;
  10415. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  10416. const Expr *LHS = L.get();
  10417. const Expr *RHS = R.get();
  10418. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  10419. ObjCPointerExpr = LHS;
  10420. OtherExpr = RHS;
  10421. }
  10422. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  10423. ObjCPointerExpr = RHS;
  10424. OtherExpr = LHS;
  10425. }
  10426. // This warning is deliberately made very specific to reduce false
  10427. // positives with logic that uses '&' for hashing. This logic mainly
  10428. // looks for code trying to introspect into tagged pointers, which
  10429. // code should generally never do.
  10430. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  10431. unsigned Diag = diag::warn_objc_pointer_masking;
  10432. // Determine if we are introspecting the result of performSelectorXXX.
  10433. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  10434. // Special case messages to -performSelector and friends, which
  10435. // can return non-pointer values boxed in a pointer value.
  10436. // Some clients may wish to silence warnings in this subcase.
  10437. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  10438. Selector S = ME->getSelector();
  10439. StringRef SelArg0 = S.getNameForSlot(0);
  10440. if (SelArg0.startswith("performSelector"))
  10441. Diag = diag::warn_objc_pointer_masking_performSelector;
  10442. }
  10443. S.Diag(OpLoc, Diag)
  10444. << ObjCPointerExpr->getSourceRange();
  10445. }
  10446. }
  10447. static NamedDecl *getDeclFromExpr(Expr *E) {
  10448. if (!E)
  10449. return nullptr;
  10450. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  10451. return DRE->getDecl();
  10452. if (auto *ME = dyn_cast<MemberExpr>(E))
  10453. return ME->getMemberDecl();
  10454. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  10455. return IRE->getDecl();
  10456. return nullptr;
  10457. }
  10458. // This helper function promotes a binary operator's operands (which are of a
  10459. // half vector type) to a vector of floats and then truncates the result to
  10460. // a vector of either half or short.
  10461. static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
  10462. BinaryOperatorKind Opc, QualType ResultTy,
  10463. ExprValueKind VK, ExprObjectKind OK,
  10464. bool IsCompAssign, SourceLocation OpLoc,
  10465. FPOptions FPFeatures) {
  10466. auto &Context = S.getASTContext();
  10467. assert((isVector(ResultTy, Context.HalfTy) ||
  10468. isVector(ResultTy, Context.ShortTy)) &&
  10469. "Result must be a vector of half or short");
  10470. assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
  10471. isVector(RHS.get()->getType(), Context.HalfTy) &&
  10472. "both operands expected to be a half vector");
  10473. RHS = convertVector(RHS.get(), Context.FloatTy, S);
  10474. QualType BinOpResTy = RHS.get()->getType();
  10475. // If Opc is a comparison, ResultType is a vector of shorts. In that case,
  10476. // change BinOpResTy to a vector of ints.
  10477. if (isVector(ResultTy, Context.ShortTy))
  10478. BinOpResTy = S.GetSignedVectorType(BinOpResTy);
  10479. if (IsCompAssign)
  10480. return new (Context) CompoundAssignOperator(
  10481. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
  10482. OpLoc, FPFeatures);
  10483. LHS = convertVector(LHS.get(), Context.FloatTy, S);
  10484. auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
  10485. VK, OK, OpLoc, FPFeatures);
  10486. return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
  10487. }
  10488. static std::pair<ExprResult, ExprResult>
  10489. CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
  10490. Expr *RHSExpr) {
  10491. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  10492. if (!S.getLangOpts().CPlusPlus) {
  10493. // C cannot handle TypoExpr nodes on either side of a binop because it
  10494. // doesn't handle dependent types properly, so make sure any TypoExprs have
  10495. // been dealt with before checking the operands.
  10496. LHS = S.CorrectDelayedTyposInExpr(LHS);
  10497. RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
  10498. if (Opc != BO_Assign)
  10499. return ExprResult(E);
  10500. // Avoid correcting the RHS to the same Expr as the LHS.
  10501. Decl *D = getDeclFromExpr(E);
  10502. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  10503. });
  10504. }
  10505. return std::make_pair(LHS, RHS);
  10506. }
  10507. /// Returns true if conversion between vectors of halfs and vectors of floats
  10508. /// is needed.
  10509. static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
  10510. QualType SrcType) {
  10511. return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
  10512. !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
  10513. isVector(SrcType, Ctx.HalfTy);
  10514. }
  10515. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  10516. /// operator @p Opc at location @c TokLoc. This routine only supports
  10517. /// built-in operations; ActOnBinOp handles overloaded operators.
  10518. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  10519. BinaryOperatorKind Opc,
  10520. Expr *LHSExpr, Expr *RHSExpr) {
  10521. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  10522. // The syntax only allows initializer lists on the RHS of assignment,
  10523. // so we don't need to worry about accepting invalid code for
  10524. // non-assignment operators.
  10525. // C++11 5.17p9:
  10526. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  10527. // of x = {} is x = T().
  10528. InitializationKind Kind = InitializationKind::CreateDirectList(
  10529. RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd());
  10530. InitializedEntity Entity =
  10531. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  10532. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  10533. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  10534. if (Init.isInvalid())
  10535. return Init;
  10536. RHSExpr = Init.get();
  10537. }
  10538. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  10539. QualType ResultTy; // Result type of the binary operator.
  10540. // The following two variables are used for compound assignment operators
  10541. QualType CompLHSTy; // Type of LHS after promotions for computation
  10542. QualType CompResultTy; // Type of computation result
  10543. ExprValueKind VK = VK_RValue;
  10544. ExprObjectKind OK = OK_Ordinary;
  10545. bool ConvertHalfVec = false;
  10546. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  10547. if (!LHS.isUsable() || !RHS.isUsable())
  10548. return ExprError();
  10549. if (getLangOpts().OpenCL) {
  10550. QualType LHSTy = LHSExpr->getType();
  10551. QualType RHSTy = RHSExpr->getType();
  10552. // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
  10553. // the ATOMIC_VAR_INIT macro.
  10554. if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
  10555. SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  10556. if (BO_Assign == Opc)
  10557. Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
  10558. else
  10559. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  10560. return ExprError();
  10561. }
  10562. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  10563. // only with a builtin functions and therefore should be disallowed here.
  10564. if (LHSTy->isImageType() || RHSTy->isImageType() ||
  10565. LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
  10566. LHSTy->isPipeType() || RHSTy->isPipeType() ||
  10567. LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
  10568. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  10569. return ExprError();
  10570. }
  10571. }
  10572. switch (Opc) {
  10573. case BO_Assign:
  10574. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  10575. if (getLangOpts().CPlusPlus &&
  10576. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  10577. VK = LHS.get()->getValueKind();
  10578. OK = LHS.get()->getObjectKind();
  10579. }
  10580. if (!ResultTy.isNull()) {
  10581. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  10582. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  10583. }
  10584. RecordModifiableNonNullParam(*this, LHS.get());
  10585. break;
  10586. case BO_PtrMemD:
  10587. case BO_PtrMemI:
  10588. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  10589. Opc == BO_PtrMemI);
  10590. break;
  10591. case BO_Mul:
  10592. case BO_Div:
  10593. ConvertHalfVec = true;
  10594. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  10595. Opc == BO_Div);
  10596. break;
  10597. case BO_Rem:
  10598. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  10599. break;
  10600. case BO_Add:
  10601. ConvertHalfVec = true;
  10602. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  10603. break;
  10604. case BO_Sub:
  10605. ConvertHalfVec = true;
  10606. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  10607. break;
  10608. case BO_Shl:
  10609. case BO_Shr:
  10610. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  10611. break;
  10612. case BO_LE:
  10613. case BO_LT:
  10614. case BO_GE:
  10615. case BO_GT:
  10616. ConvertHalfVec = true;
  10617. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  10618. break;
  10619. case BO_EQ:
  10620. case BO_NE:
  10621. ConvertHalfVec = true;
  10622. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  10623. break;
  10624. case BO_Cmp:
  10625. ConvertHalfVec = true;
  10626. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  10627. assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
  10628. break;
  10629. case BO_And:
  10630. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  10631. LLVM_FALLTHROUGH;
  10632. case BO_Xor:
  10633. case BO_Or:
  10634. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  10635. break;
  10636. case BO_LAnd:
  10637. case BO_LOr:
  10638. ConvertHalfVec = true;
  10639. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  10640. break;
  10641. case BO_MulAssign:
  10642. case BO_DivAssign:
  10643. ConvertHalfVec = true;
  10644. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  10645. Opc == BO_DivAssign);
  10646. CompLHSTy = CompResultTy;
  10647. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10648. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10649. break;
  10650. case BO_RemAssign:
  10651. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  10652. CompLHSTy = CompResultTy;
  10653. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10654. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10655. break;
  10656. case BO_AddAssign:
  10657. ConvertHalfVec = true;
  10658. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  10659. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10660. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10661. break;
  10662. case BO_SubAssign:
  10663. ConvertHalfVec = true;
  10664. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  10665. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10666. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10667. break;
  10668. case BO_ShlAssign:
  10669. case BO_ShrAssign:
  10670. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  10671. CompLHSTy = CompResultTy;
  10672. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10673. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10674. break;
  10675. case BO_AndAssign:
  10676. case BO_OrAssign: // fallthrough
  10677. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  10678. LLVM_FALLTHROUGH;
  10679. case BO_XorAssign:
  10680. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  10681. CompLHSTy = CompResultTy;
  10682. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10683. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10684. break;
  10685. case BO_Comma:
  10686. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  10687. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  10688. VK = RHS.get()->getValueKind();
  10689. OK = RHS.get()->getObjectKind();
  10690. }
  10691. break;
  10692. }
  10693. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  10694. return ExprError();
  10695. // Some of the binary operations require promoting operands of half vector to
  10696. // float vectors and truncating the result back to half vector. For now, we do
  10697. // this only when HalfArgsAndReturn is set (that is, when the target is arm or
  10698. // arm64).
  10699. assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
  10700. isVector(LHS.get()->getType(), Context.HalfTy) &&
  10701. "both sides are half vectors or neither sides are");
  10702. ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
  10703. LHS.get()->getType());
  10704. // Check for array bounds violations for both sides of the BinaryOperator
  10705. CheckArrayAccess(LHS.get());
  10706. CheckArrayAccess(RHS.get());
  10707. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  10708. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  10709. &Context.Idents.get("object_setClass"),
  10710. SourceLocation(), LookupOrdinaryName);
  10711. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  10712. SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
  10713. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
  10714. FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
  10715. FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
  10716. FixItHint::CreateInsertion(RHSLocEnd, ")");
  10717. }
  10718. else
  10719. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  10720. }
  10721. else if (const ObjCIvarRefExpr *OIRE =
  10722. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  10723. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  10724. // Opc is not a compound assignment if CompResultTy is null.
  10725. if (CompResultTy.isNull()) {
  10726. if (ConvertHalfVec)
  10727. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
  10728. OpLoc, FPFeatures);
  10729. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  10730. OK, OpLoc, FPFeatures);
  10731. }
  10732. // Handle compound assignments.
  10733. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  10734. OK_ObjCProperty) {
  10735. VK = VK_LValue;
  10736. OK = LHS.get()->getObjectKind();
  10737. }
  10738. if (ConvertHalfVec)
  10739. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
  10740. OpLoc, FPFeatures);
  10741. return new (Context) CompoundAssignOperator(
  10742. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  10743. OpLoc, FPFeatures);
  10744. }
  10745. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  10746. /// operators are mixed in a way that suggests that the programmer forgot that
  10747. /// comparison operators have higher precedence. The most typical example of
  10748. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  10749. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  10750. SourceLocation OpLoc, Expr *LHSExpr,
  10751. Expr *RHSExpr) {
  10752. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  10753. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  10754. // Check that one of the sides is a comparison operator and the other isn't.
  10755. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  10756. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  10757. if (isLeftComp == isRightComp)
  10758. return;
  10759. // Bitwise operations are sometimes used as eager logical ops.
  10760. // Don't diagnose this.
  10761. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  10762. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  10763. if (isLeftBitwise || isRightBitwise)
  10764. return;
  10765. SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
  10766. OpLoc)
  10767. : SourceRange(OpLoc, RHSExpr->getLocEnd());
  10768. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  10769. SourceRange ParensRange = isLeftComp ?
  10770. SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
  10771. : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
  10772. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  10773. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  10774. SuggestParentheses(Self, OpLoc,
  10775. Self.PDiag(diag::note_precedence_silence) << OpStr,
  10776. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  10777. SuggestParentheses(Self, OpLoc,
  10778. Self.PDiag(diag::note_precedence_bitwise_first)
  10779. << BinaryOperator::getOpcodeStr(Opc),
  10780. ParensRange);
  10781. }
  10782. /// It accepts a '&&' expr that is inside a '||' one.
  10783. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  10784. /// in parentheses.
  10785. static void
  10786. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  10787. BinaryOperator *Bop) {
  10788. assert(Bop->getOpcode() == BO_LAnd);
  10789. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  10790. << Bop->getSourceRange() << OpLoc;
  10791. SuggestParentheses(Self, Bop->getOperatorLoc(),
  10792. Self.PDiag(diag::note_precedence_silence)
  10793. << Bop->getOpcodeStr(),
  10794. Bop->getSourceRange());
  10795. }
  10796. /// Returns true if the given expression can be evaluated as a constant
  10797. /// 'true'.
  10798. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  10799. bool Res;
  10800. return !E->isValueDependent() &&
  10801. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  10802. }
  10803. /// Returns true if the given expression can be evaluated as a constant
  10804. /// 'false'.
  10805. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  10806. bool Res;
  10807. return !E->isValueDependent() &&
  10808. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  10809. }
  10810. /// Look for '&&' in the left hand of a '||' expr.
  10811. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  10812. Expr *LHSExpr, Expr *RHSExpr) {
  10813. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  10814. if (Bop->getOpcode() == BO_LAnd) {
  10815. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  10816. if (EvaluatesAsFalse(S, RHSExpr))
  10817. return;
  10818. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  10819. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  10820. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  10821. } else if (Bop->getOpcode() == BO_LOr) {
  10822. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  10823. // If it's "a || b && 1 || c" we didn't warn earlier for
  10824. // "a || b && 1", but warn now.
  10825. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  10826. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  10827. }
  10828. }
  10829. }
  10830. }
  10831. /// Look for '&&' in the right hand of a '||' expr.
  10832. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  10833. Expr *LHSExpr, Expr *RHSExpr) {
  10834. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  10835. if (Bop->getOpcode() == BO_LAnd) {
  10836. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  10837. if (EvaluatesAsFalse(S, LHSExpr))
  10838. return;
  10839. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  10840. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  10841. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  10842. }
  10843. }
  10844. }
  10845. /// Look for bitwise op in the left or right hand of a bitwise op with
  10846. /// lower precedence and emit a diagnostic together with a fixit hint that wraps
  10847. /// the '&' expression in parentheses.
  10848. static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
  10849. SourceLocation OpLoc, Expr *SubExpr) {
  10850. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  10851. if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
  10852. S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
  10853. << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
  10854. << Bop->getSourceRange() << OpLoc;
  10855. SuggestParentheses(S, Bop->getOperatorLoc(),
  10856. S.PDiag(diag::note_precedence_silence)
  10857. << Bop->getOpcodeStr(),
  10858. Bop->getSourceRange());
  10859. }
  10860. }
  10861. }
  10862. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  10863. Expr *SubExpr, StringRef Shift) {
  10864. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  10865. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  10866. StringRef Op = Bop->getOpcodeStr();
  10867. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  10868. << Bop->getSourceRange() << OpLoc << Shift << Op;
  10869. SuggestParentheses(S, Bop->getOperatorLoc(),
  10870. S.PDiag(diag::note_precedence_silence) << Op,
  10871. Bop->getSourceRange());
  10872. }
  10873. }
  10874. }
  10875. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  10876. Expr *LHSExpr, Expr *RHSExpr) {
  10877. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  10878. if (!OCE)
  10879. return;
  10880. FunctionDecl *FD = OCE->getDirectCallee();
  10881. if (!FD || !FD->isOverloadedOperator())
  10882. return;
  10883. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  10884. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  10885. return;
  10886. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  10887. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  10888. << (Kind == OO_LessLess);
  10889. SuggestParentheses(S, OCE->getOperatorLoc(),
  10890. S.PDiag(diag::note_precedence_silence)
  10891. << (Kind == OO_LessLess ? "<<" : ">>"),
  10892. OCE->getSourceRange());
  10893. SuggestParentheses(S, OpLoc,
  10894. S.PDiag(diag::note_evaluate_comparison_first),
  10895. SourceRange(OCE->getArg(1)->getLocStart(),
  10896. RHSExpr->getLocEnd()));
  10897. }
  10898. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  10899. /// precedence.
  10900. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  10901. SourceLocation OpLoc, Expr *LHSExpr,
  10902. Expr *RHSExpr){
  10903. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  10904. if (BinaryOperator::isBitwiseOp(Opc))
  10905. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  10906. // Diagnose "arg1 & arg2 | arg3"
  10907. if ((Opc == BO_Or || Opc == BO_Xor) &&
  10908. !OpLoc.isMacroID()/* Don't warn in macros. */) {
  10909. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
  10910. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
  10911. }
  10912. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  10913. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  10914. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  10915. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  10916. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  10917. }
  10918. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  10919. || Opc == BO_Shr) {
  10920. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  10921. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  10922. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  10923. }
  10924. // Warn on overloaded shift operators and comparisons, such as:
  10925. // cout << 5 == 4;
  10926. if (BinaryOperator::isComparisonOp(Opc))
  10927. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  10928. }
  10929. // Binary Operators. 'Tok' is the token for the operator.
  10930. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  10931. tok::TokenKind Kind,
  10932. Expr *LHSExpr, Expr *RHSExpr) {
  10933. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  10934. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  10935. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  10936. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  10937. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  10938. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  10939. }
  10940. /// Build an overloaded binary operator expression in the given scope.
  10941. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  10942. BinaryOperatorKind Opc,
  10943. Expr *LHS, Expr *RHS) {
  10944. switch (Opc) {
  10945. case BO_Assign:
  10946. case BO_DivAssign:
  10947. case BO_RemAssign:
  10948. case BO_SubAssign:
  10949. case BO_AndAssign:
  10950. case BO_OrAssign:
  10951. case BO_XorAssign:
  10952. DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
  10953. CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
  10954. break;
  10955. default:
  10956. break;
  10957. }
  10958. // Find all of the overloaded operators visible from this
  10959. // point. We perform both an operator-name lookup from the local
  10960. // scope and an argument-dependent lookup based on the types of
  10961. // the arguments.
  10962. UnresolvedSet<16> Functions;
  10963. OverloadedOperatorKind OverOp
  10964. = BinaryOperator::getOverloadedOperator(Opc);
  10965. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  10966. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  10967. RHS->getType(), Functions);
  10968. // Build the (potentially-overloaded, potentially-dependent)
  10969. // binary operation.
  10970. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  10971. }
  10972. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  10973. BinaryOperatorKind Opc,
  10974. Expr *LHSExpr, Expr *RHSExpr) {
  10975. ExprResult LHS, RHS;
  10976. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  10977. if (!LHS.isUsable() || !RHS.isUsable())
  10978. return ExprError();
  10979. LHSExpr = LHS.get();
  10980. RHSExpr = RHS.get();
  10981. // We want to end up calling one of checkPseudoObjectAssignment
  10982. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  10983. // both expressions are overloadable or either is type-dependent),
  10984. // or CreateBuiltinBinOp (in any other case). We also want to get
  10985. // any placeholder types out of the way.
  10986. // Handle pseudo-objects in the LHS.
  10987. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  10988. // Assignments with a pseudo-object l-value need special analysis.
  10989. if (pty->getKind() == BuiltinType::PseudoObject &&
  10990. BinaryOperator::isAssignmentOp(Opc))
  10991. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  10992. // Don't resolve overloads if the other type is overloadable.
  10993. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
  10994. // We can't actually test that if we still have a placeholder,
  10995. // though. Fortunately, none of the exceptions we see in that
  10996. // code below are valid when the LHS is an overload set. Note
  10997. // that an overload set can be dependently-typed, but it never
  10998. // instantiates to having an overloadable type.
  10999. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11000. if (resolvedRHS.isInvalid()) return ExprError();
  11001. RHSExpr = resolvedRHS.get();
  11002. if (RHSExpr->isTypeDependent() ||
  11003. RHSExpr->getType()->isOverloadableType())
  11004. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11005. }
  11006. // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
  11007. // template, diagnose the missing 'template' keyword instead of diagnosing
  11008. // an invalid use of a bound member function.
  11009. //
  11010. // Note that "A::x < b" might be valid if 'b' has an overloadable type due
  11011. // to C++1z [over.over]/1.4, but we already checked for that case above.
  11012. if (Opc == BO_LT && inTemplateInstantiation() &&
  11013. (pty->getKind() == BuiltinType::BoundMember ||
  11014. pty->getKind() == BuiltinType::Overload)) {
  11015. auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
  11016. if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
  11017. std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
  11018. return isa<FunctionTemplateDecl>(ND);
  11019. })) {
  11020. Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
  11021. : OE->getNameLoc(),
  11022. diag::err_template_kw_missing)
  11023. << OE->getName().getAsString() << "";
  11024. return ExprError();
  11025. }
  11026. }
  11027. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  11028. if (LHS.isInvalid()) return ExprError();
  11029. LHSExpr = LHS.get();
  11030. }
  11031. // Handle pseudo-objects in the RHS.
  11032. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  11033. // An overload in the RHS can potentially be resolved by the type
  11034. // being assigned to.
  11035. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  11036. if (getLangOpts().CPlusPlus &&
  11037. (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
  11038. LHSExpr->getType()->isOverloadableType()))
  11039. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11040. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11041. }
  11042. // Don't resolve overloads if the other type is overloadable.
  11043. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
  11044. LHSExpr->getType()->isOverloadableType())
  11045. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11046. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11047. if (!resolvedRHS.isUsable()) return ExprError();
  11048. RHSExpr = resolvedRHS.get();
  11049. }
  11050. if (getLangOpts().CPlusPlus) {
  11051. // If either expression is type-dependent, always build an
  11052. // overloaded op.
  11053. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  11054. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11055. // Otherwise, build an overloaded op if either expression has an
  11056. // overloadable type.
  11057. if (LHSExpr->getType()->isOverloadableType() ||
  11058. RHSExpr->getType()->isOverloadableType())
  11059. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11060. }
  11061. // Build a built-in binary operation.
  11062. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11063. }
  11064. static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
  11065. if (T.isNull() || T->isDependentType())
  11066. return false;
  11067. if (!T->isPromotableIntegerType())
  11068. return true;
  11069. return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
  11070. }
  11071. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  11072. UnaryOperatorKind Opc,
  11073. Expr *InputExpr) {
  11074. ExprResult Input = InputExpr;
  11075. ExprValueKind VK = VK_RValue;
  11076. ExprObjectKind OK = OK_Ordinary;
  11077. QualType resultType;
  11078. bool CanOverflow = false;
  11079. bool ConvertHalfVec = false;
  11080. if (getLangOpts().OpenCL) {
  11081. QualType Ty = InputExpr->getType();
  11082. // The only legal unary operation for atomics is '&'.
  11083. if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
  11084. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  11085. // only with a builtin functions and therefore should be disallowed here.
  11086. (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
  11087. || Ty->isBlockPointerType())) {
  11088. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11089. << InputExpr->getType()
  11090. << Input.get()->getSourceRange());
  11091. }
  11092. }
  11093. switch (Opc) {
  11094. case UO_PreInc:
  11095. case UO_PreDec:
  11096. case UO_PostInc:
  11097. case UO_PostDec:
  11098. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  11099. OpLoc,
  11100. Opc == UO_PreInc ||
  11101. Opc == UO_PostInc,
  11102. Opc == UO_PreInc ||
  11103. Opc == UO_PreDec);
  11104. CanOverflow = isOverflowingIntegerType(Context, resultType);
  11105. break;
  11106. case UO_AddrOf:
  11107. resultType = CheckAddressOfOperand(Input, OpLoc);
  11108. RecordModifiableNonNullParam(*this, InputExpr);
  11109. break;
  11110. case UO_Deref: {
  11111. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11112. if (Input.isInvalid()) return ExprError();
  11113. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  11114. break;
  11115. }
  11116. case UO_Plus:
  11117. case UO_Minus:
  11118. CanOverflow = Opc == UO_Minus &&
  11119. isOverflowingIntegerType(Context, Input.get()->getType());
  11120. Input = UsualUnaryConversions(Input.get());
  11121. if (Input.isInvalid()) return ExprError();
  11122. // Unary plus and minus require promoting an operand of half vector to a
  11123. // float vector and truncating the result back to a half vector. For now, we
  11124. // do this only when HalfArgsAndReturns is set (that is, when the target is
  11125. // arm or arm64).
  11126. ConvertHalfVec =
  11127. needsConversionOfHalfVec(true, Context, Input.get()->getType());
  11128. // If the operand is a half vector, promote it to a float vector.
  11129. if (ConvertHalfVec)
  11130. Input = convertVector(Input.get(), Context.FloatTy, *this);
  11131. resultType = Input.get()->getType();
  11132. if (resultType->isDependentType())
  11133. break;
  11134. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  11135. break;
  11136. else if (resultType->isVectorType() &&
  11137. // The z vector extensions don't allow + or - with bool vectors.
  11138. (!Context.getLangOpts().ZVector ||
  11139. resultType->getAs<VectorType>()->getVectorKind() !=
  11140. VectorType::AltiVecBool))
  11141. break;
  11142. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  11143. Opc == UO_Plus &&
  11144. resultType->isPointerType())
  11145. break;
  11146. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11147. << resultType << Input.get()->getSourceRange());
  11148. case UO_Not: // bitwise complement
  11149. Input = UsualUnaryConversions(Input.get());
  11150. if (Input.isInvalid())
  11151. return ExprError();
  11152. resultType = Input.get()->getType();
  11153. if (resultType->isDependentType())
  11154. break;
  11155. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  11156. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  11157. // C99 does not support '~' for complex conjugation.
  11158. Diag(OpLoc, diag::ext_integer_complement_complex)
  11159. << resultType << Input.get()->getSourceRange();
  11160. else if (resultType->hasIntegerRepresentation())
  11161. break;
  11162. else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
  11163. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  11164. // on vector float types.
  11165. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  11166. if (!T->isIntegerType())
  11167. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11168. << resultType << Input.get()->getSourceRange());
  11169. } else {
  11170. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11171. << resultType << Input.get()->getSourceRange());
  11172. }
  11173. break;
  11174. case UO_LNot: // logical negation
  11175. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  11176. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11177. if (Input.isInvalid()) return ExprError();
  11178. resultType = Input.get()->getType();
  11179. // Though we still have to promote half FP to float...
  11180. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  11181. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  11182. resultType = Context.FloatTy;
  11183. }
  11184. if (resultType->isDependentType())
  11185. break;
  11186. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  11187. // C99 6.5.3.3p1: ok, fallthrough;
  11188. if (Context.getLangOpts().CPlusPlus) {
  11189. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  11190. // operand contextually converted to bool.
  11191. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  11192. ScalarTypeToBooleanCastKind(resultType));
  11193. } else if (Context.getLangOpts().OpenCL &&
  11194. Context.getLangOpts().OpenCLVersion < 120) {
  11195. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  11196. // operate on scalar float types.
  11197. if (!resultType->isIntegerType() && !resultType->isPointerType())
  11198. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11199. << resultType << Input.get()->getSourceRange());
  11200. }
  11201. } else if (resultType->isExtVectorType()) {
  11202. if (Context.getLangOpts().OpenCL &&
  11203. Context.getLangOpts().OpenCLVersion < 120) {
  11204. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  11205. // operate on vector float types.
  11206. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  11207. if (!T->isIntegerType())
  11208. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11209. << resultType << Input.get()->getSourceRange());
  11210. }
  11211. // Vector logical not returns the signed variant of the operand type.
  11212. resultType = GetSignedVectorType(resultType);
  11213. break;
  11214. } else {
  11215. // FIXME: GCC's vector extension permits the usage of '!' with a vector
  11216. // type in C++. We should allow that here too.
  11217. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11218. << resultType << Input.get()->getSourceRange());
  11219. }
  11220. // LNot always has type int. C99 6.5.3.3p5.
  11221. // In C++, it's bool. C++ 5.3.1p8
  11222. resultType = Context.getLogicalOperationType();
  11223. break;
  11224. case UO_Real:
  11225. case UO_Imag:
  11226. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  11227. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  11228. // complex l-values to ordinary l-values and all other values to r-values.
  11229. if (Input.isInvalid()) return ExprError();
  11230. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  11231. if (Input.get()->getValueKind() != VK_RValue &&
  11232. Input.get()->getObjectKind() == OK_Ordinary)
  11233. VK = Input.get()->getValueKind();
  11234. } else if (!getLangOpts().CPlusPlus) {
  11235. // In C, a volatile scalar is read by __imag. In C++, it is not.
  11236. Input = DefaultLvalueConversion(Input.get());
  11237. }
  11238. break;
  11239. case UO_Extension:
  11240. resultType = Input.get()->getType();
  11241. VK = Input.get()->getValueKind();
  11242. OK = Input.get()->getObjectKind();
  11243. break;
  11244. case UO_Coawait:
  11245. // It's unnecessary to represent the pass-through operator co_await in the
  11246. // AST; just return the input expression instead.
  11247. assert(!Input.get()->getType()->isDependentType() &&
  11248. "the co_await expression must be non-dependant before "
  11249. "building operator co_await");
  11250. return Input;
  11251. }
  11252. if (resultType.isNull() || Input.isInvalid())
  11253. return ExprError();
  11254. // Check for array bounds violations in the operand of the UnaryOperator,
  11255. // except for the '*' and '&' operators that have to be handled specially
  11256. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  11257. // that are explicitly defined as valid by the standard).
  11258. if (Opc != UO_AddrOf && Opc != UO_Deref)
  11259. CheckArrayAccess(Input.get());
  11260. auto *UO = new (Context)
  11261. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
  11262. // Convert the result back to a half vector.
  11263. if (ConvertHalfVec)
  11264. return convertVector(UO, Context.HalfTy, *this);
  11265. return UO;
  11266. }
  11267. /// Determine whether the given expression is a qualified member
  11268. /// access expression, of a form that could be turned into a pointer to member
  11269. /// with the address-of operator.
  11270. static bool isQualifiedMemberAccess(Expr *E) {
  11271. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  11272. if (!DRE->getQualifier())
  11273. return false;
  11274. ValueDecl *VD = DRE->getDecl();
  11275. if (!VD->isCXXClassMember())
  11276. return false;
  11277. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  11278. return true;
  11279. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  11280. return Method->isInstance();
  11281. return false;
  11282. }
  11283. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  11284. if (!ULE->getQualifier())
  11285. return false;
  11286. for (NamedDecl *D : ULE->decls()) {
  11287. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  11288. if (Method->isInstance())
  11289. return true;
  11290. } else {
  11291. // Overload set does not contain methods.
  11292. break;
  11293. }
  11294. }
  11295. return false;
  11296. }
  11297. return false;
  11298. }
  11299. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  11300. UnaryOperatorKind Opc, Expr *Input) {
  11301. // First things first: handle placeholders so that the
  11302. // overloaded-operator check considers the right type.
  11303. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  11304. // Increment and decrement of pseudo-object references.
  11305. if (pty->getKind() == BuiltinType::PseudoObject &&
  11306. UnaryOperator::isIncrementDecrementOp(Opc))
  11307. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  11308. // extension is always a builtin operator.
  11309. if (Opc == UO_Extension)
  11310. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11311. // & gets special logic for several kinds of placeholder.
  11312. // The builtin code knows what to do.
  11313. if (Opc == UO_AddrOf &&
  11314. (pty->getKind() == BuiltinType::Overload ||
  11315. pty->getKind() == BuiltinType::UnknownAny ||
  11316. pty->getKind() == BuiltinType::BoundMember))
  11317. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11318. // Anything else needs to be handled now.
  11319. ExprResult Result = CheckPlaceholderExpr(Input);
  11320. if (Result.isInvalid()) return ExprError();
  11321. Input = Result.get();
  11322. }
  11323. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  11324. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  11325. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  11326. // Find all of the overloaded operators visible from this
  11327. // point. We perform both an operator-name lookup from the local
  11328. // scope and an argument-dependent lookup based on the types of
  11329. // the arguments.
  11330. UnresolvedSet<16> Functions;
  11331. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  11332. if (S && OverOp != OO_None)
  11333. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  11334. Functions);
  11335. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  11336. }
  11337. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11338. }
  11339. // Unary Operators. 'Tok' is the token for the operator.
  11340. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  11341. tok::TokenKind Op, Expr *Input) {
  11342. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  11343. }
  11344. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  11345. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  11346. LabelDecl *TheDecl) {
  11347. TheDecl->markUsed(Context);
  11348. // Create the AST node. The address of a label always has type 'void*'.
  11349. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  11350. Context.getPointerType(Context.VoidTy));
  11351. }
  11352. /// Given the last statement in a statement-expression, check whether
  11353. /// the result is a producing expression (like a call to an
  11354. /// ns_returns_retained function) and, if so, rebuild it to hoist the
  11355. /// release out of the full-expression. Otherwise, return null.
  11356. /// Cannot fail.
  11357. static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
  11358. // Should always be wrapped with one of these.
  11359. ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
  11360. if (!cleanups) return nullptr;
  11361. ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
  11362. if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
  11363. return nullptr;
  11364. // Splice out the cast. This shouldn't modify any interesting
  11365. // features of the statement.
  11366. Expr *producer = cast->getSubExpr();
  11367. assert(producer->getType() == cast->getType());
  11368. assert(producer->getValueKind() == cast->getValueKind());
  11369. cleanups->setSubExpr(producer);
  11370. return cleanups;
  11371. }
  11372. void Sema::ActOnStartStmtExpr() {
  11373. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11374. }
  11375. void Sema::ActOnStmtExprError() {
  11376. // Note that function is also called by TreeTransform when leaving a
  11377. // StmtExpr scope without rebuilding anything.
  11378. DiscardCleanupsInEvaluationContext();
  11379. PopExpressionEvaluationContext();
  11380. }
  11381. ExprResult
  11382. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  11383. SourceLocation RPLoc) { // "({..})"
  11384. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  11385. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  11386. if (hasAnyUnrecoverableErrorsInThisFunction())
  11387. DiscardCleanupsInEvaluationContext();
  11388. assert(!Cleanup.exprNeedsCleanups() &&
  11389. "cleanups within StmtExpr not correctly bound!");
  11390. PopExpressionEvaluationContext();
  11391. // FIXME: there are a variety of strange constraints to enforce here, for
  11392. // example, it is not possible to goto into a stmt expression apparently.
  11393. // More semantic analysis is needed.
  11394. // If there are sub-stmts in the compound stmt, take the type of the last one
  11395. // as the type of the stmtexpr.
  11396. QualType Ty = Context.VoidTy;
  11397. bool StmtExprMayBindToTemp = false;
  11398. if (!Compound->body_empty()) {
  11399. Stmt *LastStmt = Compound->body_back();
  11400. LabelStmt *LastLabelStmt = nullptr;
  11401. // If LastStmt is a label, skip down through into the body.
  11402. while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
  11403. LastLabelStmt = Label;
  11404. LastStmt = Label->getSubStmt();
  11405. }
  11406. if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
  11407. // Do function/array conversion on the last expression, but not
  11408. // lvalue-to-rvalue. However, initialize an unqualified type.
  11409. ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
  11410. if (LastExpr.isInvalid())
  11411. return ExprError();
  11412. Ty = LastExpr.get()->getType().getUnqualifiedType();
  11413. if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
  11414. // In ARC, if the final expression ends in a consume, splice
  11415. // the consume out and bind it later. In the alternate case
  11416. // (when dealing with a retainable type), the result
  11417. // initialization will create a produce. In both cases the
  11418. // result will be +1, and we'll need to balance that out with
  11419. // a bind.
  11420. if (Expr *rebuiltLastStmt
  11421. = maybeRebuildARCConsumingStmt(LastExpr.get())) {
  11422. LastExpr = rebuiltLastStmt;
  11423. } else {
  11424. LastExpr = PerformCopyInitialization(
  11425. InitializedEntity::InitializeResult(LPLoc,
  11426. Ty,
  11427. false),
  11428. SourceLocation(),
  11429. LastExpr);
  11430. }
  11431. if (LastExpr.isInvalid())
  11432. return ExprError();
  11433. if (LastExpr.get() != nullptr) {
  11434. if (!LastLabelStmt)
  11435. Compound->setLastStmt(LastExpr.get());
  11436. else
  11437. LastLabelStmt->setSubStmt(LastExpr.get());
  11438. StmtExprMayBindToTemp = true;
  11439. }
  11440. }
  11441. }
  11442. }
  11443. // FIXME: Check that expression type is complete/non-abstract; statement
  11444. // expressions are not lvalues.
  11445. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  11446. if (StmtExprMayBindToTemp)
  11447. return MaybeBindToTemporary(ResStmtExpr);
  11448. return ResStmtExpr;
  11449. }
  11450. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  11451. TypeSourceInfo *TInfo,
  11452. ArrayRef<OffsetOfComponent> Components,
  11453. SourceLocation RParenLoc) {
  11454. QualType ArgTy = TInfo->getType();
  11455. bool Dependent = ArgTy->isDependentType();
  11456. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  11457. // We must have at least one component that refers to the type, and the first
  11458. // one is known to be a field designator. Verify that the ArgTy represents
  11459. // a struct/union/class.
  11460. if (!Dependent && !ArgTy->isRecordType())
  11461. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  11462. << ArgTy << TypeRange);
  11463. // Type must be complete per C99 7.17p3 because a declaring a variable
  11464. // with an incomplete type would be ill-formed.
  11465. if (!Dependent
  11466. && RequireCompleteType(BuiltinLoc, ArgTy,
  11467. diag::err_offsetof_incomplete_type, TypeRange))
  11468. return ExprError();
  11469. bool DidWarnAboutNonPOD = false;
  11470. QualType CurrentType = ArgTy;
  11471. SmallVector<OffsetOfNode, 4> Comps;
  11472. SmallVector<Expr*, 4> Exprs;
  11473. for (const OffsetOfComponent &OC : Components) {
  11474. if (OC.isBrackets) {
  11475. // Offset of an array sub-field. TODO: Should we allow vector elements?
  11476. if (!CurrentType->isDependentType()) {
  11477. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  11478. if(!AT)
  11479. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  11480. << CurrentType);
  11481. CurrentType = AT->getElementType();
  11482. } else
  11483. CurrentType = Context.DependentTy;
  11484. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  11485. if (IdxRval.isInvalid())
  11486. return ExprError();
  11487. Expr *Idx = IdxRval.get();
  11488. // The expression must be an integral expression.
  11489. // FIXME: An integral constant expression?
  11490. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  11491. !Idx->getType()->isIntegerType())
  11492. return ExprError(Diag(Idx->getLocStart(),
  11493. diag::err_typecheck_subscript_not_integer)
  11494. << Idx->getSourceRange());
  11495. // Record this array index.
  11496. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  11497. Exprs.push_back(Idx);
  11498. continue;
  11499. }
  11500. // Offset of a field.
  11501. if (CurrentType->isDependentType()) {
  11502. // We have the offset of a field, but we can't look into the dependent
  11503. // type. Just record the identifier of the field.
  11504. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  11505. CurrentType = Context.DependentTy;
  11506. continue;
  11507. }
  11508. // We need to have a complete type to look into.
  11509. if (RequireCompleteType(OC.LocStart, CurrentType,
  11510. diag::err_offsetof_incomplete_type))
  11511. return ExprError();
  11512. // Look for the designated field.
  11513. const RecordType *RC = CurrentType->getAs<RecordType>();
  11514. if (!RC)
  11515. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  11516. << CurrentType);
  11517. RecordDecl *RD = RC->getDecl();
  11518. // C++ [lib.support.types]p5:
  11519. // The macro offsetof accepts a restricted set of type arguments in this
  11520. // International Standard. type shall be a POD structure or a POD union
  11521. // (clause 9).
  11522. // C++11 [support.types]p4:
  11523. // If type is not a standard-layout class (Clause 9), the results are
  11524. // undefined.
  11525. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  11526. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  11527. unsigned DiagID =
  11528. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  11529. : diag::ext_offsetof_non_pod_type;
  11530. if (!IsSafe && !DidWarnAboutNonPOD &&
  11531. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  11532. PDiag(DiagID)
  11533. << SourceRange(Components[0].LocStart, OC.LocEnd)
  11534. << CurrentType))
  11535. DidWarnAboutNonPOD = true;
  11536. }
  11537. // Look for the field.
  11538. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  11539. LookupQualifiedName(R, RD);
  11540. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  11541. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  11542. if (!MemberDecl) {
  11543. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  11544. MemberDecl = IndirectMemberDecl->getAnonField();
  11545. }
  11546. if (!MemberDecl)
  11547. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  11548. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  11549. OC.LocEnd));
  11550. // C99 7.17p3:
  11551. // (If the specified member is a bit-field, the behavior is undefined.)
  11552. //
  11553. // We diagnose this as an error.
  11554. if (MemberDecl->isBitField()) {
  11555. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  11556. << MemberDecl->getDeclName()
  11557. << SourceRange(BuiltinLoc, RParenLoc);
  11558. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  11559. return ExprError();
  11560. }
  11561. RecordDecl *Parent = MemberDecl->getParent();
  11562. if (IndirectMemberDecl)
  11563. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  11564. // If the member was found in a base class, introduce OffsetOfNodes for
  11565. // the base class indirections.
  11566. CXXBasePaths Paths;
  11567. if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
  11568. Paths)) {
  11569. if (Paths.getDetectedVirtual()) {
  11570. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  11571. << MemberDecl->getDeclName()
  11572. << SourceRange(BuiltinLoc, RParenLoc);
  11573. return ExprError();
  11574. }
  11575. CXXBasePath &Path = Paths.front();
  11576. for (const CXXBasePathElement &B : Path)
  11577. Comps.push_back(OffsetOfNode(B.Base));
  11578. }
  11579. if (IndirectMemberDecl) {
  11580. for (auto *FI : IndirectMemberDecl->chain()) {
  11581. assert(isa<FieldDecl>(FI));
  11582. Comps.push_back(OffsetOfNode(OC.LocStart,
  11583. cast<FieldDecl>(FI), OC.LocEnd));
  11584. }
  11585. } else
  11586. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  11587. CurrentType = MemberDecl->getType().getNonReferenceType();
  11588. }
  11589. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  11590. Comps, Exprs, RParenLoc);
  11591. }
  11592. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  11593. SourceLocation BuiltinLoc,
  11594. SourceLocation TypeLoc,
  11595. ParsedType ParsedArgTy,
  11596. ArrayRef<OffsetOfComponent> Components,
  11597. SourceLocation RParenLoc) {
  11598. TypeSourceInfo *ArgTInfo;
  11599. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  11600. if (ArgTy.isNull())
  11601. return ExprError();
  11602. if (!ArgTInfo)
  11603. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  11604. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
  11605. }
  11606. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  11607. Expr *CondExpr,
  11608. Expr *LHSExpr, Expr *RHSExpr,
  11609. SourceLocation RPLoc) {
  11610. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  11611. ExprValueKind VK = VK_RValue;
  11612. ExprObjectKind OK = OK_Ordinary;
  11613. QualType resType;
  11614. bool ValueDependent = false;
  11615. bool CondIsTrue = false;
  11616. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  11617. resType = Context.DependentTy;
  11618. ValueDependent = true;
  11619. } else {
  11620. // The conditional expression is required to be a constant expression.
  11621. llvm::APSInt condEval(32);
  11622. ExprResult CondICE
  11623. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  11624. diag::err_typecheck_choose_expr_requires_constant, false);
  11625. if (CondICE.isInvalid())
  11626. return ExprError();
  11627. CondExpr = CondICE.get();
  11628. CondIsTrue = condEval.getZExtValue();
  11629. // If the condition is > zero, then the AST type is the same as the LHSExpr.
  11630. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  11631. resType = ActiveExpr->getType();
  11632. ValueDependent = ActiveExpr->isValueDependent();
  11633. VK = ActiveExpr->getValueKind();
  11634. OK = ActiveExpr->getObjectKind();
  11635. }
  11636. return new (Context)
  11637. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  11638. CondIsTrue, resType->isDependentType(), ValueDependent);
  11639. }
  11640. //===----------------------------------------------------------------------===//
  11641. // Clang Extensions.
  11642. //===----------------------------------------------------------------------===//
  11643. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  11644. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  11645. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  11646. if (LangOpts.CPlusPlus) {
  11647. Decl *ManglingContextDecl;
  11648. if (MangleNumberingContext *MCtx =
  11649. getCurrentMangleNumberContext(Block->getDeclContext(),
  11650. ManglingContextDecl)) {
  11651. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  11652. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  11653. }
  11654. }
  11655. PushBlockScope(CurScope, Block);
  11656. CurContext->addDecl(Block);
  11657. if (CurScope)
  11658. PushDeclContext(CurScope, Block);
  11659. else
  11660. CurContext = Block;
  11661. getCurBlock()->HasImplicitReturnType = true;
  11662. // Enter a new evaluation context to insulate the block from any
  11663. // cleanups from the enclosing full-expression.
  11664. PushExpressionEvaluationContext(
  11665. ExpressionEvaluationContext::PotentiallyEvaluated);
  11666. }
  11667. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  11668. Scope *CurScope) {
  11669. assert(ParamInfo.getIdentifier() == nullptr &&
  11670. "block-id should have no identifier!");
  11671. assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
  11672. BlockScopeInfo *CurBlock = getCurBlock();
  11673. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  11674. QualType T = Sig->getType();
  11675. // FIXME: We should allow unexpanded parameter packs here, but that would,
  11676. // in turn, make the block expression contain unexpanded parameter packs.
  11677. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  11678. // Drop the parameters.
  11679. FunctionProtoType::ExtProtoInfo EPI;
  11680. EPI.HasTrailingReturn = false;
  11681. EPI.TypeQuals |= DeclSpec::TQ_const;
  11682. T = Context.getFunctionType(Context.DependentTy, None, EPI);
  11683. Sig = Context.getTrivialTypeSourceInfo(T);
  11684. }
  11685. // GetTypeForDeclarator always produces a function type for a block
  11686. // literal signature. Furthermore, it is always a FunctionProtoType
  11687. // unless the function was written with a typedef.
  11688. assert(T->isFunctionType() &&
  11689. "GetTypeForDeclarator made a non-function block signature");
  11690. // Look for an explicit signature in that function type.
  11691. FunctionProtoTypeLoc ExplicitSignature;
  11692. if ((ExplicitSignature =
  11693. Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
  11694. // Check whether that explicit signature was synthesized by
  11695. // GetTypeForDeclarator. If so, don't save that as part of the
  11696. // written signature.
  11697. if (ExplicitSignature.getLocalRangeBegin() ==
  11698. ExplicitSignature.getLocalRangeEnd()) {
  11699. // This would be much cheaper if we stored TypeLocs instead of
  11700. // TypeSourceInfos.
  11701. TypeLoc Result = ExplicitSignature.getReturnLoc();
  11702. unsigned Size = Result.getFullDataSize();
  11703. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  11704. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  11705. ExplicitSignature = FunctionProtoTypeLoc();
  11706. }
  11707. }
  11708. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  11709. CurBlock->FunctionType = T;
  11710. const FunctionType *Fn = T->getAs<FunctionType>();
  11711. QualType RetTy = Fn->getReturnType();
  11712. bool isVariadic =
  11713. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  11714. CurBlock->TheDecl->setIsVariadic(isVariadic);
  11715. // Context.DependentTy is used as a placeholder for a missing block
  11716. // return type. TODO: what should we do with declarators like:
  11717. // ^ * { ... }
  11718. // If the answer is "apply template argument deduction"....
  11719. if (RetTy != Context.DependentTy) {
  11720. CurBlock->ReturnType = RetTy;
  11721. CurBlock->TheDecl->setBlockMissingReturnType(false);
  11722. CurBlock->HasImplicitReturnType = false;
  11723. }
  11724. // Push block parameters from the declarator if we had them.
  11725. SmallVector<ParmVarDecl*, 8> Params;
  11726. if (ExplicitSignature) {
  11727. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  11728. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  11729. if (Param->getIdentifier() == nullptr &&
  11730. !Param->isImplicit() &&
  11731. !Param->isInvalidDecl() &&
  11732. !getLangOpts().CPlusPlus)
  11733. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  11734. Params.push_back(Param);
  11735. }
  11736. // Fake up parameter variables if we have a typedef, like
  11737. // ^ fntype { ... }
  11738. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  11739. for (const auto &I : Fn->param_types()) {
  11740. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  11741. CurBlock->TheDecl, ParamInfo.getLocStart(), I);
  11742. Params.push_back(Param);
  11743. }
  11744. }
  11745. // Set the parameters on the block decl.
  11746. if (!Params.empty()) {
  11747. CurBlock->TheDecl->setParams(Params);
  11748. CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
  11749. /*CheckParameterNames=*/false);
  11750. }
  11751. // Finally we can process decl attributes.
  11752. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  11753. // Put the parameter variables in scope.
  11754. for (auto AI : CurBlock->TheDecl->parameters()) {
  11755. AI->setOwningFunction(CurBlock->TheDecl);
  11756. // If this has an identifier, add it to the scope stack.
  11757. if (AI->getIdentifier()) {
  11758. CheckShadow(CurBlock->TheScope, AI);
  11759. PushOnScopeChains(AI, CurBlock->TheScope);
  11760. }
  11761. }
  11762. }
  11763. /// ActOnBlockError - If there is an error parsing a block, this callback
  11764. /// is invoked to pop the information about the block from the action impl.
  11765. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  11766. // Leave the expression-evaluation context.
  11767. DiscardCleanupsInEvaluationContext();
  11768. PopExpressionEvaluationContext();
  11769. // Pop off CurBlock, handle nested blocks.
  11770. PopDeclContext();
  11771. PopFunctionScopeInfo();
  11772. }
  11773. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  11774. /// literal was successfully completed. ^(int x){...}
  11775. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  11776. Stmt *Body, Scope *CurScope) {
  11777. // If blocks are disabled, emit an error.
  11778. if (!LangOpts.Blocks)
  11779. Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
  11780. // Leave the expression-evaluation context.
  11781. if (hasAnyUnrecoverableErrorsInThisFunction())
  11782. DiscardCleanupsInEvaluationContext();
  11783. assert(!Cleanup.exprNeedsCleanups() &&
  11784. "cleanups within block not correctly bound!");
  11785. PopExpressionEvaluationContext();
  11786. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  11787. if (BSI->HasImplicitReturnType)
  11788. deduceClosureReturnType(*BSI);
  11789. PopDeclContext();
  11790. QualType RetTy = Context.VoidTy;
  11791. if (!BSI->ReturnType.isNull())
  11792. RetTy = BSI->ReturnType;
  11793. bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
  11794. QualType BlockTy;
  11795. // Set the captured variables on the block.
  11796. // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
  11797. SmallVector<BlockDecl::Capture, 4> Captures;
  11798. for (Capture &Cap : BSI->Captures) {
  11799. if (Cap.isThisCapture())
  11800. continue;
  11801. BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
  11802. Cap.isNested(), Cap.getInitExpr());
  11803. Captures.push_back(NewCap);
  11804. }
  11805. BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
  11806. // If the user wrote a function type in some form, try to use that.
  11807. if (!BSI->FunctionType.isNull()) {
  11808. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  11809. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  11810. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  11811. // Turn protoless block types into nullary block types.
  11812. if (isa<FunctionNoProtoType>(FTy)) {
  11813. FunctionProtoType::ExtProtoInfo EPI;
  11814. EPI.ExtInfo = Ext;
  11815. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  11816. // Otherwise, if we don't need to change anything about the function type,
  11817. // preserve its sugar structure.
  11818. } else if (FTy->getReturnType() == RetTy &&
  11819. (!NoReturn || FTy->getNoReturnAttr())) {
  11820. BlockTy = BSI->FunctionType;
  11821. // Otherwise, make the minimal modifications to the function type.
  11822. } else {
  11823. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  11824. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  11825. EPI.TypeQuals = 0; // FIXME: silently?
  11826. EPI.ExtInfo = Ext;
  11827. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  11828. }
  11829. // If we don't have a function type, just build one from nothing.
  11830. } else {
  11831. FunctionProtoType::ExtProtoInfo EPI;
  11832. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  11833. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  11834. }
  11835. DiagnoseUnusedParameters(BSI->TheDecl->parameters());
  11836. BlockTy = Context.getBlockPointerType(BlockTy);
  11837. // If needed, diagnose invalid gotos and switches in the block.
  11838. if (getCurFunction()->NeedsScopeChecking() &&
  11839. !PP.isCodeCompletionEnabled())
  11840. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  11841. BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
  11842. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  11843. DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
  11844. // Try to apply the named return value optimization. We have to check again
  11845. // if we can do this, though, because blocks keep return statements around
  11846. // to deduce an implicit return type.
  11847. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  11848. !BSI->TheDecl->isDependentContext())
  11849. computeNRVO(Body, BSI);
  11850. BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
  11851. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  11852. PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
  11853. // If the block isn't obviously global, i.e. it captures anything at
  11854. // all, then we need to do a few things in the surrounding context:
  11855. if (Result->getBlockDecl()->hasCaptures()) {
  11856. // First, this expression has a new cleanup object.
  11857. ExprCleanupObjects.push_back(Result->getBlockDecl());
  11858. Cleanup.setExprNeedsCleanups(true);
  11859. // It also gets a branch-protected scope if any of the captured
  11860. // variables needs destruction.
  11861. for (const auto &CI : Result->getBlockDecl()->captures()) {
  11862. const VarDecl *var = CI.getVariable();
  11863. if (var->getType().isDestructedType() != QualType::DK_none) {
  11864. setFunctionHasBranchProtectedScope();
  11865. break;
  11866. }
  11867. }
  11868. }
  11869. return Result;
  11870. }
  11871. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
  11872. SourceLocation RPLoc) {
  11873. TypeSourceInfo *TInfo;
  11874. GetTypeFromParser(Ty, &TInfo);
  11875. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  11876. }
  11877. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  11878. Expr *E, TypeSourceInfo *TInfo,
  11879. SourceLocation RPLoc) {
  11880. Expr *OrigExpr = E;
  11881. bool IsMS = false;
  11882. // CUDA device code does not support varargs.
  11883. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  11884. if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
  11885. CUDAFunctionTarget T = IdentifyCUDATarget(F);
  11886. if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
  11887. return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
  11888. }
  11889. }
  11890. // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
  11891. // as Microsoft ABI on an actual Microsoft platform, where
  11892. // __builtin_ms_va_list and __builtin_va_list are the same.)
  11893. if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
  11894. Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
  11895. QualType MSVaListType = Context.getBuiltinMSVaListType();
  11896. if (Context.hasSameType(MSVaListType, E->getType())) {
  11897. if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
  11898. return ExprError();
  11899. IsMS = true;
  11900. }
  11901. }
  11902. // Get the va_list type
  11903. QualType VaListType = Context.getBuiltinVaListType();
  11904. if (!IsMS) {
  11905. if (VaListType->isArrayType()) {
  11906. // Deal with implicit array decay; for example, on x86-64,
  11907. // va_list is an array, but it's supposed to decay to
  11908. // a pointer for va_arg.
  11909. VaListType = Context.getArrayDecayedType(VaListType);
  11910. // Make sure the input expression also decays appropriately.
  11911. ExprResult Result = UsualUnaryConversions(E);
  11912. if (Result.isInvalid())
  11913. return ExprError();
  11914. E = Result.get();
  11915. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  11916. // If va_list is a record type and we are compiling in C++ mode,
  11917. // check the argument using reference binding.
  11918. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  11919. Context, Context.getLValueReferenceType(VaListType), false);
  11920. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  11921. if (Init.isInvalid())
  11922. return ExprError();
  11923. E = Init.getAs<Expr>();
  11924. } else {
  11925. // Otherwise, the va_list argument must be an l-value because
  11926. // it is modified by va_arg.
  11927. if (!E->isTypeDependent() &&
  11928. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  11929. return ExprError();
  11930. }
  11931. }
  11932. if (!IsMS && !E->isTypeDependent() &&
  11933. !Context.hasSameType(VaListType, E->getType()))
  11934. return ExprError(Diag(E->getLocStart(),
  11935. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  11936. << OrigExpr->getType() << E->getSourceRange());
  11937. if (!TInfo->getType()->isDependentType()) {
  11938. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  11939. diag::err_second_parameter_to_va_arg_incomplete,
  11940. TInfo->getTypeLoc()))
  11941. return ExprError();
  11942. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  11943. TInfo->getType(),
  11944. diag::err_second_parameter_to_va_arg_abstract,
  11945. TInfo->getTypeLoc()))
  11946. return ExprError();
  11947. if (!TInfo->getType().isPODType(Context)) {
  11948. Diag(TInfo->getTypeLoc().getBeginLoc(),
  11949. TInfo->getType()->isObjCLifetimeType()
  11950. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  11951. : diag::warn_second_parameter_to_va_arg_not_pod)
  11952. << TInfo->getType()
  11953. << TInfo->getTypeLoc().getSourceRange();
  11954. }
  11955. // Check for va_arg where arguments of the given type will be promoted
  11956. // (i.e. this va_arg is guaranteed to have undefined behavior).
  11957. QualType PromoteType;
  11958. if (TInfo->getType()->isPromotableIntegerType()) {
  11959. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  11960. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  11961. PromoteType = QualType();
  11962. }
  11963. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  11964. PromoteType = Context.DoubleTy;
  11965. if (!PromoteType.isNull())
  11966. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  11967. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  11968. << TInfo->getType()
  11969. << PromoteType
  11970. << TInfo->getTypeLoc().getSourceRange());
  11971. }
  11972. QualType T = TInfo->getType().getNonLValueExprType(Context);
  11973. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
  11974. }
  11975. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  11976. // The type of __null will be int or long, depending on the size of
  11977. // pointers on the target.
  11978. QualType Ty;
  11979. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  11980. if (pw == Context.getTargetInfo().getIntWidth())
  11981. Ty = Context.IntTy;
  11982. else if (pw == Context.getTargetInfo().getLongWidth())
  11983. Ty = Context.LongTy;
  11984. else if (pw == Context.getTargetInfo().getLongLongWidth())
  11985. Ty = Context.LongLongTy;
  11986. else {
  11987. llvm_unreachable("I don't know size of pointer!");
  11988. }
  11989. return new (Context) GNUNullExpr(Ty, TokenLoc);
  11990. }
  11991. bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
  11992. bool Diagnose) {
  11993. if (!getLangOpts().ObjC1)
  11994. return false;
  11995. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  11996. if (!PT)
  11997. return false;
  11998. if (!PT->isObjCIdType()) {
  11999. // Check if the destination is the 'NSString' interface.
  12000. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  12001. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  12002. return false;
  12003. }
  12004. // Ignore any parens, implicit casts (should only be
  12005. // array-to-pointer decays), and not-so-opaque values. The last is
  12006. // important for making this trigger for property assignments.
  12007. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  12008. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  12009. if (OV->getSourceExpr())
  12010. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  12011. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  12012. if (!SL || !SL->isAscii())
  12013. return false;
  12014. if (Diagnose) {
  12015. Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
  12016. << FixItHint::CreateInsertion(SL->getLocStart(), "@");
  12017. Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
  12018. }
  12019. return true;
  12020. }
  12021. static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
  12022. const Expr *SrcExpr) {
  12023. if (!DstType->isFunctionPointerType() ||
  12024. !SrcExpr->getType()->isFunctionType())
  12025. return false;
  12026. auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
  12027. if (!DRE)
  12028. return false;
  12029. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  12030. if (!FD)
  12031. return false;
  12032. return !S.checkAddressOfFunctionIsAvailable(FD,
  12033. /*Complain=*/true,
  12034. SrcExpr->getLocStart());
  12035. }
  12036. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  12037. SourceLocation Loc,
  12038. QualType DstType, QualType SrcType,
  12039. Expr *SrcExpr, AssignmentAction Action,
  12040. bool *Complained) {
  12041. if (Complained)
  12042. *Complained = false;
  12043. // Decode the result (notice that AST's are still created for extensions).
  12044. bool CheckInferredResultType = false;
  12045. bool isInvalid = false;
  12046. unsigned DiagKind = 0;
  12047. FixItHint Hint;
  12048. ConversionFixItGenerator ConvHints;
  12049. bool MayHaveConvFixit = false;
  12050. bool MayHaveFunctionDiff = false;
  12051. const ObjCInterfaceDecl *IFace = nullptr;
  12052. const ObjCProtocolDecl *PDecl = nullptr;
  12053. switch (ConvTy) {
  12054. case Compatible:
  12055. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  12056. return false;
  12057. case PointerToInt:
  12058. DiagKind = diag::ext_typecheck_convert_pointer_int;
  12059. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12060. MayHaveConvFixit = true;
  12061. break;
  12062. case IntToPointer:
  12063. DiagKind = diag::ext_typecheck_convert_int_pointer;
  12064. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12065. MayHaveConvFixit = true;
  12066. break;
  12067. case IncompatiblePointer:
  12068. if (Action == AA_Passing_CFAudited)
  12069. DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
  12070. else if (SrcType->isFunctionPointerType() &&
  12071. DstType->isFunctionPointerType())
  12072. DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
  12073. else
  12074. DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
  12075. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  12076. SrcType->isObjCObjectPointerType();
  12077. if (Hint.isNull() && !CheckInferredResultType) {
  12078. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12079. }
  12080. else if (CheckInferredResultType) {
  12081. SrcType = SrcType.getUnqualifiedType();
  12082. DstType = DstType.getUnqualifiedType();
  12083. }
  12084. MayHaveConvFixit = true;
  12085. break;
  12086. case IncompatiblePointerSign:
  12087. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  12088. break;
  12089. case FunctionVoidPointer:
  12090. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  12091. break;
  12092. case IncompatiblePointerDiscardsQualifiers: {
  12093. // Perform array-to-pointer decay if necessary.
  12094. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  12095. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  12096. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  12097. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  12098. DiagKind = diag::err_typecheck_incompatible_address_space;
  12099. break;
  12100. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  12101. DiagKind = diag::err_typecheck_incompatible_ownership;
  12102. break;
  12103. }
  12104. llvm_unreachable("unknown error case for discarding qualifiers!");
  12105. // fallthrough
  12106. }
  12107. case CompatiblePointerDiscardsQualifiers:
  12108. // If the qualifiers lost were because we were applying the
  12109. // (deprecated) C++ conversion from a string literal to a char*
  12110. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  12111. // Ideally, this check would be performed in
  12112. // checkPointerTypesForAssignment. However, that would require a
  12113. // bit of refactoring (so that the second argument is an
  12114. // expression, rather than a type), which should be done as part
  12115. // of a larger effort to fix checkPointerTypesForAssignment for
  12116. // C++ semantics.
  12117. if (getLangOpts().CPlusPlus &&
  12118. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  12119. return false;
  12120. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  12121. break;
  12122. case IncompatibleNestedPointerQualifiers:
  12123. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  12124. break;
  12125. case IntToBlockPointer:
  12126. DiagKind = diag::err_int_to_block_pointer;
  12127. break;
  12128. case IncompatibleBlockPointer:
  12129. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  12130. break;
  12131. case IncompatibleObjCQualifiedId: {
  12132. if (SrcType->isObjCQualifiedIdType()) {
  12133. const ObjCObjectPointerType *srcOPT =
  12134. SrcType->getAs<ObjCObjectPointerType>();
  12135. for (auto *srcProto : srcOPT->quals()) {
  12136. PDecl = srcProto;
  12137. break;
  12138. }
  12139. if (const ObjCInterfaceType *IFaceT =
  12140. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  12141. IFace = IFaceT->getDecl();
  12142. }
  12143. else if (DstType->isObjCQualifiedIdType()) {
  12144. const ObjCObjectPointerType *dstOPT =
  12145. DstType->getAs<ObjCObjectPointerType>();
  12146. for (auto *dstProto : dstOPT->quals()) {
  12147. PDecl = dstProto;
  12148. break;
  12149. }
  12150. if (const ObjCInterfaceType *IFaceT =
  12151. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  12152. IFace = IFaceT->getDecl();
  12153. }
  12154. DiagKind = diag::warn_incompatible_qualified_id;
  12155. break;
  12156. }
  12157. case IncompatibleVectors:
  12158. DiagKind = diag::warn_incompatible_vectors;
  12159. break;
  12160. case IncompatibleObjCWeakRef:
  12161. DiagKind = diag::err_arc_weak_unavailable_assign;
  12162. break;
  12163. case Incompatible:
  12164. if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
  12165. if (Complained)
  12166. *Complained = true;
  12167. return true;
  12168. }
  12169. DiagKind = diag::err_typecheck_convert_incompatible;
  12170. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12171. MayHaveConvFixit = true;
  12172. isInvalid = true;
  12173. MayHaveFunctionDiff = true;
  12174. break;
  12175. }
  12176. QualType FirstType, SecondType;
  12177. switch (Action) {
  12178. case AA_Assigning:
  12179. case AA_Initializing:
  12180. // The destination type comes first.
  12181. FirstType = DstType;
  12182. SecondType = SrcType;
  12183. break;
  12184. case AA_Returning:
  12185. case AA_Passing:
  12186. case AA_Passing_CFAudited:
  12187. case AA_Converting:
  12188. case AA_Sending:
  12189. case AA_Casting:
  12190. // The source type comes first.
  12191. FirstType = SrcType;
  12192. SecondType = DstType;
  12193. break;
  12194. }
  12195. PartialDiagnostic FDiag = PDiag(DiagKind);
  12196. if (Action == AA_Passing_CFAudited)
  12197. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  12198. else
  12199. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  12200. // If we can fix the conversion, suggest the FixIts.
  12201. assert(ConvHints.isNull() || Hint.isNull());
  12202. if (!ConvHints.isNull()) {
  12203. for (FixItHint &H : ConvHints.Hints)
  12204. FDiag << H;
  12205. } else {
  12206. FDiag << Hint;
  12207. }
  12208. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  12209. if (MayHaveFunctionDiff)
  12210. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  12211. Diag(Loc, FDiag);
  12212. if (DiagKind == diag::warn_incompatible_qualified_id &&
  12213. PDecl && IFace && !IFace->hasDefinition())
  12214. Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
  12215. << IFace << PDecl;
  12216. if (SecondType == Context.OverloadTy)
  12217. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  12218. FirstType, /*TakingAddress=*/true);
  12219. if (CheckInferredResultType)
  12220. EmitRelatedResultTypeNote(SrcExpr);
  12221. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  12222. EmitRelatedResultTypeNoteForReturn(DstType);
  12223. if (Complained)
  12224. *Complained = true;
  12225. return isInvalid;
  12226. }
  12227. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  12228. llvm::APSInt *Result) {
  12229. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  12230. public:
  12231. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  12232. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  12233. }
  12234. } Diagnoser;
  12235. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  12236. }
  12237. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  12238. llvm::APSInt *Result,
  12239. unsigned DiagID,
  12240. bool AllowFold) {
  12241. class IDDiagnoser : public VerifyICEDiagnoser {
  12242. unsigned DiagID;
  12243. public:
  12244. IDDiagnoser(unsigned DiagID)
  12245. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  12246. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  12247. S.Diag(Loc, DiagID) << SR;
  12248. }
  12249. } Diagnoser(DiagID);
  12250. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  12251. }
  12252. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  12253. SourceRange SR) {
  12254. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  12255. }
  12256. ExprResult
  12257. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  12258. VerifyICEDiagnoser &Diagnoser,
  12259. bool AllowFold) {
  12260. SourceLocation DiagLoc = E->getLocStart();
  12261. if (getLangOpts().CPlusPlus11) {
  12262. // C++11 [expr.const]p5:
  12263. // If an expression of literal class type is used in a context where an
  12264. // integral constant expression is required, then that class type shall
  12265. // have a single non-explicit conversion function to an integral or
  12266. // unscoped enumeration type
  12267. ExprResult Converted;
  12268. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  12269. public:
  12270. CXX11ConvertDiagnoser(bool Silent)
  12271. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  12272. Silent, true) {}
  12273. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  12274. QualType T) override {
  12275. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  12276. }
  12277. SemaDiagnosticBuilder diagnoseIncomplete(
  12278. Sema &S, SourceLocation Loc, QualType T) override {
  12279. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  12280. }
  12281. SemaDiagnosticBuilder diagnoseExplicitConv(
  12282. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  12283. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  12284. }
  12285. SemaDiagnosticBuilder noteExplicitConv(
  12286. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  12287. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  12288. << ConvTy->isEnumeralType() << ConvTy;
  12289. }
  12290. SemaDiagnosticBuilder diagnoseAmbiguous(
  12291. Sema &S, SourceLocation Loc, QualType T) override {
  12292. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  12293. }
  12294. SemaDiagnosticBuilder noteAmbiguous(
  12295. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  12296. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  12297. << ConvTy->isEnumeralType() << ConvTy;
  12298. }
  12299. SemaDiagnosticBuilder diagnoseConversion(
  12300. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  12301. llvm_unreachable("conversion functions are permitted");
  12302. }
  12303. } ConvertDiagnoser(Diagnoser.Suppress);
  12304. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  12305. ConvertDiagnoser);
  12306. if (Converted.isInvalid())
  12307. return Converted;
  12308. E = Converted.get();
  12309. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  12310. return ExprError();
  12311. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  12312. // An ICE must be of integral or unscoped enumeration type.
  12313. if (!Diagnoser.Suppress)
  12314. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  12315. return ExprError();
  12316. }
  12317. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  12318. // in the non-ICE case.
  12319. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  12320. if (Result)
  12321. *Result = E->EvaluateKnownConstInt(Context);
  12322. return E;
  12323. }
  12324. Expr::EvalResult EvalResult;
  12325. SmallVector<PartialDiagnosticAt, 8> Notes;
  12326. EvalResult.Diag = &Notes;
  12327. // Try to evaluate the expression, and produce diagnostics explaining why it's
  12328. // not a constant expression as a side-effect.
  12329. bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
  12330. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  12331. // In C++11, we can rely on diagnostics being produced for any expression
  12332. // which is not a constant expression. If no diagnostics were produced, then
  12333. // this is a constant expression.
  12334. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  12335. if (Result)
  12336. *Result = EvalResult.Val.getInt();
  12337. return E;
  12338. }
  12339. // If our only note is the usual "invalid subexpression" note, just point
  12340. // the caret at its location rather than producing an essentially
  12341. // redundant note.
  12342. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  12343. diag::note_invalid_subexpr_in_const_expr) {
  12344. DiagLoc = Notes[0].first;
  12345. Notes.clear();
  12346. }
  12347. if (!Folded || !AllowFold) {
  12348. if (!Diagnoser.Suppress) {
  12349. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  12350. for (const PartialDiagnosticAt &Note : Notes)
  12351. Diag(Note.first, Note.second);
  12352. }
  12353. return ExprError();
  12354. }
  12355. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  12356. for (const PartialDiagnosticAt &Note : Notes)
  12357. Diag(Note.first, Note.second);
  12358. if (Result)
  12359. *Result = EvalResult.Val.getInt();
  12360. return E;
  12361. }
  12362. namespace {
  12363. // Handle the case where we conclude a expression which we speculatively
  12364. // considered to be unevaluated is actually evaluated.
  12365. class TransformToPE : public TreeTransform<TransformToPE> {
  12366. typedef TreeTransform<TransformToPE> BaseTransform;
  12367. public:
  12368. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  12369. // Make sure we redo semantic analysis
  12370. bool AlwaysRebuild() { return true; }
  12371. // Make sure we handle LabelStmts correctly.
  12372. // FIXME: This does the right thing, but maybe we need a more general
  12373. // fix to TreeTransform?
  12374. StmtResult TransformLabelStmt(LabelStmt *S) {
  12375. S->getDecl()->setStmt(nullptr);
  12376. return BaseTransform::TransformLabelStmt(S);
  12377. }
  12378. // We need to special-case DeclRefExprs referring to FieldDecls which
  12379. // are not part of a member pointer formation; normal TreeTransforming
  12380. // doesn't catch this case because of the way we represent them in the AST.
  12381. // FIXME: This is a bit ugly; is it really the best way to handle this
  12382. // case?
  12383. //
  12384. // Error on DeclRefExprs referring to FieldDecls.
  12385. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  12386. if (isa<FieldDecl>(E->getDecl()) &&
  12387. !SemaRef.isUnevaluatedContext())
  12388. return SemaRef.Diag(E->getLocation(),
  12389. diag::err_invalid_non_static_member_use)
  12390. << E->getDecl() << E->getSourceRange();
  12391. return BaseTransform::TransformDeclRefExpr(E);
  12392. }
  12393. // Exception: filter out member pointer formation
  12394. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  12395. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  12396. return E;
  12397. return BaseTransform::TransformUnaryOperator(E);
  12398. }
  12399. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  12400. // Lambdas never need to be transformed.
  12401. return E;
  12402. }
  12403. };
  12404. }
  12405. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  12406. assert(isUnevaluatedContext() &&
  12407. "Should only transform unevaluated expressions");
  12408. ExprEvalContexts.back().Context =
  12409. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  12410. if (isUnevaluatedContext())
  12411. return E;
  12412. return TransformToPE(*this).TransformExpr(E);
  12413. }
  12414. void
  12415. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  12416. Decl *LambdaContextDecl,
  12417. bool IsDecltype) {
  12418. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
  12419. LambdaContextDecl, IsDecltype);
  12420. Cleanup.reset();
  12421. if (!MaybeODRUseExprs.empty())
  12422. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  12423. }
  12424. void
  12425. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  12426. ReuseLambdaContextDecl_t,
  12427. bool IsDecltype) {
  12428. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  12429. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
  12430. }
  12431. void Sema::PopExpressionEvaluationContext() {
  12432. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  12433. unsigned NumTypos = Rec.NumTypos;
  12434. if (!Rec.Lambdas.empty()) {
  12435. if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
  12436. unsigned D;
  12437. if (Rec.isUnevaluated()) {
  12438. // C++11 [expr.prim.lambda]p2:
  12439. // A lambda-expression shall not appear in an unevaluated operand
  12440. // (Clause 5).
  12441. D = diag::err_lambda_unevaluated_operand;
  12442. } else {
  12443. // C++1y [expr.const]p2:
  12444. // A conditional-expression e is a core constant expression unless the
  12445. // evaluation of e, following the rules of the abstract machine, would
  12446. // evaluate [...] a lambda-expression.
  12447. D = diag::err_lambda_in_constant_expression;
  12448. }
  12449. // C++1z allows lambda expressions as core constant expressions.
  12450. // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
  12451. // 1607) from appearing within template-arguments and array-bounds that
  12452. // are part of function-signatures. Be mindful that P0315 (Lambdas in
  12453. // unevaluated contexts) might lift some of these restrictions in a
  12454. // future version.
  12455. if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17)
  12456. for (const auto *L : Rec.Lambdas)
  12457. Diag(L->getLocStart(), D);
  12458. } else {
  12459. // Mark the capture expressions odr-used. This was deferred
  12460. // during lambda expression creation.
  12461. for (auto *Lambda : Rec.Lambdas) {
  12462. for (auto *C : Lambda->capture_inits())
  12463. MarkDeclarationsReferencedInExpr(C);
  12464. }
  12465. }
  12466. }
  12467. // When are coming out of an unevaluated context, clear out any
  12468. // temporaries that we may have created as part of the evaluation of
  12469. // the expression in that context: they aren't relevant because they
  12470. // will never be constructed.
  12471. if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
  12472. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  12473. ExprCleanupObjects.end());
  12474. Cleanup = Rec.ParentCleanup;
  12475. CleanupVarDeclMarking();
  12476. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  12477. // Otherwise, merge the contexts together.
  12478. } else {
  12479. Cleanup.mergeFrom(Rec.ParentCleanup);
  12480. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  12481. Rec.SavedMaybeODRUseExprs.end());
  12482. }
  12483. // Pop the current expression evaluation context off the stack.
  12484. ExprEvalContexts.pop_back();
  12485. if (!ExprEvalContexts.empty())
  12486. ExprEvalContexts.back().NumTypos += NumTypos;
  12487. else
  12488. assert(NumTypos == 0 && "There are outstanding typos after popping the "
  12489. "last ExpressionEvaluationContextRecord");
  12490. }
  12491. void Sema::DiscardCleanupsInEvaluationContext() {
  12492. ExprCleanupObjects.erase(
  12493. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  12494. ExprCleanupObjects.end());
  12495. Cleanup.reset();
  12496. MaybeODRUseExprs.clear();
  12497. }
  12498. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  12499. if (!E->getType()->isVariablyModifiedType())
  12500. return E;
  12501. return TransformToPotentiallyEvaluated(E);
  12502. }
  12503. /// Are we within a context in which some evaluation could be performed (be it
  12504. /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
  12505. /// captured by C++'s idea of an "unevaluated context".
  12506. static bool isEvaluatableContext(Sema &SemaRef) {
  12507. switch (SemaRef.ExprEvalContexts.back().Context) {
  12508. case Sema::ExpressionEvaluationContext::Unevaluated:
  12509. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  12510. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  12511. // Expressions in this context are never evaluated.
  12512. return false;
  12513. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  12514. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  12515. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  12516. // Expressions in this context could be evaluated.
  12517. return true;
  12518. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  12519. // Referenced declarations will only be used if the construct in the
  12520. // containing expression is used, at which point we'll be given another
  12521. // turn to mark them.
  12522. return false;
  12523. }
  12524. llvm_unreachable("Invalid context");
  12525. }
  12526. /// Are we within a context in which references to resolved functions or to
  12527. /// variables result in odr-use?
  12528. static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
  12529. // An expression in a template is not really an expression until it's been
  12530. // instantiated, so it doesn't trigger odr-use.
  12531. if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
  12532. return false;
  12533. switch (SemaRef.ExprEvalContexts.back().Context) {
  12534. case Sema::ExpressionEvaluationContext::Unevaluated:
  12535. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  12536. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  12537. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  12538. return false;
  12539. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  12540. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  12541. return true;
  12542. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  12543. return false;
  12544. }
  12545. llvm_unreachable("Invalid context");
  12546. }
  12547. static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
  12548. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  12549. return Func->isConstexpr() &&
  12550. (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
  12551. }
  12552. /// Mark a function referenced, and check whether it is odr-used
  12553. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  12554. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  12555. bool MightBeOdrUse) {
  12556. assert(Func && "No function?");
  12557. Func->setReferenced();
  12558. // C++11 [basic.def.odr]p3:
  12559. // A function whose name appears as a potentially-evaluated expression is
  12560. // odr-used if it is the unique lookup result or the selected member of a
  12561. // set of overloaded functions [...].
  12562. //
  12563. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  12564. // can just check that here.
  12565. bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
  12566. // Determine whether we require a function definition to exist, per
  12567. // C++11 [temp.inst]p3:
  12568. // Unless a function template specialization has been explicitly
  12569. // instantiated or explicitly specialized, the function template
  12570. // specialization is implicitly instantiated when the specialization is
  12571. // referenced in a context that requires a function definition to exist.
  12572. //
  12573. // That is either when this is an odr-use, or when a usage of a constexpr
  12574. // function occurs within an evaluatable context.
  12575. bool NeedDefinition =
  12576. OdrUse || (isEvaluatableContext(*this) &&
  12577. isImplicitlyDefinableConstexprFunction(Func));
  12578. // C++14 [temp.expl.spec]p6:
  12579. // If a template [...] is explicitly specialized then that specialization
  12580. // shall be declared before the first use of that specialization that would
  12581. // cause an implicit instantiation to take place, in every translation unit
  12582. // in which such a use occurs
  12583. if (NeedDefinition &&
  12584. (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
  12585. Func->getMemberSpecializationInfo()))
  12586. checkSpecializationVisibility(Loc, Func);
  12587. // C++14 [except.spec]p17:
  12588. // An exception-specification is considered to be needed when:
  12589. // - the function is odr-used or, if it appears in an unevaluated operand,
  12590. // would be odr-used if the expression were potentially-evaluated;
  12591. //
  12592. // Note, we do this even if MightBeOdrUse is false. That indicates that the
  12593. // function is a pure virtual function we're calling, and in that case the
  12594. // function was selected by overload resolution and we need to resolve its
  12595. // exception specification for a different reason.
  12596. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  12597. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  12598. ResolveExceptionSpec(Loc, FPT);
  12599. // If we don't need to mark the function as used, and we don't need to
  12600. // try to provide a definition, there's nothing more to do.
  12601. if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
  12602. (!NeedDefinition || Func->getBody()))
  12603. return;
  12604. // Note that this declaration has been used.
  12605. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  12606. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  12607. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  12608. if (Constructor->isDefaultConstructor()) {
  12609. if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
  12610. return;
  12611. DefineImplicitDefaultConstructor(Loc, Constructor);
  12612. } else if (Constructor->isCopyConstructor()) {
  12613. DefineImplicitCopyConstructor(Loc, Constructor);
  12614. } else if (Constructor->isMoveConstructor()) {
  12615. DefineImplicitMoveConstructor(Loc, Constructor);
  12616. }
  12617. } else if (Constructor->getInheritedConstructor()) {
  12618. DefineInheritingConstructor(Loc, Constructor);
  12619. }
  12620. } else if (CXXDestructorDecl *Destructor =
  12621. dyn_cast<CXXDestructorDecl>(Func)) {
  12622. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  12623. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  12624. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  12625. return;
  12626. DefineImplicitDestructor(Loc, Destructor);
  12627. }
  12628. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  12629. MarkVTableUsed(Loc, Destructor->getParent());
  12630. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  12631. if (MethodDecl->isOverloadedOperator() &&
  12632. MethodDecl->getOverloadedOperator() == OO_Equal) {
  12633. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  12634. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  12635. if (MethodDecl->isCopyAssignmentOperator())
  12636. DefineImplicitCopyAssignment(Loc, MethodDecl);
  12637. else if (MethodDecl->isMoveAssignmentOperator())
  12638. DefineImplicitMoveAssignment(Loc, MethodDecl);
  12639. }
  12640. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  12641. MethodDecl->getParent()->isLambda()) {
  12642. CXXConversionDecl *Conversion =
  12643. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  12644. if (Conversion->isLambdaToBlockPointerConversion())
  12645. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  12646. else
  12647. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  12648. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  12649. MarkVTableUsed(Loc, MethodDecl->getParent());
  12650. }
  12651. // Recursive functions should be marked when used from another function.
  12652. // FIXME: Is this really right?
  12653. if (CurContext == Func) return;
  12654. // Implicit instantiation of function templates and member functions of
  12655. // class templates.
  12656. if (Func->isImplicitlyInstantiable()) {
  12657. TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
  12658. SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
  12659. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  12660. if (FirstInstantiation) {
  12661. PointOfInstantiation = Loc;
  12662. Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  12663. } else if (TSK != TSK_ImplicitInstantiation) {
  12664. // Use the point of use as the point of instantiation, instead of the
  12665. // point of explicit instantiation (which we track as the actual point of
  12666. // instantiation). This gives better backtraces in diagnostics.
  12667. PointOfInstantiation = Loc;
  12668. }
  12669. if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
  12670. Func->isConstexpr()) {
  12671. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  12672. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  12673. CodeSynthesisContexts.size())
  12674. PendingLocalImplicitInstantiations.push_back(
  12675. std::make_pair(Func, PointOfInstantiation));
  12676. else if (Func->isConstexpr())
  12677. // Do not defer instantiations of constexpr functions, to avoid the
  12678. // expression evaluator needing to call back into Sema if it sees a
  12679. // call to such a function.
  12680. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  12681. else {
  12682. Func->setInstantiationIsPending(true);
  12683. PendingInstantiations.push_back(std::make_pair(Func,
  12684. PointOfInstantiation));
  12685. // Notify the consumer that a function was implicitly instantiated.
  12686. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  12687. }
  12688. }
  12689. } else {
  12690. // Walk redefinitions, as some of them may be instantiable.
  12691. for (auto i : Func->redecls()) {
  12692. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  12693. MarkFunctionReferenced(Loc, i, OdrUse);
  12694. }
  12695. }
  12696. if (!OdrUse) return;
  12697. // Keep track of used but undefined functions.
  12698. if (!Func->isDefined()) {
  12699. if (mightHaveNonExternalLinkage(Func))
  12700. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  12701. else if (Func->getMostRecentDecl()->isInlined() &&
  12702. !LangOpts.GNUInline &&
  12703. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  12704. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  12705. else if (isExternalWithNoLinkageType(Func))
  12706. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  12707. }
  12708. Func->markUsed(Context);
  12709. }
  12710. static void
  12711. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  12712. ValueDecl *var, DeclContext *DC) {
  12713. DeclContext *VarDC = var->getDeclContext();
  12714. // If the parameter still belongs to the translation unit, then
  12715. // we're actually just using one parameter in the declaration of
  12716. // the next.
  12717. if (isa<ParmVarDecl>(var) &&
  12718. isa<TranslationUnitDecl>(VarDC))
  12719. return;
  12720. // For C code, don't diagnose about capture if we're not actually in code
  12721. // right now; it's impossible to write a non-constant expression outside of
  12722. // function context, so we'll get other (more useful) diagnostics later.
  12723. //
  12724. // For C++, things get a bit more nasty... it would be nice to suppress this
  12725. // diagnostic for certain cases like using a local variable in an array bound
  12726. // for a member of a local class, but the correct predicate is not obvious.
  12727. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  12728. return;
  12729. unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
  12730. unsigned ContextKind = 3; // unknown
  12731. if (isa<CXXMethodDecl>(VarDC) &&
  12732. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  12733. ContextKind = 2;
  12734. } else if (isa<FunctionDecl>(VarDC)) {
  12735. ContextKind = 0;
  12736. } else if (isa<BlockDecl>(VarDC)) {
  12737. ContextKind = 1;
  12738. }
  12739. S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
  12740. << var << ValueKind << ContextKind << VarDC;
  12741. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  12742. << var;
  12743. // FIXME: Add additional diagnostic info about class etc. which prevents
  12744. // capture.
  12745. }
  12746. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  12747. bool &SubCapturesAreNested,
  12748. QualType &CaptureType,
  12749. QualType &DeclRefType) {
  12750. // Check whether we've already captured it.
  12751. if (CSI->CaptureMap.count(Var)) {
  12752. // If we found a capture, any subcaptures are nested.
  12753. SubCapturesAreNested = true;
  12754. // Retrieve the capture type for this variable.
  12755. CaptureType = CSI->getCapture(Var).getCaptureType();
  12756. // Compute the type of an expression that refers to this variable.
  12757. DeclRefType = CaptureType.getNonReferenceType();
  12758. // Similarly to mutable captures in lambda, all the OpenMP captures by copy
  12759. // are mutable in the sense that user can change their value - they are
  12760. // private instances of the captured declarations.
  12761. const Capture &Cap = CSI->getCapture(Var);
  12762. if (Cap.isCopyCapture() &&
  12763. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
  12764. !(isa<CapturedRegionScopeInfo>(CSI) &&
  12765. cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
  12766. DeclRefType.addConst();
  12767. return true;
  12768. }
  12769. return false;
  12770. }
  12771. // Only block literals, captured statements, and lambda expressions can
  12772. // capture; other scopes don't work.
  12773. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  12774. SourceLocation Loc,
  12775. const bool Diagnose, Sema &S) {
  12776. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  12777. return getLambdaAwareParentOfDeclContext(DC);
  12778. else if (Var->hasLocalStorage()) {
  12779. if (Diagnose)
  12780. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  12781. }
  12782. return nullptr;
  12783. }
  12784. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  12785. // certain types of variables (unnamed, variably modified types etc.)
  12786. // so check for eligibility.
  12787. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  12788. SourceLocation Loc,
  12789. const bool Diagnose, Sema &S) {
  12790. bool IsBlock = isa<BlockScopeInfo>(CSI);
  12791. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  12792. // Lambdas are not allowed to capture unnamed variables
  12793. // (e.g. anonymous unions).
  12794. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  12795. // assuming that's the intent.
  12796. if (IsLambda && !Var->getDeclName()) {
  12797. if (Diagnose) {
  12798. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  12799. S.Diag(Var->getLocation(), diag::note_declared_at);
  12800. }
  12801. return false;
  12802. }
  12803. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  12804. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  12805. if (Diagnose) {
  12806. S.Diag(Loc, diag::err_ref_vm_type);
  12807. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12808. << Var->getDeclName();
  12809. }
  12810. return false;
  12811. }
  12812. // Prohibit structs with flexible array members too.
  12813. // We cannot capture what is in the tail end of the struct.
  12814. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  12815. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  12816. if (Diagnose) {
  12817. if (IsBlock)
  12818. S.Diag(Loc, diag::err_ref_flexarray_type);
  12819. else
  12820. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  12821. << Var->getDeclName();
  12822. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12823. << Var->getDeclName();
  12824. }
  12825. return false;
  12826. }
  12827. }
  12828. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  12829. // Lambdas and captured statements are not allowed to capture __block
  12830. // variables; they don't support the expected semantics.
  12831. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  12832. if (Diagnose) {
  12833. S.Diag(Loc, diag::err_capture_block_variable)
  12834. << Var->getDeclName() << !IsLambda;
  12835. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12836. << Var->getDeclName();
  12837. }
  12838. return false;
  12839. }
  12840. // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
  12841. if (S.getLangOpts().OpenCL && IsBlock &&
  12842. Var->getType()->isBlockPointerType()) {
  12843. if (Diagnose)
  12844. S.Diag(Loc, diag::err_opencl_block_ref_block);
  12845. return false;
  12846. }
  12847. return true;
  12848. }
  12849. // Returns true if the capture by block was successful.
  12850. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  12851. SourceLocation Loc,
  12852. const bool BuildAndDiagnose,
  12853. QualType &CaptureType,
  12854. QualType &DeclRefType,
  12855. const bool Nested,
  12856. Sema &S) {
  12857. Expr *CopyExpr = nullptr;
  12858. bool ByRef = false;
  12859. // Blocks are not allowed to capture arrays.
  12860. if (CaptureType->isArrayType()) {
  12861. if (BuildAndDiagnose) {
  12862. S.Diag(Loc, diag::err_ref_array_type);
  12863. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12864. << Var->getDeclName();
  12865. }
  12866. return false;
  12867. }
  12868. // Forbid the block-capture of autoreleasing variables.
  12869. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  12870. if (BuildAndDiagnose) {
  12871. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  12872. << /*block*/ 0;
  12873. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12874. << Var->getDeclName();
  12875. }
  12876. return false;
  12877. }
  12878. // Warn about implicitly autoreleasing indirect parameters captured by blocks.
  12879. if (const auto *PT = CaptureType->getAs<PointerType>()) {
  12880. // This function finds out whether there is an AttributedType of kind
  12881. // attr_objc_ownership in Ty. The existence of AttributedType of kind
  12882. // attr_objc_ownership implies __autoreleasing was explicitly specified
  12883. // rather than being added implicitly by the compiler.
  12884. auto IsObjCOwnershipAttributedType = [](QualType Ty) {
  12885. while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
  12886. if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
  12887. return true;
  12888. // Peel off AttributedTypes that are not of kind objc_ownership.
  12889. Ty = AttrTy->getModifiedType();
  12890. }
  12891. return false;
  12892. };
  12893. QualType PointeeTy = PT->getPointeeType();
  12894. if (PointeeTy->getAs<ObjCObjectPointerType>() &&
  12895. PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
  12896. !IsObjCOwnershipAttributedType(PointeeTy)) {
  12897. if (BuildAndDiagnose) {
  12898. SourceLocation VarLoc = Var->getLocation();
  12899. S.Diag(Loc, diag::warn_block_capture_autoreleasing);
  12900. S.Diag(VarLoc, diag::note_declare_parameter_strong);
  12901. }
  12902. }
  12903. }
  12904. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  12905. if (HasBlocksAttr || CaptureType->isReferenceType() ||
  12906. (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
  12907. // Block capture by reference does not change the capture or
  12908. // declaration reference types.
  12909. ByRef = true;
  12910. } else {
  12911. // Block capture by copy introduces 'const'.
  12912. CaptureType = CaptureType.getNonReferenceType().withConst();
  12913. DeclRefType = CaptureType;
  12914. if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
  12915. if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
  12916. // The capture logic needs the destructor, so make sure we mark it.
  12917. // Usually this is unnecessary because most local variables have
  12918. // their destructors marked at declaration time, but parameters are
  12919. // an exception because it's technically only the call site that
  12920. // actually requires the destructor.
  12921. if (isa<ParmVarDecl>(Var))
  12922. S.FinalizeVarWithDestructor(Var, Record);
  12923. // Enter a new evaluation context to insulate the copy
  12924. // full-expression.
  12925. EnterExpressionEvaluationContext scope(
  12926. S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  12927. // According to the blocks spec, the capture of a variable from
  12928. // the stack requires a const copy constructor. This is not true
  12929. // of the copy/move done to move a __block variable to the heap.
  12930. Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
  12931. DeclRefType.withConst(),
  12932. VK_LValue, Loc);
  12933. ExprResult Result
  12934. = S.PerformCopyInitialization(
  12935. InitializedEntity::InitializeBlock(Var->getLocation(),
  12936. CaptureType, false),
  12937. Loc, DeclRef);
  12938. // Build a full-expression copy expression if initialization
  12939. // succeeded and used a non-trivial constructor. Recover from
  12940. // errors by pretending that the copy isn't necessary.
  12941. if (!Result.isInvalid() &&
  12942. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  12943. ->isTrivial()) {
  12944. Result = S.MaybeCreateExprWithCleanups(Result);
  12945. CopyExpr = Result.get();
  12946. }
  12947. }
  12948. }
  12949. }
  12950. // Actually capture the variable.
  12951. if (BuildAndDiagnose)
  12952. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
  12953. SourceLocation(), CaptureType, CopyExpr);
  12954. return true;
  12955. }
  12956. /// Capture the given variable in the captured region.
  12957. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  12958. VarDecl *Var,
  12959. SourceLocation Loc,
  12960. const bool BuildAndDiagnose,
  12961. QualType &CaptureType,
  12962. QualType &DeclRefType,
  12963. const bool RefersToCapturedVariable,
  12964. Sema &S) {
  12965. // By default, capture variables by reference.
  12966. bool ByRef = true;
  12967. // Using an LValue reference type is consistent with Lambdas (see below).
  12968. if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
  12969. if (S.isOpenMPCapturedDecl(Var)) {
  12970. bool HasConst = DeclRefType.isConstQualified();
  12971. DeclRefType = DeclRefType.getUnqualifiedType();
  12972. // Don't lose diagnostics about assignments to const.
  12973. if (HasConst)
  12974. DeclRefType.addConst();
  12975. }
  12976. ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
  12977. }
  12978. if (ByRef)
  12979. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  12980. else
  12981. CaptureType = DeclRefType;
  12982. Expr *CopyExpr = nullptr;
  12983. if (BuildAndDiagnose) {
  12984. // The current implementation assumes that all variables are captured
  12985. // by references. Since there is no capture by copy, no expression
  12986. // evaluation will be needed.
  12987. RecordDecl *RD = RSI->TheRecordDecl;
  12988. FieldDecl *Field
  12989. = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
  12990. S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
  12991. nullptr, false, ICIS_NoInit);
  12992. Field->setImplicit(true);
  12993. Field->setAccess(AS_private);
  12994. RD->addDecl(Field);
  12995. if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
  12996. S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
  12997. CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
  12998. DeclRefType, VK_LValue, Loc);
  12999. Var->setReferenced(true);
  13000. Var->markUsed(S.Context);
  13001. }
  13002. // Actually capture the variable.
  13003. if (BuildAndDiagnose)
  13004. RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
  13005. SourceLocation(), CaptureType, CopyExpr);
  13006. return true;
  13007. }
  13008. /// Create a field within the lambda class for the variable
  13009. /// being captured.
  13010. static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
  13011. QualType FieldType, QualType DeclRefType,
  13012. SourceLocation Loc,
  13013. bool RefersToCapturedVariable) {
  13014. CXXRecordDecl *Lambda = LSI->Lambda;
  13015. // Build the non-static data member.
  13016. FieldDecl *Field
  13017. = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
  13018. S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
  13019. nullptr, false, ICIS_NoInit);
  13020. Field->setImplicit(true);
  13021. Field->setAccess(AS_private);
  13022. Lambda->addDecl(Field);
  13023. }
  13024. /// Capture the given variable in the lambda.
  13025. static bool captureInLambda(LambdaScopeInfo *LSI,
  13026. VarDecl *Var,
  13027. SourceLocation Loc,
  13028. const bool BuildAndDiagnose,
  13029. QualType &CaptureType,
  13030. QualType &DeclRefType,
  13031. const bool RefersToCapturedVariable,
  13032. const Sema::TryCaptureKind Kind,
  13033. SourceLocation EllipsisLoc,
  13034. const bool IsTopScope,
  13035. Sema &S) {
  13036. // Determine whether we are capturing by reference or by value.
  13037. bool ByRef = false;
  13038. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  13039. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  13040. } else {
  13041. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  13042. }
  13043. // Compute the type of the field that will capture this variable.
  13044. if (ByRef) {
  13045. // C++11 [expr.prim.lambda]p15:
  13046. // An entity is captured by reference if it is implicitly or
  13047. // explicitly captured but not captured by copy. It is
  13048. // unspecified whether additional unnamed non-static data
  13049. // members are declared in the closure type for entities
  13050. // captured by reference.
  13051. //
  13052. // FIXME: It is not clear whether we want to build an lvalue reference
  13053. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  13054. // to do the former, while EDG does the latter. Core issue 1249 will
  13055. // clarify, but for now we follow GCC because it's a more permissive and
  13056. // easily defensible position.
  13057. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  13058. } else {
  13059. // C++11 [expr.prim.lambda]p14:
  13060. // For each entity captured by copy, an unnamed non-static
  13061. // data member is declared in the closure type. The
  13062. // declaration order of these members is unspecified. The type
  13063. // of such a data member is the type of the corresponding
  13064. // captured entity if the entity is not a reference to an
  13065. // object, or the referenced type otherwise. [Note: If the
  13066. // captured entity is a reference to a function, the
  13067. // corresponding data member is also a reference to a
  13068. // function. - end note ]
  13069. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  13070. if (!RefType->getPointeeType()->isFunctionType())
  13071. CaptureType = RefType->getPointeeType();
  13072. }
  13073. // Forbid the lambda copy-capture of autoreleasing variables.
  13074. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  13075. if (BuildAndDiagnose) {
  13076. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  13077. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13078. << Var->getDeclName();
  13079. }
  13080. return false;
  13081. }
  13082. // Make sure that by-copy captures are of a complete and non-abstract type.
  13083. if (BuildAndDiagnose) {
  13084. if (!CaptureType->isDependentType() &&
  13085. S.RequireCompleteType(Loc, CaptureType,
  13086. diag::err_capture_of_incomplete_type,
  13087. Var->getDeclName()))
  13088. return false;
  13089. if (S.RequireNonAbstractType(Loc, CaptureType,
  13090. diag::err_capture_of_abstract_type))
  13091. return false;
  13092. }
  13093. }
  13094. // Capture this variable in the lambda.
  13095. if (BuildAndDiagnose)
  13096. addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
  13097. RefersToCapturedVariable);
  13098. // Compute the type of a reference to this captured variable.
  13099. if (ByRef)
  13100. DeclRefType = CaptureType.getNonReferenceType();
  13101. else {
  13102. // C++ [expr.prim.lambda]p5:
  13103. // The closure type for a lambda-expression has a public inline
  13104. // function call operator [...]. This function call operator is
  13105. // declared const (9.3.1) if and only if the lambda-expression's
  13106. // parameter-declaration-clause is not followed by mutable.
  13107. DeclRefType = CaptureType.getNonReferenceType();
  13108. if (!LSI->Mutable && !CaptureType->isReferenceType())
  13109. DeclRefType.addConst();
  13110. }
  13111. // Add the capture.
  13112. if (BuildAndDiagnose)
  13113. LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
  13114. Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
  13115. return true;
  13116. }
  13117. bool Sema::tryCaptureVariable(
  13118. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  13119. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  13120. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  13121. // An init-capture is notionally from the context surrounding its
  13122. // declaration, but its parent DC is the lambda class.
  13123. DeclContext *VarDC = Var->getDeclContext();
  13124. if (Var->isInitCapture())
  13125. VarDC = VarDC->getParent();
  13126. DeclContext *DC = CurContext;
  13127. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  13128. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  13129. // We need to sync up the Declaration Context with the
  13130. // FunctionScopeIndexToStopAt
  13131. if (FunctionScopeIndexToStopAt) {
  13132. unsigned FSIndex = FunctionScopes.size() - 1;
  13133. while (FSIndex != MaxFunctionScopesIndex) {
  13134. DC = getLambdaAwareParentOfDeclContext(DC);
  13135. --FSIndex;
  13136. }
  13137. }
  13138. // If the variable is declared in the current context, there is no need to
  13139. // capture it.
  13140. if (VarDC == DC) return true;
  13141. // Capture global variables if it is required to use private copy of this
  13142. // variable.
  13143. bool IsGlobal = !Var->hasLocalStorage();
  13144. if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
  13145. return true;
  13146. Var = Var->getCanonicalDecl();
  13147. // Walk up the stack to determine whether we can capture the variable,
  13148. // performing the "simple" checks that don't depend on type. We stop when
  13149. // we've either hit the declared scope of the variable or find an existing
  13150. // capture of that variable. We start from the innermost capturing-entity
  13151. // (the DC) and ensure that all intervening capturing-entities
  13152. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  13153. // declcontext can either capture the variable or have already captured
  13154. // the variable.
  13155. CaptureType = Var->getType();
  13156. DeclRefType = CaptureType.getNonReferenceType();
  13157. bool Nested = false;
  13158. bool Explicit = (Kind != TryCapture_Implicit);
  13159. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  13160. do {
  13161. // Only block literals, captured statements, and lambda expressions can
  13162. // capture; other scopes don't work.
  13163. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  13164. ExprLoc,
  13165. BuildAndDiagnose,
  13166. *this);
  13167. // We need to check for the parent *first* because, if we *have*
  13168. // private-captured a global variable, we need to recursively capture it in
  13169. // intermediate blocks, lambdas, etc.
  13170. if (!ParentDC) {
  13171. if (IsGlobal) {
  13172. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  13173. break;
  13174. }
  13175. return true;
  13176. }
  13177. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  13178. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  13179. // Check whether we've already captured it.
  13180. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  13181. DeclRefType)) {
  13182. CSI->getCapture(Var).markUsed(BuildAndDiagnose);
  13183. break;
  13184. }
  13185. // If we are instantiating a generic lambda call operator body,
  13186. // we do not want to capture new variables. What was captured
  13187. // during either a lambdas transformation or initial parsing
  13188. // should be used.
  13189. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  13190. if (BuildAndDiagnose) {
  13191. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  13192. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  13193. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  13194. Diag(Var->getLocation(), diag::note_previous_decl)
  13195. << Var->getDeclName();
  13196. Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
  13197. } else
  13198. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  13199. }
  13200. return true;
  13201. }
  13202. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  13203. // certain types of variables (unnamed, variably modified types etc.)
  13204. // so check for eligibility.
  13205. if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
  13206. return true;
  13207. // Try to capture variable-length arrays types.
  13208. if (Var->getType()->isVariablyModifiedType()) {
  13209. // We're going to walk down into the type and look for VLA
  13210. // expressions.
  13211. QualType QTy = Var->getType();
  13212. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  13213. QTy = PVD->getOriginalType();
  13214. captureVariablyModifiedType(Context, QTy, CSI);
  13215. }
  13216. if (getLangOpts().OpenMP) {
  13217. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  13218. // OpenMP private variables should not be captured in outer scope, so
  13219. // just break here. Similarly, global variables that are captured in a
  13220. // target region should not be captured outside the scope of the region.
  13221. if (RSI->CapRegionKind == CR_OpenMP) {
  13222. bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
  13223. auto IsTargetCap = !IsOpenMPPrivateDecl &&
  13224. isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
  13225. // When we detect target captures we are looking from inside the
  13226. // target region, therefore we need to propagate the capture from the
  13227. // enclosing region. Therefore, the capture is not initially nested.
  13228. if (IsTargetCap)
  13229. adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
  13230. if (IsTargetCap || IsOpenMPPrivateDecl) {
  13231. Nested = !IsTargetCap;
  13232. DeclRefType = DeclRefType.getUnqualifiedType();
  13233. CaptureType = Context.getLValueReferenceType(DeclRefType);
  13234. break;
  13235. }
  13236. }
  13237. }
  13238. }
  13239. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  13240. // No capture-default, and this is not an explicit capture
  13241. // so cannot capture this variable.
  13242. if (BuildAndDiagnose) {
  13243. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  13244. Diag(Var->getLocation(), diag::note_previous_decl)
  13245. << Var->getDeclName();
  13246. if (cast<LambdaScopeInfo>(CSI)->Lambda)
  13247. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
  13248. diag::note_lambda_decl);
  13249. // FIXME: If we error out because an outer lambda can not implicitly
  13250. // capture a variable that an inner lambda explicitly captures, we
  13251. // should have the inner lambda do the explicit capture - because
  13252. // it makes for cleaner diagnostics later. This would purely be done
  13253. // so that the diagnostic does not misleadingly claim that a variable
  13254. // can not be captured by a lambda implicitly even though it is captured
  13255. // explicitly. Suggestion:
  13256. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  13257. // at the function head
  13258. // - cache the StartingDeclContext - this must be a lambda
  13259. // - captureInLambda in the innermost lambda the variable.
  13260. }
  13261. return true;
  13262. }
  13263. FunctionScopesIndex--;
  13264. DC = ParentDC;
  13265. Explicit = false;
  13266. } while (!VarDC->Equals(DC));
  13267. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  13268. // computing the type of the capture at each step, checking type-specific
  13269. // requirements, and adding captures if requested.
  13270. // If the variable had already been captured previously, we start capturing
  13271. // at the lambda nested within that one.
  13272. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  13273. ++I) {
  13274. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  13275. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  13276. if (!captureInBlock(BSI, Var, ExprLoc,
  13277. BuildAndDiagnose, CaptureType,
  13278. DeclRefType, Nested, *this))
  13279. return true;
  13280. Nested = true;
  13281. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  13282. if (!captureInCapturedRegion(RSI, Var, ExprLoc,
  13283. BuildAndDiagnose, CaptureType,
  13284. DeclRefType, Nested, *this))
  13285. return true;
  13286. Nested = true;
  13287. } else {
  13288. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  13289. if (!captureInLambda(LSI, Var, ExprLoc,
  13290. BuildAndDiagnose, CaptureType,
  13291. DeclRefType, Nested, Kind, EllipsisLoc,
  13292. /*IsTopScope*/I == N - 1, *this))
  13293. return true;
  13294. Nested = true;
  13295. }
  13296. }
  13297. return false;
  13298. }
  13299. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  13300. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  13301. QualType CaptureType;
  13302. QualType DeclRefType;
  13303. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  13304. /*BuildAndDiagnose=*/true, CaptureType,
  13305. DeclRefType, nullptr);
  13306. }
  13307. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  13308. QualType CaptureType;
  13309. QualType DeclRefType;
  13310. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  13311. /*BuildAndDiagnose=*/false, CaptureType,
  13312. DeclRefType, nullptr);
  13313. }
  13314. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  13315. QualType CaptureType;
  13316. QualType DeclRefType;
  13317. // Determine whether we can capture this variable.
  13318. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  13319. /*BuildAndDiagnose=*/false, CaptureType,
  13320. DeclRefType, nullptr))
  13321. return QualType();
  13322. return DeclRefType;
  13323. }
  13324. // If either the type of the variable or the initializer is dependent,
  13325. // return false. Otherwise, determine whether the variable is a constant
  13326. // expression. Use this if you need to know if a variable that might or
  13327. // might not be dependent is truly a constant expression.
  13328. static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
  13329. ASTContext &Context) {
  13330. if (Var->getType()->isDependentType())
  13331. return false;
  13332. const VarDecl *DefVD = nullptr;
  13333. Var->getAnyInitializer(DefVD);
  13334. if (!DefVD)
  13335. return false;
  13336. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  13337. Expr *Init = cast<Expr>(Eval->Value);
  13338. if (Init->isValueDependent())
  13339. return false;
  13340. return IsVariableAConstantExpression(Var, Context);
  13341. }
  13342. void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
  13343. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  13344. // an object that satisfies the requirements for appearing in a
  13345. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  13346. // is immediately applied." This function handles the lvalue-to-rvalue
  13347. // conversion part.
  13348. MaybeODRUseExprs.erase(E->IgnoreParens());
  13349. // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
  13350. // to a variable that is a constant expression, and if so, identify it as
  13351. // a reference to a variable that does not involve an odr-use of that
  13352. // variable.
  13353. if (LambdaScopeInfo *LSI = getCurLambda()) {
  13354. Expr *SansParensExpr = E->IgnoreParens();
  13355. VarDecl *Var = nullptr;
  13356. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
  13357. Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
  13358. else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
  13359. Var = dyn_cast<VarDecl>(ME->getMemberDecl());
  13360. if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
  13361. LSI->markVariableExprAsNonODRUsed(SansParensExpr);
  13362. }
  13363. }
  13364. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  13365. Res = CorrectDelayedTyposInExpr(Res);
  13366. if (!Res.isUsable())
  13367. return Res;
  13368. // If a constant-expression is a reference to a variable where we delay
  13369. // deciding whether it is an odr-use, just assume we will apply the
  13370. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  13371. // (a non-type template argument), we have special handling anyway.
  13372. UpdateMarkingForLValueToRValue(Res.get());
  13373. return Res;
  13374. }
  13375. void Sema::CleanupVarDeclMarking() {
  13376. for (Expr *E : MaybeODRUseExprs) {
  13377. VarDecl *Var;
  13378. SourceLocation Loc;
  13379. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  13380. Var = cast<VarDecl>(DRE->getDecl());
  13381. Loc = DRE->getLocation();
  13382. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  13383. Var = cast<VarDecl>(ME->getMemberDecl());
  13384. Loc = ME->getMemberLoc();
  13385. } else {
  13386. llvm_unreachable("Unexpected expression");
  13387. }
  13388. MarkVarDeclODRUsed(Var, Loc, *this,
  13389. /*MaxFunctionScopeIndex Pointer*/ nullptr);
  13390. }
  13391. MaybeODRUseExprs.clear();
  13392. }
  13393. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  13394. VarDecl *Var, Expr *E) {
  13395. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
  13396. "Invalid Expr argument to DoMarkVarDeclReferenced");
  13397. Var->setReferenced();
  13398. TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
  13399. bool OdrUseContext = isOdrUseContext(SemaRef);
  13400. bool UsableInConstantExpr =
  13401. Var->isUsableInConstantExpressions(SemaRef.Context);
  13402. bool NeedDefinition =
  13403. OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
  13404. VarTemplateSpecializationDecl *VarSpec =
  13405. dyn_cast<VarTemplateSpecializationDecl>(Var);
  13406. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  13407. "Can't instantiate a partial template specialization.");
  13408. // If this might be a member specialization of a static data member, check
  13409. // the specialization is visible. We already did the checks for variable
  13410. // template specializations when we created them.
  13411. if (NeedDefinition && TSK != TSK_Undeclared &&
  13412. !isa<VarTemplateSpecializationDecl>(Var))
  13413. SemaRef.checkSpecializationVisibility(Loc, Var);
  13414. // Perform implicit instantiation of static data members, static data member
  13415. // templates of class templates, and variable template specializations. Delay
  13416. // instantiations of variable templates, except for those that could be used
  13417. // in a constant expression.
  13418. if (NeedDefinition && isTemplateInstantiation(TSK)) {
  13419. // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
  13420. // instantiation declaration if a variable is usable in a constant
  13421. // expression (among other cases).
  13422. bool TryInstantiating =
  13423. TSK == TSK_ImplicitInstantiation ||
  13424. (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
  13425. if (TryInstantiating) {
  13426. SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
  13427. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  13428. if (FirstInstantiation) {
  13429. PointOfInstantiation = Loc;
  13430. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  13431. }
  13432. bool InstantiationDependent = false;
  13433. bool IsNonDependent =
  13434. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  13435. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  13436. : true;
  13437. // Do not instantiate specializations that are still type-dependent.
  13438. if (IsNonDependent) {
  13439. if (UsableInConstantExpr) {
  13440. // Do not defer instantiations of variables that could be used in a
  13441. // constant expression.
  13442. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  13443. } else if (FirstInstantiation ||
  13444. isa<VarTemplateSpecializationDecl>(Var)) {
  13445. // FIXME: For a specialization of a variable template, we don't
  13446. // distinguish between "declaration and type implicitly instantiated"
  13447. // and "implicit instantiation of definition requested", so we have
  13448. // no direct way to avoid enqueueing the pending instantiation
  13449. // multiple times.
  13450. SemaRef.PendingInstantiations
  13451. .push_back(std::make_pair(Var, PointOfInstantiation));
  13452. }
  13453. }
  13454. }
  13455. }
  13456. // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
  13457. // the requirements for appearing in a constant expression (5.19) and, if
  13458. // it is an object, the lvalue-to-rvalue conversion (4.1)
  13459. // is immediately applied." We check the first part here, and
  13460. // Sema::UpdateMarkingForLValueToRValue deals with the second part.
  13461. // Note that we use the C++11 definition everywhere because nothing in
  13462. // C++03 depends on whether we get the C++03 version correct. The second
  13463. // part does not apply to references, since they are not objects.
  13464. if (OdrUseContext && E &&
  13465. IsVariableAConstantExpression(Var, SemaRef.Context)) {
  13466. // A reference initialized by a constant expression can never be
  13467. // odr-used, so simply ignore it.
  13468. if (!Var->getType()->isReferenceType() ||
  13469. (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
  13470. SemaRef.MaybeODRUseExprs.insert(E);
  13471. } else if (OdrUseContext) {
  13472. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  13473. /*MaxFunctionScopeIndex ptr*/ nullptr);
  13474. } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
  13475. // If this is a dependent context, we don't need to mark variables as
  13476. // odr-used, but we may still need to track them for lambda capture.
  13477. // FIXME: Do we also need to do this inside dependent typeid expressions
  13478. // (which are modeled as unevaluated at this point)?
  13479. const bool RefersToEnclosingScope =
  13480. (SemaRef.CurContext != Var->getDeclContext() &&
  13481. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  13482. if (RefersToEnclosingScope) {
  13483. LambdaScopeInfo *const LSI =
  13484. SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
  13485. if (LSI && (!LSI->CallOperator ||
  13486. !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
  13487. // If a variable could potentially be odr-used, defer marking it so
  13488. // until we finish analyzing the full expression for any
  13489. // lvalue-to-rvalue
  13490. // or discarded value conversions that would obviate odr-use.
  13491. // Add it to the list of potential captures that will be analyzed
  13492. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  13493. // unless the variable is a reference that was initialized by a constant
  13494. // expression (this will never need to be captured or odr-used).
  13495. assert(E && "Capture variable should be used in an expression.");
  13496. if (!Var->getType()->isReferenceType() ||
  13497. !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
  13498. LSI->addPotentialCapture(E->IgnoreParens());
  13499. }
  13500. }
  13501. }
  13502. }
  13503. /// Mark a variable referenced, and check whether it is odr-used
  13504. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  13505. /// used directly for normal expressions referring to VarDecl.
  13506. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  13507. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  13508. }
  13509. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  13510. Decl *D, Expr *E, bool MightBeOdrUse) {
  13511. if (SemaRef.isInOpenMPDeclareTargetContext())
  13512. SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
  13513. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  13514. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  13515. return;
  13516. }
  13517. SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
  13518. // If this is a call to a method via a cast, also mark the method in the
  13519. // derived class used in case codegen can devirtualize the call.
  13520. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  13521. if (!ME)
  13522. return;
  13523. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  13524. if (!MD)
  13525. return;
  13526. // Only attempt to devirtualize if this is truly a virtual call.
  13527. bool IsVirtualCall = MD->isVirtual() &&
  13528. ME->performsVirtualDispatch(SemaRef.getLangOpts());
  13529. if (!IsVirtualCall)
  13530. return;
  13531. // If it's possible to devirtualize the call, mark the called function
  13532. // referenced.
  13533. CXXMethodDecl *DM = MD->getDevirtualizedMethod(
  13534. ME->getBase(), SemaRef.getLangOpts().AppleKext);
  13535. if (DM)
  13536. SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
  13537. }
  13538. /// Perform reference-marking and odr-use handling for a DeclRefExpr.
  13539. void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
  13540. // TODO: update this with DR# once a defect report is filed.
  13541. // C++11 defect. The address of a pure member should not be an ODR use, even
  13542. // if it's a qualified reference.
  13543. bool OdrUse = true;
  13544. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  13545. if (Method->isVirtual() &&
  13546. !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
  13547. OdrUse = false;
  13548. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  13549. }
  13550. /// Perform reference-marking and odr-use handling for a MemberExpr.
  13551. void Sema::MarkMemberReferenced(MemberExpr *E) {
  13552. // C++11 [basic.def.odr]p2:
  13553. // A non-overloaded function whose name appears as a potentially-evaluated
  13554. // expression or a member of a set of candidate functions, if selected by
  13555. // overload resolution when referred to from a potentially-evaluated
  13556. // expression, is odr-used, unless it is a pure virtual function and its
  13557. // name is not explicitly qualified.
  13558. bool MightBeOdrUse = true;
  13559. if (E->performsVirtualDispatch(getLangOpts())) {
  13560. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  13561. if (Method->isPure())
  13562. MightBeOdrUse = false;
  13563. }
  13564. SourceLocation Loc = E->getMemberLoc().isValid() ?
  13565. E->getMemberLoc() : E->getLocStart();
  13566. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
  13567. }
  13568. /// Perform marking for a reference to an arbitrary declaration. It
  13569. /// marks the declaration referenced, and performs odr-use checking for
  13570. /// functions and variables. This method should not be used when building a
  13571. /// normal expression which refers to a variable.
  13572. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
  13573. bool MightBeOdrUse) {
  13574. if (MightBeOdrUse) {
  13575. if (auto *VD = dyn_cast<VarDecl>(D)) {
  13576. MarkVariableReferenced(Loc, VD);
  13577. return;
  13578. }
  13579. }
  13580. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  13581. MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
  13582. return;
  13583. }
  13584. D->setReferenced();
  13585. }
  13586. namespace {
  13587. // Mark all of the declarations used by a type as referenced.
  13588. // FIXME: Not fully implemented yet! We need to have a better understanding
  13589. // of when we're entering a context we should not recurse into.
  13590. // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
  13591. // TreeTransforms rebuilding the type in a new context. Rather than
  13592. // duplicating the TreeTransform logic, we should consider reusing it here.
  13593. // Currently that causes problems when rebuilding LambdaExprs.
  13594. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  13595. Sema &S;
  13596. SourceLocation Loc;
  13597. public:
  13598. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  13599. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  13600. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  13601. };
  13602. }
  13603. bool MarkReferencedDecls::TraverseTemplateArgument(
  13604. const TemplateArgument &Arg) {
  13605. {
  13606. // A non-type template argument is a constant-evaluated context.
  13607. EnterExpressionEvaluationContext Evaluated(
  13608. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  13609. if (Arg.getKind() == TemplateArgument::Declaration) {
  13610. if (Decl *D = Arg.getAsDecl())
  13611. S.MarkAnyDeclReferenced(Loc, D, true);
  13612. } else if (Arg.getKind() == TemplateArgument::Expression) {
  13613. S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
  13614. }
  13615. }
  13616. return Inherited::TraverseTemplateArgument(Arg);
  13617. }
  13618. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  13619. MarkReferencedDecls Marker(*this, Loc);
  13620. Marker.TraverseType(T);
  13621. }
  13622. namespace {
  13623. /// Helper class that marks all of the declarations referenced by
  13624. /// potentially-evaluated subexpressions as "referenced".
  13625. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  13626. Sema &S;
  13627. bool SkipLocalVariables;
  13628. public:
  13629. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  13630. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  13631. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  13632. void VisitDeclRefExpr(DeclRefExpr *E) {
  13633. // If we were asked not to visit local variables, don't.
  13634. if (SkipLocalVariables) {
  13635. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  13636. if (VD->hasLocalStorage())
  13637. return;
  13638. }
  13639. S.MarkDeclRefReferenced(E);
  13640. }
  13641. void VisitMemberExpr(MemberExpr *E) {
  13642. S.MarkMemberReferenced(E);
  13643. Inherited::VisitMemberExpr(E);
  13644. }
  13645. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  13646. S.MarkFunctionReferenced(E->getLocStart(),
  13647. const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
  13648. Visit(E->getSubExpr());
  13649. }
  13650. void VisitCXXNewExpr(CXXNewExpr *E) {
  13651. if (E->getOperatorNew())
  13652. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
  13653. if (E->getOperatorDelete())
  13654. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  13655. Inherited::VisitCXXNewExpr(E);
  13656. }
  13657. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  13658. if (E->getOperatorDelete())
  13659. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  13660. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  13661. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  13662. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  13663. S.MarkFunctionReferenced(E->getLocStart(),
  13664. S.LookupDestructor(Record));
  13665. }
  13666. Inherited::VisitCXXDeleteExpr(E);
  13667. }
  13668. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  13669. S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
  13670. Inherited::VisitCXXConstructExpr(E);
  13671. }
  13672. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  13673. Visit(E->getExpr());
  13674. }
  13675. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  13676. Inherited::VisitImplicitCastExpr(E);
  13677. if (E->getCastKind() == CK_LValueToRValue)
  13678. S.UpdateMarkingForLValueToRValue(E->getSubExpr());
  13679. }
  13680. };
  13681. }
  13682. /// Mark any declarations that appear within this expression or any
  13683. /// potentially-evaluated subexpressions as "referenced".
  13684. ///
  13685. /// \param SkipLocalVariables If true, don't mark local variables as
  13686. /// 'referenced'.
  13687. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  13688. bool SkipLocalVariables) {
  13689. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  13690. }
  13691. /// Emit a diagnostic that describes an effect on the run-time behavior
  13692. /// of the program being compiled.
  13693. ///
  13694. /// This routine emits the given diagnostic when the code currently being
  13695. /// type-checked is "potentially evaluated", meaning that there is a
  13696. /// possibility that the code will actually be executable. Code in sizeof()
  13697. /// expressions, code used only during overload resolution, etc., are not
  13698. /// potentially evaluated. This routine will suppress such diagnostics or,
  13699. /// in the absolutely nutty case of potentially potentially evaluated
  13700. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  13701. /// later.
  13702. ///
  13703. /// This routine should be used for all diagnostics that describe the run-time
  13704. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  13705. /// Failure to do so will likely result in spurious diagnostics or failures
  13706. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  13707. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  13708. const PartialDiagnostic &PD) {
  13709. switch (ExprEvalContexts.back().Context) {
  13710. case ExpressionEvaluationContext::Unevaluated:
  13711. case ExpressionEvaluationContext::UnevaluatedList:
  13712. case ExpressionEvaluationContext::UnevaluatedAbstract:
  13713. case ExpressionEvaluationContext::DiscardedStatement:
  13714. // The argument will never be evaluated, so don't complain.
  13715. break;
  13716. case ExpressionEvaluationContext::ConstantEvaluated:
  13717. // Relevant diagnostics should be produced by constant evaluation.
  13718. break;
  13719. case ExpressionEvaluationContext::PotentiallyEvaluated:
  13720. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13721. if (Statement && getCurFunctionOrMethodDecl()) {
  13722. FunctionScopes.back()->PossiblyUnreachableDiags.
  13723. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
  13724. return true;
  13725. }
  13726. // The initializer of a constexpr variable or of the first declaration of a
  13727. // static data member is not syntactically a constant evaluated constant,
  13728. // but nonetheless is always required to be a constant expression, so we
  13729. // can skip diagnosing.
  13730. // FIXME: Using the mangling context here is a hack.
  13731. if (auto *VD = dyn_cast_or_null<VarDecl>(
  13732. ExprEvalContexts.back().ManglingContextDecl)) {
  13733. if (VD->isConstexpr() ||
  13734. (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
  13735. break;
  13736. // FIXME: For any other kind of variable, we should build a CFG for its
  13737. // initializer and check whether the context in question is reachable.
  13738. }
  13739. Diag(Loc, PD);
  13740. return true;
  13741. }
  13742. return false;
  13743. }
  13744. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  13745. CallExpr *CE, FunctionDecl *FD) {
  13746. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  13747. return false;
  13748. // If we're inside a decltype's expression, don't check for a valid return
  13749. // type or construct temporaries until we know whether this is the last call.
  13750. if (ExprEvalContexts.back().IsDecltype) {
  13751. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  13752. return false;
  13753. }
  13754. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  13755. FunctionDecl *FD;
  13756. CallExpr *CE;
  13757. public:
  13758. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  13759. : FD(FD), CE(CE) { }
  13760. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  13761. if (!FD) {
  13762. S.Diag(Loc, diag::err_call_incomplete_return)
  13763. << T << CE->getSourceRange();
  13764. return;
  13765. }
  13766. S.Diag(Loc, diag::err_call_function_incomplete_return)
  13767. << CE->getSourceRange() << FD->getDeclName() << T;
  13768. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  13769. << FD->getDeclName();
  13770. }
  13771. } Diagnoser(FD, CE);
  13772. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  13773. return true;
  13774. return false;
  13775. }
  13776. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  13777. // will prevent this condition from triggering, which is what we want.
  13778. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  13779. SourceLocation Loc;
  13780. unsigned diagnostic = diag::warn_condition_is_assignment;
  13781. bool IsOrAssign = false;
  13782. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  13783. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  13784. return;
  13785. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  13786. // Greylist some idioms by putting them into a warning subcategory.
  13787. if (ObjCMessageExpr *ME
  13788. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  13789. Selector Sel = ME->getSelector();
  13790. // self = [<foo> init...]
  13791. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  13792. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  13793. // <foo> = [<bar> nextObject]
  13794. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  13795. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  13796. }
  13797. Loc = Op->getOperatorLoc();
  13798. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  13799. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  13800. return;
  13801. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  13802. Loc = Op->getOperatorLoc();
  13803. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  13804. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  13805. else {
  13806. // Not an assignment.
  13807. return;
  13808. }
  13809. Diag(Loc, diagnostic) << E->getSourceRange();
  13810. SourceLocation Open = E->getLocStart();
  13811. SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
  13812. Diag(Loc, diag::note_condition_assign_silence)
  13813. << FixItHint::CreateInsertion(Open, "(")
  13814. << FixItHint::CreateInsertion(Close, ")");
  13815. if (IsOrAssign)
  13816. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  13817. << FixItHint::CreateReplacement(Loc, "!=");
  13818. else
  13819. Diag(Loc, diag::note_condition_assign_to_comparison)
  13820. << FixItHint::CreateReplacement(Loc, "==");
  13821. }
  13822. /// Redundant parentheses over an equality comparison can indicate
  13823. /// that the user intended an assignment used as condition.
  13824. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  13825. // Don't warn if the parens came from a macro.
  13826. SourceLocation parenLoc = ParenE->getLocStart();
  13827. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  13828. return;
  13829. // Don't warn for dependent expressions.
  13830. if (ParenE->isTypeDependent())
  13831. return;
  13832. Expr *E = ParenE->IgnoreParens();
  13833. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  13834. if (opE->getOpcode() == BO_EQ &&
  13835. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  13836. == Expr::MLV_Valid) {
  13837. SourceLocation Loc = opE->getOperatorLoc();
  13838. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  13839. SourceRange ParenERange = ParenE->getSourceRange();
  13840. Diag(Loc, diag::note_equality_comparison_silence)
  13841. << FixItHint::CreateRemoval(ParenERange.getBegin())
  13842. << FixItHint::CreateRemoval(ParenERange.getEnd());
  13843. Diag(Loc, diag::note_equality_comparison_to_assign)
  13844. << FixItHint::CreateReplacement(Loc, "=");
  13845. }
  13846. }
  13847. ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
  13848. bool IsConstexpr) {
  13849. DiagnoseAssignmentAsCondition(E);
  13850. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  13851. DiagnoseEqualityWithExtraParens(parenE);
  13852. ExprResult result = CheckPlaceholderExpr(E);
  13853. if (result.isInvalid()) return ExprError();
  13854. E = result.get();
  13855. if (!E->isTypeDependent()) {
  13856. if (getLangOpts().CPlusPlus)
  13857. return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
  13858. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  13859. if (ERes.isInvalid())
  13860. return ExprError();
  13861. E = ERes.get();
  13862. QualType T = E->getType();
  13863. if (!T->isScalarType()) { // C99 6.8.4.1p1
  13864. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  13865. << T << E->getSourceRange();
  13866. return ExprError();
  13867. }
  13868. CheckBoolLikeConversion(E, Loc);
  13869. }
  13870. return E;
  13871. }
  13872. Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
  13873. Expr *SubExpr, ConditionKind CK) {
  13874. // Empty conditions are valid in for-statements.
  13875. if (!SubExpr)
  13876. return ConditionResult();
  13877. ExprResult Cond;
  13878. switch (CK) {
  13879. case ConditionKind::Boolean:
  13880. Cond = CheckBooleanCondition(Loc, SubExpr);
  13881. break;
  13882. case ConditionKind::ConstexprIf:
  13883. Cond = CheckBooleanCondition(Loc, SubExpr, true);
  13884. break;
  13885. case ConditionKind::Switch:
  13886. Cond = CheckSwitchCondition(Loc, SubExpr);
  13887. break;
  13888. }
  13889. if (Cond.isInvalid())
  13890. return ConditionError();
  13891. // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
  13892. FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
  13893. if (!FullExpr.get())
  13894. return ConditionError();
  13895. return ConditionResult(*this, nullptr, FullExpr,
  13896. CK == ConditionKind::ConstexprIf);
  13897. }
  13898. namespace {
  13899. /// A visitor for rebuilding a call to an __unknown_any expression
  13900. /// to have an appropriate type.
  13901. struct RebuildUnknownAnyFunction
  13902. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  13903. Sema &S;
  13904. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  13905. ExprResult VisitStmt(Stmt *S) {
  13906. llvm_unreachable("unexpected statement!");
  13907. }
  13908. ExprResult VisitExpr(Expr *E) {
  13909. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  13910. << E->getSourceRange();
  13911. return ExprError();
  13912. }
  13913. /// Rebuild an expression which simply semantically wraps another
  13914. /// expression which it shares the type and value kind of.
  13915. template <class T> ExprResult rebuildSugarExpr(T *E) {
  13916. ExprResult SubResult = Visit(E->getSubExpr());
  13917. if (SubResult.isInvalid()) return ExprError();
  13918. Expr *SubExpr = SubResult.get();
  13919. E->setSubExpr(SubExpr);
  13920. E->setType(SubExpr->getType());
  13921. E->setValueKind(SubExpr->getValueKind());
  13922. assert(E->getObjectKind() == OK_Ordinary);
  13923. return E;
  13924. }
  13925. ExprResult VisitParenExpr(ParenExpr *E) {
  13926. return rebuildSugarExpr(E);
  13927. }
  13928. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  13929. return rebuildSugarExpr(E);
  13930. }
  13931. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  13932. ExprResult SubResult = Visit(E->getSubExpr());
  13933. if (SubResult.isInvalid()) return ExprError();
  13934. Expr *SubExpr = SubResult.get();
  13935. E->setSubExpr(SubExpr);
  13936. E->setType(S.Context.getPointerType(SubExpr->getType()));
  13937. assert(E->getValueKind() == VK_RValue);
  13938. assert(E->getObjectKind() == OK_Ordinary);
  13939. return E;
  13940. }
  13941. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  13942. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  13943. E->setType(VD->getType());
  13944. assert(E->getValueKind() == VK_RValue);
  13945. if (S.getLangOpts().CPlusPlus &&
  13946. !(isa<CXXMethodDecl>(VD) &&
  13947. cast<CXXMethodDecl>(VD)->isInstance()))
  13948. E->setValueKind(VK_LValue);
  13949. return E;
  13950. }
  13951. ExprResult VisitMemberExpr(MemberExpr *E) {
  13952. return resolveDecl(E, E->getMemberDecl());
  13953. }
  13954. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  13955. return resolveDecl(E, E->getDecl());
  13956. }
  13957. };
  13958. }
  13959. /// Given a function expression of unknown-any type, try to rebuild it
  13960. /// to have a function type.
  13961. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  13962. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  13963. if (Result.isInvalid()) return ExprError();
  13964. return S.DefaultFunctionArrayConversion(Result.get());
  13965. }
  13966. namespace {
  13967. /// A visitor for rebuilding an expression of type __unknown_anytype
  13968. /// into one which resolves the type directly on the referring
  13969. /// expression. Strict preservation of the original source
  13970. /// structure is not a goal.
  13971. struct RebuildUnknownAnyExpr
  13972. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  13973. Sema &S;
  13974. /// The current destination type.
  13975. QualType DestType;
  13976. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  13977. : S(S), DestType(CastType) {}
  13978. ExprResult VisitStmt(Stmt *S) {
  13979. llvm_unreachable("unexpected statement!");
  13980. }
  13981. ExprResult VisitExpr(Expr *E) {
  13982. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  13983. << E->getSourceRange();
  13984. return ExprError();
  13985. }
  13986. ExprResult VisitCallExpr(CallExpr *E);
  13987. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  13988. /// Rebuild an expression which simply semantically wraps another
  13989. /// expression which it shares the type and value kind of.
  13990. template <class T> ExprResult rebuildSugarExpr(T *E) {
  13991. ExprResult SubResult = Visit(E->getSubExpr());
  13992. if (SubResult.isInvalid()) return ExprError();
  13993. Expr *SubExpr = SubResult.get();
  13994. E->setSubExpr(SubExpr);
  13995. E->setType(SubExpr->getType());
  13996. E->setValueKind(SubExpr->getValueKind());
  13997. assert(E->getObjectKind() == OK_Ordinary);
  13998. return E;
  13999. }
  14000. ExprResult VisitParenExpr(ParenExpr *E) {
  14001. return rebuildSugarExpr(E);
  14002. }
  14003. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  14004. return rebuildSugarExpr(E);
  14005. }
  14006. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  14007. const PointerType *Ptr = DestType->getAs<PointerType>();
  14008. if (!Ptr) {
  14009. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  14010. << E->getSourceRange();
  14011. return ExprError();
  14012. }
  14013. if (isa<CallExpr>(E->getSubExpr())) {
  14014. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
  14015. << E->getSourceRange();
  14016. return ExprError();
  14017. }
  14018. assert(E->getValueKind() == VK_RValue);
  14019. assert(E->getObjectKind() == OK_Ordinary);
  14020. E->setType(DestType);
  14021. // Build the sub-expression as if it were an object of the pointee type.
  14022. DestType = Ptr->getPointeeType();
  14023. ExprResult SubResult = Visit(E->getSubExpr());
  14024. if (SubResult.isInvalid()) return ExprError();
  14025. E->setSubExpr(SubResult.get());
  14026. return E;
  14027. }
  14028. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  14029. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  14030. ExprResult VisitMemberExpr(MemberExpr *E) {
  14031. return resolveDecl(E, E->getMemberDecl());
  14032. }
  14033. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  14034. return resolveDecl(E, E->getDecl());
  14035. }
  14036. };
  14037. }
  14038. /// Rebuilds a call expression which yielded __unknown_anytype.
  14039. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  14040. Expr *CalleeExpr = E->getCallee();
  14041. enum FnKind {
  14042. FK_MemberFunction,
  14043. FK_FunctionPointer,
  14044. FK_BlockPointer
  14045. };
  14046. FnKind Kind;
  14047. QualType CalleeType = CalleeExpr->getType();
  14048. if (CalleeType == S.Context.BoundMemberTy) {
  14049. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  14050. Kind = FK_MemberFunction;
  14051. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  14052. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  14053. CalleeType = Ptr->getPointeeType();
  14054. Kind = FK_FunctionPointer;
  14055. } else {
  14056. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  14057. Kind = FK_BlockPointer;
  14058. }
  14059. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  14060. // Verify that this is a legal result type of a function.
  14061. if (DestType->isArrayType() || DestType->isFunctionType()) {
  14062. unsigned diagID = diag::err_func_returning_array_function;
  14063. if (Kind == FK_BlockPointer)
  14064. diagID = diag::err_block_returning_array_function;
  14065. S.Diag(E->getExprLoc(), diagID)
  14066. << DestType->isFunctionType() << DestType;
  14067. return ExprError();
  14068. }
  14069. // Otherwise, go ahead and set DestType as the call's result.
  14070. E->setType(DestType.getNonLValueExprType(S.Context));
  14071. E->setValueKind(Expr::getValueKindForType(DestType));
  14072. assert(E->getObjectKind() == OK_Ordinary);
  14073. // Rebuild the function type, replacing the result type with DestType.
  14074. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  14075. if (Proto) {
  14076. // __unknown_anytype(...) is a special case used by the debugger when
  14077. // it has no idea what a function's signature is.
  14078. //
  14079. // We want to build this call essentially under the K&R
  14080. // unprototyped rules, but making a FunctionNoProtoType in C++
  14081. // would foul up all sorts of assumptions. However, we cannot
  14082. // simply pass all arguments as variadic arguments, nor can we
  14083. // portably just call the function under a non-variadic type; see
  14084. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  14085. // However, it turns out that in practice it is generally safe to
  14086. // call a function declared as "A foo(B,C,D);" under the prototype
  14087. // "A foo(B,C,D,...);". The only known exception is with the
  14088. // Windows ABI, where any variadic function is implicitly cdecl
  14089. // regardless of its normal CC. Therefore we change the parameter
  14090. // types to match the types of the arguments.
  14091. //
  14092. // This is a hack, but it is far superior to moving the
  14093. // corresponding target-specific code from IR-gen to Sema/AST.
  14094. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  14095. SmallVector<QualType, 8> ArgTypes;
  14096. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  14097. ArgTypes.reserve(E->getNumArgs());
  14098. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  14099. Expr *Arg = E->getArg(i);
  14100. QualType ArgType = Arg->getType();
  14101. if (E->isLValue()) {
  14102. ArgType = S.Context.getLValueReferenceType(ArgType);
  14103. } else if (E->isXValue()) {
  14104. ArgType = S.Context.getRValueReferenceType(ArgType);
  14105. }
  14106. ArgTypes.push_back(ArgType);
  14107. }
  14108. ParamTypes = ArgTypes;
  14109. }
  14110. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  14111. Proto->getExtProtoInfo());
  14112. } else {
  14113. DestType = S.Context.getFunctionNoProtoType(DestType,
  14114. FnType->getExtInfo());
  14115. }
  14116. // Rebuild the appropriate pointer-to-function type.
  14117. switch (Kind) {
  14118. case FK_MemberFunction:
  14119. // Nothing to do.
  14120. break;
  14121. case FK_FunctionPointer:
  14122. DestType = S.Context.getPointerType(DestType);
  14123. break;
  14124. case FK_BlockPointer:
  14125. DestType = S.Context.getBlockPointerType(DestType);
  14126. break;
  14127. }
  14128. // Finally, we can recurse.
  14129. ExprResult CalleeResult = Visit(CalleeExpr);
  14130. if (!CalleeResult.isUsable()) return ExprError();
  14131. E->setCallee(CalleeResult.get());
  14132. // Bind a temporary if necessary.
  14133. return S.MaybeBindToTemporary(E);
  14134. }
  14135. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  14136. // Verify that this is a legal result type of a call.
  14137. if (DestType->isArrayType() || DestType->isFunctionType()) {
  14138. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  14139. << DestType->isFunctionType() << DestType;
  14140. return ExprError();
  14141. }
  14142. // Rewrite the method result type if available.
  14143. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  14144. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  14145. Method->setReturnType(DestType);
  14146. }
  14147. // Change the type of the message.
  14148. E->setType(DestType.getNonReferenceType());
  14149. E->setValueKind(Expr::getValueKindForType(DestType));
  14150. return S.MaybeBindToTemporary(E);
  14151. }
  14152. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  14153. // The only case we should ever see here is a function-to-pointer decay.
  14154. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  14155. assert(E->getValueKind() == VK_RValue);
  14156. assert(E->getObjectKind() == OK_Ordinary);
  14157. E->setType(DestType);
  14158. // Rebuild the sub-expression as the pointee (function) type.
  14159. DestType = DestType->castAs<PointerType>()->getPointeeType();
  14160. ExprResult Result = Visit(E->getSubExpr());
  14161. if (!Result.isUsable()) return ExprError();
  14162. E->setSubExpr(Result.get());
  14163. return E;
  14164. } else if (E->getCastKind() == CK_LValueToRValue) {
  14165. assert(E->getValueKind() == VK_RValue);
  14166. assert(E->getObjectKind() == OK_Ordinary);
  14167. assert(isa<BlockPointerType>(E->getType()));
  14168. E->setType(DestType);
  14169. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  14170. DestType = S.Context.getLValueReferenceType(DestType);
  14171. ExprResult Result = Visit(E->getSubExpr());
  14172. if (!Result.isUsable()) return ExprError();
  14173. E->setSubExpr(Result.get());
  14174. return E;
  14175. } else {
  14176. llvm_unreachable("Unhandled cast type!");
  14177. }
  14178. }
  14179. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  14180. ExprValueKind ValueKind = VK_LValue;
  14181. QualType Type = DestType;
  14182. // We know how to make this work for certain kinds of decls:
  14183. // - functions
  14184. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  14185. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  14186. DestType = Ptr->getPointeeType();
  14187. ExprResult Result = resolveDecl(E, VD);
  14188. if (Result.isInvalid()) return ExprError();
  14189. return S.ImpCastExprToType(Result.get(), Type,
  14190. CK_FunctionToPointerDecay, VK_RValue);
  14191. }
  14192. if (!Type->isFunctionType()) {
  14193. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  14194. << VD << E->getSourceRange();
  14195. return ExprError();
  14196. }
  14197. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  14198. // We must match the FunctionDecl's type to the hack introduced in
  14199. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  14200. // type. See the lengthy commentary in that routine.
  14201. QualType FDT = FD->getType();
  14202. const FunctionType *FnType = FDT->castAs<FunctionType>();
  14203. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  14204. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  14205. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  14206. SourceLocation Loc = FD->getLocation();
  14207. FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
  14208. FD->getDeclContext(),
  14209. Loc, Loc, FD->getNameInfo().getName(),
  14210. DestType, FD->getTypeSourceInfo(),
  14211. SC_None, false/*isInlineSpecified*/,
  14212. FD->hasPrototype(),
  14213. false/*isConstexprSpecified*/);
  14214. if (FD->getQualifier())
  14215. NewFD->setQualifierInfo(FD->getQualifierLoc());
  14216. SmallVector<ParmVarDecl*, 16> Params;
  14217. for (const auto &AI : FT->param_types()) {
  14218. ParmVarDecl *Param =
  14219. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  14220. Param->setScopeInfo(0, Params.size());
  14221. Params.push_back(Param);
  14222. }
  14223. NewFD->setParams(Params);
  14224. DRE->setDecl(NewFD);
  14225. VD = DRE->getDecl();
  14226. }
  14227. }
  14228. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  14229. if (MD->isInstance()) {
  14230. ValueKind = VK_RValue;
  14231. Type = S.Context.BoundMemberTy;
  14232. }
  14233. // Function references aren't l-values in C.
  14234. if (!S.getLangOpts().CPlusPlus)
  14235. ValueKind = VK_RValue;
  14236. // - variables
  14237. } else if (isa<VarDecl>(VD)) {
  14238. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  14239. Type = RefTy->getPointeeType();
  14240. } else if (Type->isFunctionType()) {
  14241. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  14242. << VD << E->getSourceRange();
  14243. return ExprError();
  14244. }
  14245. // - nothing else
  14246. } else {
  14247. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  14248. << VD << E->getSourceRange();
  14249. return ExprError();
  14250. }
  14251. // Modifying the declaration like this is friendly to IR-gen but
  14252. // also really dangerous.
  14253. VD->setType(DestType);
  14254. E->setType(Type);
  14255. E->setValueKind(ValueKind);
  14256. return E;
  14257. }
  14258. /// Check a cast of an unknown-any type. We intentionally only
  14259. /// trigger this for C-style casts.
  14260. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  14261. Expr *CastExpr, CastKind &CastKind,
  14262. ExprValueKind &VK, CXXCastPath &Path) {
  14263. // The type we're casting to must be either void or complete.
  14264. if (!CastType->isVoidType() &&
  14265. RequireCompleteType(TypeRange.getBegin(), CastType,
  14266. diag::err_typecheck_cast_to_incomplete))
  14267. return ExprError();
  14268. // Rewrite the casted expression from scratch.
  14269. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  14270. if (!result.isUsable()) return ExprError();
  14271. CastExpr = result.get();
  14272. VK = CastExpr->getValueKind();
  14273. CastKind = CK_NoOp;
  14274. return CastExpr;
  14275. }
  14276. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  14277. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  14278. }
  14279. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  14280. Expr *arg, QualType &paramType) {
  14281. // If the syntactic form of the argument is not an explicit cast of
  14282. // any sort, just do default argument promotion.
  14283. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  14284. if (!castArg) {
  14285. ExprResult result = DefaultArgumentPromotion(arg);
  14286. if (result.isInvalid()) return ExprError();
  14287. paramType = result.get()->getType();
  14288. return result;
  14289. }
  14290. // Otherwise, use the type that was written in the explicit cast.
  14291. assert(!arg->hasPlaceholderType());
  14292. paramType = castArg->getTypeAsWritten();
  14293. // Copy-initialize a parameter of that type.
  14294. InitializedEntity entity =
  14295. InitializedEntity::InitializeParameter(Context, paramType,
  14296. /*consumed*/ false);
  14297. return PerformCopyInitialization(entity, callLoc, arg);
  14298. }
  14299. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  14300. Expr *orig = E;
  14301. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  14302. while (true) {
  14303. E = E->IgnoreParenImpCasts();
  14304. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  14305. E = call->getCallee();
  14306. diagID = diag::err_uncasted_call_of_unknown_any;
  14307. } else {
  14308. break;
  14309. }
  14310. }
  14311. SourceLocation loc;
  14312. NamedDecl *d;
  14313. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  14314. loc = ref->getLocation();
  14315. d = ref->getDecl();
  14316. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  14317. loc = mem->getMemberLoc();
  14318. d = mem->getMemberDecl();
  14319. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  14320. diagID = diag::err_uncasted_call_of_unknown_any;
  14321. loc = msg->getSelectorStartLoc();
  14322. d = msg->getMethodDecl();
  14323. if (!d) {
  14324. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  14325. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  14326. << orig->getSourceRange();
  14327. return ExprError();
  14328. }
  14329. } else {
  14330. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  14331. << E->getSourceRange();
  14332. return ExprError();
  14333. }
  14334. S.Diag(loc, diagID) << d << orig->getSourceRange();
  14335. // Never recoverable.
  14336. return ExprError();
  14337. }
  14338. /// Check for operands with placeholder types and complain if found.
  14339. /// Returns ExprError() if there was an error and no recovery was possible.
  14340. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  14341. if (!getLangOpts().CPlusPlus) {
  14342. // C cannot handle TypoExpr nodes on either side of a binop because it
  14343. // doesn't handle dependent types properly, so make sure any TypoExprs have
  14344. // been dealt with before checking the operands.
  14345. ExprResult Result = CorrectDelayedTyposInExpr(E);
  14346. if (!Result.isUsable()) return ExprError();
  14347. E = Result.get();
  14348. }
  14349. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  14350. if (!placeholderType) return E;
  14351. switch (placeholderType->getKind()) {
  14352. // Overloaded expressions.
  14353. case BuiltinType::Overload: {
  14354. // Try to resolve a single function template specialization.
  14355. // This is obligatory.
  14356. ExprResult Result = E;
  14357. if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
  14358. return Result;
  14359. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  14360. // leaves Result unchanged on failure.
  14361. Result = E;
  14362. if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
  14363. return Result;
  14364. // If that failed, try to recover with a call.
  14365. tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
  14366. /*complain*/ true);
  14367. return Result;
  14368. }
  14369. // Bound member functions.
  14370. case BuiltinType::BoundMember: {
  14371. ExprResult result = E;
  14372. const Expr *BME = E->IgnoreParens();
  14373. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  14374. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  14375. if (isa<CXXPseudoDestructorExpr>(BME)) {
  14376. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  14377. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  14378. if (ME->getMemberNameInfo().getName().getNameKind() ==
  14379. DeclarationName::CXXDestructorName)
  14380. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  14381. }
  14382. tryToRecoverWithCall(result, PD,
  14383. /*complain*/ true);
  14384. return result;
  14385. }
  14386. // ARC unbridged casts.
  14387. case BuiltinType::ARCUnbridgedCast: {
  14388. Expr *realCast = stripARCUnbridgedCast(E);
  14389. diagnoseARCUnbridgedCast(realCast);
  14390. return realCast;
  14391. }
  14392. // Expressions of unknown type.
  14393. case BuiltinType::UnknownAny:
  14394. return diagnoseUnknownAnyExpr(*this, E);
  14395. // Pseudo-objects.
  14396. case BuiltinType::PseudoObject:
  14397. return checkPseudoObjectRValue(E);
  14398. case BuiltinType::BuiltinFn: {
  14399. // Accept __noop without parens by implicitly converting it to a call expr.
  14400. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  14401. if (DRE) {
  14402. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  14403. if (FD->getBuiltinID() == Builtin::BI__noop) {
  14404. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  14405. CK_BuiltinFnToFnPtr).get();
  14406. return new (Context) CallExpr(Context, E, None, Context.IntTy,
  14407. VK_RValue, SourceLocation());
  14408. }
  14409. }
  14410. Diag(E->getLocStart(), diag::err_builtin_fn_use);
  14411. return ExprError();
  14412. }
  14413. // Expressions of unknown type.
  14414. case BuiltinType::OMPArraySection:
  14415. Diag(E->getLocStart(), diag::err_omp_array_section_use);
  14416. return ExprError();
  14417. // Everything else should be impossible.
  14418. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  14419. case BuiltinType::Id:
  14420. #include "clang/Basic/OpenCLImageTypes.def"
  14421. #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
  14422. #define PLACEHOLDER_TYPE(Id, SingletonId)
  14423. #include "clang/AST/BuiltinTypes.def"
  14424. break;
  14425. }
  14426. llvm_unreachable("invalid placeholder type!");
  14427. }
  14428. bool Sema::CheckCaseExpression(Expr *E) {
  14429. if (E->isTypeDependent())
  14430. return true;
  14431. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  14432. return E->getType()->isIntegralOrEnumerationType();
  14433. return false;
  14434. }
  14435. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  14436. ExprResult
  14437. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  14438. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  14439. "Unknown Objective-C Boolean value!");
  14440. QualType BoolT = Context.ObjCBuiltinBoolTy;
  14441. if (!Context.getBOOLDecl()) {
  14442. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  14443. Sema::LookupOrdinaryName);
  14444. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  14445. NamedDecl *ND = Result.getFoundDecl();
  14446. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  14447. Context.setBOOLDecl(TD);
  14448. }
  14449. }
  14450. if (Context.getBOOLDecl())
  14451. BoolT = Context.getBOOLType();
  14452. return new (Context)
  14453. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  14454. }
  14455. ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
  14456. llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
  14457. SourceLocation RParen) {
  14458. StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
  14459. auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
  14460. [&](const AvailabilitySpec &Spec) {
  14461. return Spec.getPlatform() == Platform;
  14462. });
  14463. VersionTuple Version;
  14464. if (Spec != AvailSpecs.end())
  14465. Version = Spec->getVersion();
  14466. // The use of `@available` in the enclosing function should be analyzed to
  14467. // warn when it's used inappropriately (i.e. not if(@available)).
  14468. if (getCurFunctionOrMethodDecl())
  14469. getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
  14470. else if (getCurBlock() || getCurLambda())
  14471. getCurFunction()->HasPotentialAvailabilityViolations = true;
  14472. return new (Context)
  14473. ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
  14474. }