SemaChecking.cpp 354 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763
  1. //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
  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 extra semantic analysis beyond what is enforced
  11. // by the C type system.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Sema/SemaInternal.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/CharUnits.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/EvaluatedExprVisitor.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/ExprObjC.h"
  23. #include "clang/AST/ExprOpenMP.h"
  24. #include "clang/AST/StmtCXX.h"
  25. #include "clang/AST/StmtObjC.h"
  26. #include "clang/Analysis/Analyses/FormatString.h"
  27. #include "clang/Basic/CharInfo.h"
  28. #include "clang/Basic/TargetBuiltins.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  31. #include "clang/Sema/Initialization.h"
  32. #include "clang/Sema/Lookup.h"
  33. #include "clang/Sema/ScopeInfo.h"
  34. #include "clang/Sema/Sema.h"
  35. #include "llvm/ADT/STLExtras.h"
  36. #include "llvm/ADT/SmallBitVector.h"
  37. #include "llvm/ADT/SmallString.h"
  38. #include "llvm/Support/ConvertUTF.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include <limits>
  41. using namespace clang;
  42. using namespace sema;
  43. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  44. unsigned ByteNo) const {
  45. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  46. Context.getTargetInfo());
  47. }
  48. /// Checks that a call expression's argument count is the desired number.
  49. /// This is useful when doing custom type-checking. Returns true on error.
  50. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  51. unsigned argCount = call->getNumArgs();
  52. if (argCount == desiredArgCount) return false;
  53. if (argCount < desiredArgCount)
  54. return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
  55. << 0 /*function call*/ << desiredArgCount << argCount
  56. << call->getSourceRange();
  57. // Highlight all the excess arguments.
  58. SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
  59. call->getArg(argCount - 1)->getLocEnd());
  60. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  61. << 0 /*function call*/ << desiredArgCount << argCount
  62. << call->getArg(1)->getSourceRange();
  63. }
  64. /// Check that the first argument to __builtin_annotation is an integer
  65. /// and the second argument is a non-wide string literal.
  66. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  67. if (checkArgCount(S, TheCall, 2))
  68. return true;
  69. // First argument should be an integer.
  70. Expr *ValArg = TheCall->getArg(0);
  71. QualType Ty = ValArg->getType();
  72. if (!Ty->isIntegerType()) {
  73. S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
  74. << ValArg->getSourceRange();
  75. return true;
  76. }
  77. // Second argument should be a constant string.
  78. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  79. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  80. if (!Literal || !Literal->isAscii()) {
  81. S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
  82. << StrArg->getSourceRange();
  83. return true;
  84. }
  85. TheCall->setType(Ty);
  86. return false;
  87. }
  88. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  89. /// result type to the corresponding pointer type.
  90. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  91. if (checkArgCount(S, TheCall, 1))
  92. return true;
  93. ExprResult Arg(TheCall->getArg(0));
  94. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
  95. if (ResultType.isNull())
  96. return true;
  97. TheCall->setArg(0, Arg.get());
  98. TheCall->setType(ResultType);
  99. return false;
  100. }
  101. static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
  102. CallExpr *TheCall, unsigned SizeIdx,
  103. unsigned DstSizeIdx) {
  104. if (TheCall->getNumArgs() <= SizeIdx ||
  105. TheCall->getNumArgs() <= DstSizeIdx)
  106. return;
  107. const Expr *SizeArg = TheCall->getArg(SizeIdx);
  108. const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
  109. llvm::APSInt Size, DstSize;
  110. // find out if both sizes are known at compile time
  111. if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
  112. !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
  113. return;
  114. if (Size.ule(DstSize))
  115. return;
  116. // confirmed overflow so generate the diagnostic.
  117. IdentifierInfo *FnName = FDecl->getIdentifier();
  118. SourceLocation SL = TheCall->getLocStart();
  119. SourceRange SR = TheCall->getSourceRange();
  120. S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
  121. }
  122. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  123. if (checkArgCount(S, BuiltinCall, 2))
  124. return true;
  125. SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
  126. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  127. Expr *Call = BuiltinCall->getArg(0);
  128. Expr *Chain = BuiltinCall->getArg(1);
  129. if (Call->getStmtClass() != Stmt::CallExprClass) {
  130. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  131. << Call->getSourceRange();
  132. return true;
  133. }
  134. auto CE = cast<CallExpr>(Call);
  135. if (CE->getCallee()->getType()->isBlockPointerType()) {
  136. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  137. << Call->getSourceRange();
  138. return true;
  139. }
  140. const Decl *TargetDecl = CE->getCalleeDecl();
  141. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  142. if (FD->getBuiltinID()) {
  143. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  144. << Call->getSourceRange();
  145. return true;
  146. }
  147. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  148. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  149. << Call->getSourceRange();
  150. return true;
  151. }
  152. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  153. if (ChainResult.isInvalid())
  154. return true;
  155. if (!ChainResult.get()->getType()->isPointerType()) {
  156. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  157. << Chain->getSourceRange();
  158. return true;
  159. }
  160. QualType ReturnTy = CE->getCallReturnType(S.Context);
  161. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  162. QualType BuiltinTy = S.Context.getFunctionType(
  163. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  164. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  165. Builtin =
  166. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  167. BuiltinCall->setType(CE->getType());
  168. BuiltinCall->setValueKind(CE->getValueKind());
  169. BuiltinCall->setObjectKind(CE->getObjectKind());
  170. BuiltinCall->setCallee(Builtin);
  171. BuiltinCall->setArg(1, ChainResult.get());
  172. return false;
  173. }
  174. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  175. Scope::ScopeFlags NeededScopeFlags,
  176. unsigned DiagID) {
  177. // Scopes aren't available during instantiation. Fortunately, builtin
  178. // functions cannot be template args so they cannot be formed through template
  179. // instantiation. Therefore checking once during the parse is sufficient.
  180. if (!SemaRef.ActiveTemplateInstantiations.empty())
  181. return false;
  182. Scope *S = SemaRef.getCurScope();
  183. while (S && !S->isSEHExceptScope())
  184. S = S->getParent();
  185. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  186. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  187. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  188. << DRE->getDecl()->getIdentifier();
  189. return true;
  190. }
  191. return false;
  192. }
  193. ExprResult
  194. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  195. CallExpr *TheCall) {
  196. ExprResult TheCallResult(TheCall);
  197. // Find out if any arguments are required to be integer constant expressions.
  198. unsigned ICEArguments = 0;
  199. ASTContext::GetBuiltinTypeError Error;
  200. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  201. if (Error != ASTContext::GE_None)
  202. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  203. // If any arguments are required to be ICE's, check and diagnose.
  204. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  205. // Skip arguments not required to be ICE's.
  206. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  207. llvm::APSInt Result;
  208. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  209. return true;
  210. ICEArguments &= ~(1 << ArgNo);
  211. }
  212. switch (BuiltinID) {
  213. case Builtin::BI__builtin___CFStringMakeConstantString:
  214. assert(TheCall->getNumArgs() == 1 &&
  215. "Wrong # arguments to builtin CFStringMakeConstantString");
  216. if (CheckObjCString(TheCall->getArg(0)))
  217. return ExprError();
  218. break;
  219. case Builtin::BI__builtin_stdarg_start:
  220. case Builtin::BI__builtin_va_start:
  221. if (SemaBuiltinVAStart(TheCall))
  222. return ExprError();
  223. break;
  224. case Builtin::BI__va_start: {
  225. switch (Context.getTargetInfo().getTriple().getArch()) {
  226. case llvm::Triple::arm:
  227. case llvm::Triple::thumb:
  228. if (SemaBuiltinVAStartARM(TheCall))
  229. return ExprError();
  230. break;
  231. default:
  232. if (SemaBuiltinVAStart(TheCall))
  233. return ExprError();
  234. break;
  235. }
  236. break;
  237. }
  238. case Builtin::BI__builtin_isgreater:
  239. case Builtin::BI__builtin_isgreaterequal:
  240. case Builtin::BI__builtin_isless:
  241. case Builtin::BI__builtin_islessequal:
  242. case Builtin::BI__builtin_islessgreater:
  243. case Builtin::BI__builtin_isunordered:
  244. if (SemaBuiltinUnorderedCompare(TheCall))
  245. return ExprError();
  246. break;
  247. case Builtin::BI__builtin_fpclassify:
  248. if (SemaBuiltinFPClassification(TheCall, 6))
  249. return ExprError();
  250. break;
  251. case Builtin::BI__builtin_isfinite:
  252. case Builtin::BI__builtin_isinf:
  253. case Builtin::BI__builtin_isinf_sign:
  254. case Builtin::BI__builtin_isnan:
  255. case Builtin::BI__builtin_isnormal:
  256. if (SemaBuiltinFPClassification(TheCall, 1))
  257. return ExprError();
  258. break;
  259. case Builtin::BI__builtin_shufflevector:
  260. return SemaBuiltinShuffleVector(TheCall);
  261. // TheCall will be freed by the smart pointer here, but that's fine, since
  262. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  263. case Builtin::BI__builtin_prefetch:
  264. if (SemaBuiltinPrefetch(TheCall))
  265. return ExprError();
  266. break;
  267. case Builtin::BI__assume:
  268. case Builtin::BI__builtin_assume:
  269. if (SemaBuiltinAssume(TheCall))
  270. return ExprError();
  271. break;
  272. case Builtin::BI__builtin_assume_aligned:
  273. if (SemaBuiltinAssumeAligned(TheCall))
  274. return ExprError();
  275. break;
  276. case Builtin::BI__builtin_object_size:
  277. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  278. return ExprError();
  279. break;
  280. case Builtin::BI__builtin_longjmp:
  281. if (SemaBuiltinLongjmp(TheCall))
  282. return ExprError();
  283. break;
  284. case Builtin::BI__builtin_setjmp:
  285. if (SemaBuiltinSetjmp(TheCall))
  286. return ExprError();
  287. break;
  288. case Builtin::BI_setjmp:
  289. case Builtin::BI_setjmpex:
  290. if (checkArgCount(*this, TheCall, 1))
  291. return true;
  292. break;
  293. case Builtin::BI__builtin_classify_type:
  294. if (checkArgCount(*this, TheCall, 1)) return true;
  295. TheCall->setType(Context.IntTy);
  296. break;
  297. case Builtin::BI__builtin_constant_p:
  298. if (checkArgCount(*this, TheCall, 1)) return true;
  299. TheCall->setType(Context.IntTy);
  300. break;
  301. case Builtin::BI__sync_fetch_and_add:
  302. case Builtin::BI__sync_fetch_and_add_1:
  303. case Builtin::BI__sync_fetch_and_add_2:
  304. case Builtin::BI__sync_fetch_and_add_4:
  305. case Builtin::BI__sync_fetch_and_add_8:
  306. case Builtin::BI__sync_fetch_and_add_16:
  307. case Builtin::BI__sync_fetch_and_sub:
  308. case Builtin::BI__sync_fetch_and_sub_1:
  309. case Builtin::BI__sync_fetch_and_sub_2:
  310. case Builtin::BI__sync_fetch_and_sub_4:
  311. case Builtin::BI__sync_fetch_and_sub_8:
  312. case Builtin::BI__sync_fetch_and_sub_16:
  313. case Builtin::BI__sync_fetch_and_or:
  314. case Builtin::BI__sync_fetch_and_or_1:
  315. case Builtin::BI__sync_fetch_and_or_2:
  316. case Builtin::BI__sync_fetch_and_or_4:
  317. case Builtin::BI__sync_fetch_and_or_8:
  318. case Builtin::BI__sync_fetch_and_or_16:
  319. case Builtin::BI__sync_fetch_and_and:
  320. case Builtin::BI__sync_fetch_and_and_1:
  321. case Builtin::BI__sync_fetch_and_and_2:
  322. case Builtin::BI__sync_fetch_and_and_4:
  323. case Builtin::BI__sync_fetch_and_and_8:
  324. case Builtin::BI__sync_fetch_and_and_16:
  325. case Builtin::BI__sync_fetch_and_xor:
  326. case Builtin::BI__sync_fetch_and_xor_1:
  327. case Builtin::BI__sync_fetch_and_xor_2:
  328. case Builtin::BI__sync_fetch_and_xor_4:
  329. case Builtin::BI__sync_fetch_and_xor_8:
  330. case Builtin::BI__sync_fetch_and_xor_16:
  331. case Builtin::BI__sync_fetch_and_nand:
  332. case Builtin::BI__sync_fetch_and_nand_1:
  333. case Builtin::BI__sync_fetch_and_nand_2:
  334. case Builtin::BI__sync_fetch_and_nand_4:
  335. case Builtin::BI__sync_fetch_and_nand_8:
  336. case Builtin::BI__sync_fetch_and_nand_16:
  337. case Builtin::BI__sync_add_and_fetch:
  338. case Builtin::BI__sync_add_and_fetch_1:
  339. case Builtin::BI__sync_add_and_fetch_2:
  340. case Builtin::BI__sync_add_and_fetch_4:
  341. case Builtin::BI__sync_add_and_fetch_8:
  342. case Builtin::BI__sync_add_and_fetch_16:
  343. case Builtin::BI__sync_sub_and_fetch:
  344. case Builtin::BI__sync_sub_and_fetch_1:
  345. case Builtin::BI__sync_sub_and_fetch_2:
  346. case Builtin::BI__sync_sub_and_fetch_4:
  347. case Builtin::BI__sync_sub_and_fetch_8:
  348. case Builtin::BI__sync_sub_and_fetch_16:
  349. case Builtin::BI__sync_and_and_fetch:
  350. case Builtin::BI__sync_and_and_fetch_1:
  351. case Builtin::BI__sync_and_and_fetch_2:
  352. case Builtin::BI__sync_and_and_fetch_4:
  353. case Builtin::BI__sync_and_and_fetch_8:
  354. case Builtin::BI__sync_and_and_fetch_16:
  355. case Builtin::BI__sync_or_and_fetch:
  356. case Builtin::BI__sync_or_and_fetch_1:
  357. case Builtin::BI__sync_or_and_fetch_2:
  358. case Builtin::BI__sync_or_and_fetch_4:
  359. case Builtin::BI__sync_or_and_fetch_8:
  360. case Builtin::BI__sync_or_and_fetch_16:
  361. case Builtin::BI__sync_xor_and_fetch:
  362. case Builtin::BI__sync_xor_and_fetch_1:
  363. case Builtin::BI__sync_xor_and_fetch_2:
  364. case Builtin::BI__sync_xor_and_fetch_4:
  365. case Builtin::BI__sync_xor_and_fetch_8:
  366. case Builtin::BI__sync_xor_and_fetch_16:
  367. case Builtin::BI__sync_nand_and_fetch:
  368. case Builtin::BI__sync_nand_and_fetch_1:
  369. case Builtin::BI__sync_nand_and_fetch_2:
  370. case Builtin::BI__sync_nand_and_fetch_4:
  371. case Builtin::BI__sync_nand_and_fetch_8:
  372. case Builtin::BI__sync_nand_and_fetch_16:
  373. case Builtin::BI__sync_val_compare_and_swap:
  374. case Builtin::BI__sync_val_compare_and_swap_1:
  375. case Builtin::BI__sync_val_compare_and_swap_2:
  376. case Builtin::BI__sync_val_compare_and_swap_4:
  377. case Builtin::BI__sync_val_compare_and_swap_8:
  378. case Builtin::BI__sync_val_compare_and_swap_16:
  379. case Builtin::BI__sync_bool_compare_and_swap:
  380. case Builtin::BI__sync_bool_compare_and_swap_1:
  381. case Builtin::BI__sync_bool_compare_and_swap_2:
  382. case Builtin::BI__sync_bool_compare_and_swap_4:
  383. case Builtin::BI__sync_bool_compare_and_swap_8:
  384. case Builtin::BI__sync_bool_compare_and_swap_16:
  385. case Builtin::BI__sync_lock_test_and_set:
  386. case Builtin::BI__sync_lock_test_and_set_1:
  387. case Builtin::BI__sync_lock_test_and_set_2:
  388. case Builtin::BI__sync_lock_test_and_set_4:
  389. case Builtin::BI__sync_lock_test_and_set_8:
  390. case Builtin::BI__sync_lock_test_and_set_16:
  391. case Builtin::BI__sync_lock_release:
  392. case Builtin::BI__sync_lock_release_1:
  393. case Builtin::BI__sync_lock_release_2:
  394. case Builtin::BI__sync_lock_release_4:
  395. case Builtin::BI__sync_lock_release_8:
  396. case Builtin::BI__sync_lock_release_16:
  397. case Builtin::BI__sync_swap:
  398. case Builtin::BI__sync_swap_1:
  399. case Builtin::BI__sync_swap_2:
  400. case Builtin::BI__sync_swap_4:
  401. case Builtin::BI__sync_swap_8:
  402. case Builtin::BI__sync_swap_16:
  403. return SemaBuiltinAtomicOverloaded(TheCallResult);
  404. case Builtin::BI__builtin_nontemporal_load:
  405. case Builtin::BI__builtin_nontemporal_store:
  406. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  407. #define BUILTIN(ID, TYPE, ATTRS)
  408. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  409. case Builtin::BI##ID: \
  410. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  411. #include "clang/Basic/Builtins.def"
  412. case Builtin::BI__builtin_annotation:
  413. if (SemaBuiltinAnnotation(*this, TheCall))
  414. return ExprError();
  415. break;
  416. case Builtin::BI__builtin_addressof:
  417. if (SemaBuiltinAddressof(*this, TheCall))
  418. return ExprError();
  419. break;
  420. case Builtin::BI__builtin_operator_new:
  421. case Builtin::BI__builtin_operator_delete:
  422. if (!getLangOpts().CPlusPlus) {
  423. Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
  424. << (BuiltinID == Builtin::BI__builtin_operator_new
  425. ? "__builtin_operator_new"
  426. : "__builtin_operator_delete")
  427. << "C++";
  428. return ExprError();
  429. }
  430. // CodeGen assumes it can find the global new and delete to call,
  431. // so ensure that they are declared.
  432. DeclareGlobalNewDelete();
  433. break;
  434. // check secure string manipulation functions where overflows
  435. // are detectable at compile time
  436. case Builtin::BI__builtin___memcpy_chk:
  437. case Builtin::BI__builtin___memmove_chk:
  438. case Builtin::BI__builtin___memset_chk:
  439. case Builtin::BI__builtin___strlcat_chk:
  440. case Builtin::BI__builtin___strlcpy_chk:
  441. case Builtin::BI__builtin___strncat_chk:
  442. case Builtin::BI__builtin___strncpy_chk:
  443. case Builtin::BI__builtin___stpncpy_chk:
  444. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
  445. break;
  446. case Builtin::BI__builtin___memccpy_chk:
  447. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
  448. break;
  449. case Builtin::BI__builtin___snprintf_chk:
  450. case Builtin::BI__builtin___vsnprintf_chk:
  451. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
  452. break;
  453. case Builtin::BI__builtin_call_with_static_chain:
  454. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  455. return ExprError();
  456. break;
  457. case Builtin::BI__exception_code:
  458. case Builtin::BI_exception_code: {
  459. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  460. diag::err_seh___except_block))
  461. return ExprError();
  462. break;
  463. }
  464. case Builtin::BI__exception_info:
  465. case Builtin::BI_exception_info: {
  466. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  467. diag::err_seh___except_filter))
  468. return ExprError();
  469. break;
  470. }
  471. case Builtin::BI__GetExceptionInfo:
  472. if (checkArgCount(*this, TheCall, 1))
  473. return ExprError();
  474. if (CheckCXXThrowOperand(
  475. TheCall->getLocStart(),
  476. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  477. TheCall))
  478. return ExprError();
  479. TheCall->setType(Context.VoidPtrTy);
  480. break;
  481. }
  482. // Since the target specific builtins for each arch overlap, only check those
  483. // of the arch we are compiling for.
  484. if (BuiltinID >= Builtin::FirstTSBuiltin) {
  485. switch (Context.getTargetInfo().getTriple().getArch()) {
  486. case llvm::Triple::arm:
  487. case llvm::Triple::armeb:
  488. case llvm::Triple::thumb:
  489. case llvm::Triple::thumbeb:
  490. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  491. return ExprError();
  492. break;
  493. case llvm::Triple::aarch64:
  494. case llvm::Triple::aarch64_be:
  495. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  496. return ExprError();
  497. break;
  498. case llvm::Triple::mips:
  499. case llvm::Triple::mipsel:
  500. case llvm::Triple::mips64:
  501. case llvm::Triple::mips64el:
  502. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  503. return ExprError();
  504. break;
  505. case llvm::Triple::systemz:
  506. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  507. return ExprError();
  508. break;
  509. case llvm::Triple::x86:
  510. case llvm::Triple::x86_64:
  511. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  512. return ExprError();
  513. break;
  514. case llvm::Triple::ppc:
  515. case llvm::Triple::ppc64:
  516. case llvm::Triple::ppc64le:
  517. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  518. return ExprError();
  519. break;
  520. default:
  521. break;
  522. }
  523. }
  524. return TheCallResult;
  525. }
  526. // Get the valid immediate range for the specified NEON type code.
  527. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  528. NeonTypeFlags Type(t);
  529. int IsQuad = ForceQuad ? true : Type.isQuad();
  530. switch (Type.getEltType()) {
  531. case NeonTypeFlags::Int8:
  532. case NeonTypeFlags::Poly8:
  533. return shift ? 7 : (8 << IsQuad) - 1;
  534. case NeonTypeFlags::Int16:
  535. case NeonTypeFlags::Poly16:
  536. return shift ? 15 : (4 << IsQuad) - 1;
  537. case NeonTypeFlags::Int32:
  538. return shift ? 31 : (2 << IsQuad) - 1;
  539. case NeonTypeFlags::Int64:
  540. case NeonTypeFlags::Poly64:
  541. return shift ? 63 : (1 << IsQuad) - 1;
  542. case NeonTypeFlags::Poly128:
  543. return shift ? 127 : (1 << IsQuad) - 1;
  544. case NeonTypeFlags::Float16:
  545. assert(!shift && "cannot shift float types!");
  546. return (4 << IsQuad) - 1;
  547. case NeonTypeFlags::Float32:
  548. assert(!shift && "cannot shift float types!");
  549. return (2 << IsQuad) - 1;
  550. case NeonTypeFlags::Float64:
  551. assert(!shift && "cannot shift float types!");
  552. return (1 << IsQuad) - 1;
  553. }
  554. llvm_unreachable("Invalid NeonTypeFlag!");
  555. }
  556. /// getNeonEltType - Return the QualType corresponding to the elements of
  557. /// the vector type specified by the NeonTypeFlags. This is used to check
  558. /// the pointer arguments for Neon load/store intrinsics.
  559. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  560. bool IsPolyUnsigned, bool IsInt64Long) {
  561. switch (Flags.getEltType()) {
  562. case NeonTypeFlags::Int8:
  563. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  564. case NeonTypeFlags::Int16:
  565. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  566. case NeonTypeFlags::Int32:
  567. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  568. case NeonTypeFlags::Int64:
  569. if (IsInt64Long)
  570. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  571. else
  572. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  573. : Context.LongLongTy;
  574. case NeonTypeFlags::Poly8:
  575. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  576. case NeonTypeFlags::Poly16:
  577. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  578. case NeonTypeFlags::Poly64:
  579. if (IsInt64Long)
  580. return Context.UnsignedLongTy;
  581. else
  582. return Context.UnsignedLongLongTy;
  583. case NeonTypeFlags::Poly128:
  584. break;
  585. case NeonTypeFlags::Float16:
  586. return Context.HalfTy;
  587. case NeonTypeFlags::Float32:
  588. return Context.FloatTy;
  589. case NeonTypeFlags::Float64:
  590. return Context.DoubleTy;
  591. }
  592. llvm_unreachable("Invalid NeonTypeFlag!");
  593. }
  594. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  595. llvm::APSInt Result;
  596. uint64_t mask = 0;
  597. unsigned TV = 0;
  598. int PtrArgNum = -1;
  599. bool HasConstPtr = false;
  600. switch (BuiltinID) {
  601. #define GET_NEON_OVERLOAD_CHECK
  602. #include "clang/Basic/arm_neon.inc"
  603. #undef GET_NEON_OVERLOAD_CHECK
  604. }
  605. // For NEON intrinsics which are overloaded on vector element type, validate
  606. // the immediate which specifies which variant to emit.
  607. unsigned ImmArg = TheCall->getNumArgs()-1;
  608. if (mask) {
  609. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  610. return true;
  611. TV = Result.getLimitedValue(64);
  612. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  613. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  614. << TheCall->getArg(ImmArg)->getSourceRange();
  615. }
  616. if (PtrArgNum >= 0) {
  617. // Check that pointer arguments have the specified type.
  618. Expr *Arg = TheCall->getArg(PtrArgNum);
  619. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  620. Arg = ICE->getSubExpr();
  621. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  622. QualType RHSTy = RHS.get()->getType();
  623. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  624. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
  625. bool IsInt64Long =
  626. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  627. QualType EltTy =
  628. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  629. if (HasConstPtr)
  630. EltTy = EltTy.withConst();
  631. QualType LHSTy = Context.getPointerType(EltTy);
  632. AssignConvertType ConvTy;
  633. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  634. if (RHS.isInvalid())
  635. return true;
  636. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  637. RHS.get(), AA_Assigning))
  638. return true;
  639. }
  640. // For NEON intrinsics which take an immediate value as part of the
  641. // instruction, range check them here.
  642. unsigned i = 0, l = 0, u = 0;
  643. switch (BuiltinID) {
  644. default:
  645. return false;
  646. #define GET_NEON_IMMEDIATE_CHECK
  647. #include "clang/Basic/arm_neon.inc"
  648. #undef GET_NEON_IMMEDIATE_CHECK
  649. }
  650. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  651. }
  652. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  653. unsigned MaxWidth) {
  654. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  655. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  656. BuiltinID == ARM::BI__builtin_arm_strex ||
  657. BuiltinID == ARM::BI__builtin_arm_stlex ||
  658. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  659. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  660. BuiltinID == AArch64::BI__builtin_arm_strex ||
  661. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  662. "unexpected ARM builtin");
  663. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  664. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  665. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  666. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  667. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  668. // Ensure that we have the proper number of arguments.
  669. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  670. return true;
  671. // Inspect the pointer argument of the atomic builtin. This should always be
  672. // a pointer type, whose element is an integral scalar or pointer type.
  673. // Because it is a pointer type, we don't have to worry about any implicit
  674. // casts here.
  675. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  676. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  677. if (PointerArgRes.isInvalid())
  678. return true;
  679. PointerArg = PointerArgRes.get();
  680. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  681. if (!pointerType) {
  682. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  683. << PointerArg->getType() << PointerArg->getSourceRange();
  684. return true;
  685. }
  686. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  687. // task is to insert the appropriate casts into the AST. First work out just
  688. // what the appropriate type is.
  689. QualType ValType = pointerType->getPointeeType();
  690. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  691. if (IsLdrex)
  692. AddrType.addConst();
  693. // Issue a warning if the cast is dodgy.
  694. CastKind CastNeeded = CK_NoOp;
  695. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  696. CastNeeded = CK_BitCast;
  697. Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
  698. << PointerArg->getType()
  699. << Context.getPointerType(AddrType)
  700. << AA_Passing << PointerArg->getSourceRange();
  701. }
  702. // Finally, do the cast and replace the argument with the corrected version.
  703. AddrType = Context.getPointerType(AddrType);
  704. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  705. if (PointerArgRes.isInvalid())
  706. return true;
  707. PointerArg = PointerArgRes.get();
  708. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  709. // In general, we allow ints, floats and pointers to be loaded and stored.
  710. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  711. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  712. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  713. << PointerArg->getType() << PointerArg->getSourceRange();
  714. return true;
  715. }
  716. // But ARM doesn't have instructions to deal with 128-bit versions.
  717. if (Context.getTypeSize(ValType) > MaxWidth) {
  718. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  719. Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
  720. << PointerArg->getType() << PointerArg->getSourceRange();
  721. return true;
  722. }
  723. switch (ValType.getObjCLifetime()) {
  724. case Qualifiers::OCL_None:
  725. case Qualifiers::OCL_ExplicitNone:
  726. // okay
  727. break;
  728. case Qualifiers::OCL_Weak:
  729. case Qualifiers::OCL_Strong:
  730. case Qualifiers::OCL_Autoreleasing:
  731. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  732. << ValType << PointerArg->getSourceRange();
  733. return true;
  734. }
  735. if (IsLdrex) {
  736. TheCall->setType(ValType);
  737. return false;
  738. }
  739. // Initialize the argument to be stored.
  740. ExprResult ValArg = TheCall->getArg(0);
  741. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  742. Context, ValType, /*consume*/ false);
  743. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  744. if (ValArg.isInvalid())
  745. return true;
  746. TheCall->setArg(0, ValArg.get());
  747. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  748. // but the custom checker bypasses all default analysis.
  749. TheCall->setType(Context.IntTy);
  750. return false;
  751. }
  752. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  753. llvm::APSInt Result;
  754. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  755. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  756. BuiltinID == ARM::BI__builtin_arm_strex ||
  757. BuiltinID == ARM::BI__builtin_arm_stlex) {
  758. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  759. }
  760. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  761. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  762. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  763. }
  764. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  765. BuiltinID == ARM::BI__builtin_arm_wsr64)
  766. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  767. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  768. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  769. BuiltinID == ARM::BI__builtin_arm_wsr ||
  770. BuiltinID == ARM::BI__builtin_arm_wsrp)
  771. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  772. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  773. return true;
  774. // For intrinsics which take an immediate value as part of the instruction,
  775. // range check them here.
  776. unsigned i = 0, l = 0, u = 0;
  777. switch (BuiltinID) {
  778. default: return false;
  779. case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
  780. case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
  781. case ARM::BI__builtin_arm_vcvtr_f:
  782. case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
  783. case ARM::BI__builtin_arm_dmb:
  784. case ARM::BI__builtin_arm_dsb:
  785. case ARM::BI__builtin_arm_isb:
  786. case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
  787. }
  788. // FIXME: VFP Intrinsics should error if VFP not present.
  789. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  790. }
  791. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  792. CallExpr *TheCall) {
  793. llvm::APSInt Result;
  794. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  795. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  796. BuiltinID == AArch64::BI__builtin_arm_strex ||
  797. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  798. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  799. }
  800. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  801. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  802. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  803. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  804. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  805. }
  806. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  807. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  808. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
  809. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  810. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  811. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  812. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  813. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  814. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  815. return true;
  816. // For intrinsics which take an immediate value as part of the instruction,
  817. // range check them here.
  818. unsigned i = 0, l = 0, u = 0;
  819. switch (BuiltinID) {
  820. default: return false;
  821. case AArch64::BI__builtin_arm_dmb:
  822. case AArch64::BI__builtin_arm_dsb:
  823. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  824. }
  825. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  826. }
  827. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  828. unsigned i = 0, l = 0, u = 0;
  829. switch (BuiltinID) {
  830. default: return false;
  831. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  832. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  833. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  834. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  835. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  836. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  837. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  838. }
  839. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  840. }
  841. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  842. unsigned i = 0, l = 0, u = 0;
  843. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  844. BuiltinID == PPC::BI__builtin_divdeu ||
  845. BuiltinID == PPC::BI__builtin_bpermd;
  846. bool IsTarget64Bit = Context.getTargetInfo()
  847. .getTypeWidth(Context
  848. .getTargetInfo()
  849. .getIntPtrType()) == 64;
  850. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  851. BuiltinID == PPC::BI__builtin_divweu ||
  852. BuiltinID == PPC::BI__builtin_divde ||
  853. BuiltinID == PPC::BI__builtin_divdeu;
  854. if (Is64BitBltin && !IsTarget64Bit)
  855. return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
  856. << TheCall->getSourceRange();
  857. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  858. (BuiltinID == PPC::BI__builtin_bpermd &&
  859. !Context.getTargetInfo().hasFeature("bpermd")))
  860. return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
  861. << TheCall->getSourceRange();
  862. switch (BuiltinID) {
  863. default: return false;
  864. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  865. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  866. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  867. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  868. case PPC::BI__builtin_tbegin:
  869. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  870. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  871. case PPC::BI__builtin_tabortwc:
  872. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  873. case PPC::BI__builtin_tabortwci:
  874. case PPC::BI__builtin_tabortdci:
  875. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  876. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  877. }
  878. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  879. }
  880. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  881. CallExpr *TheCall) {
  882. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  883. Expr *Arg = TheCall->getArg(0);
  884. llvm::APSInt AbortCode(32);
  885. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  886. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  887. return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
  888. << Arg->getSourceRange();
  889. }
  890. // For intrinsics which take an immediate value as part of the instruction,
  891. // range check them here.
  892. unsigned i = 0, l = 0, u = 0;
  893. switch (BuiltinID) {
  894. default: return false;
  895. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  896. case SystemZ::BI__builtin_s390_verimb:
  897. case SystemZ::BI__builtin_s390_verimh:
  898. case SystemZ::BI__builtin_s390_verimf:
  899. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  900. case SystemZ::BI__builtin_s390_vfaeb:
  901. case SystemZ::BI__builtin_s390_vfaeh:
  902. case SystemZ::BI__builtin_s390_vfaef:
  903. case SystemZ::BI__builtin_s390_vfaebs:
  904. case SystemZ::BI__builtin_s390_vfaehs:
  905. case SystemZ::BI__builtin_s390_vfaefs:
  906. case SystemZ::BI__builtin_s390_vfaezb:
  907. case SystemZ::BI__builtin_s390_vfaezh:
  908. case SystemZ::BI__builtin_s390_vfaezf:
  909. case SystemZ::BI__builtin_s390_vfaezbs:
  910. case SystemZ::BI__builtin_s390_vfaezhs:
  911. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  912. case SystemZ::BI__builtin_s390_vfidb:
  913. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  914. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  915. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  916. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  917. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  918. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  919. case SystemZ::BI__builtin_s390_vstrcb:
  920. case SystemZ::BI__builtin_s390_vstrch:
  921. case SystemZ::BI__builtin_s390_vstrcf:
  922. case SystemZ::BI__builtin_s390_vstrczb:
  923. case SystemZ::BI__builtin_s390_vstrczh:
  924. case SystemZ::BI__builtin_s390_vstrczf:
  925. case SystemZ::BI__builtin_s390_vstrcbs:
  926. case SystemZ::BI__builtin_s390_vstrchs:
  927. case SystemZ::BI__builtin_s390_vstrcfs:
  928. case SystemZ::BI__builtin_s390_vstrczbs:
  929. case SystemZ::BI__builtin_s390_vstrczhs:
  930. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  931. }
  932. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  933. }
  934. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  935. unsigned i = 0, l = 0, u = 0;
  936. switch (BuiltinID) {
  937. default: return false;
  938. case X86::BI__builtin_cpu_supports:
  939. return SemaBuiltinCpuSupports(TheCall);
  940. case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
  941. case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
  942. case X86::BI__builtin_ia32_vpermil2pd:
  943. case X86::BI__builtin_ia32_vpermil2pd256:
  944. case X86::BI__builtin_ia32_vpermil2ps:
  945. case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
  946. case X86::BI__builtin_ia32_cmpb128_mask:
  947. case X86::BI__builtin_ia32_cmpw128_mask:
  948. case X86::BI__builtin_ia32_cmpd128_mask:
  949. case X86::BI__builtin_ia32_cmpq128_mask:
  950. case X86::BI__builtin_ia32_cmpb256_mask:
  951. case X86::BI__builtin_ia32_cmpw256_mask:
  952. case X86::BI__builtin_ia32_cmpd256_mask:
  953. case X86::BI__builtin_ia32_cmpq256_mask:
  954. case X86::BI__builtin_ia32_cmpb512_mask:
  955. case X86::BI__builtin_ia32_cmpw512_mask:
  956. case X86::BI__builtin_ia32_cmpd512_mask:
  957. case X86::BI__builtin_ia32_cmpq512_mask:
  958. case X86::BI__builtin_ia32_ucmpb128_mask:
  959. case X86::BI__builtin_ia32_ucmpw128_mask:
  960. case X86::BI__builtin_ia32_ucmpd128_mask:
  961. case X86::BI__builtin_ia32_ucmpq128_mask:
  962. case X86::BI__builtin_ia32_ucmpb256_mask:
  963. case X86::BI__builtin_ia32_ucmpw256_mask:
  964. case X86::BI__builtin_ia32_ucmpd256_mask:
  965. case X86::BI__builtin_ia32_ucmpq256_mask:
  966. case X86::BI__builtin_ia32_ucmpb512_mask:
  967. case X86::BI__builtin_ia32_ucmpw512_mask:
  968. case X86::BI__builtin_ia32_ucmpd512_mask:
  969. case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
  970. case X86::BI__builtin_ia32_roundps:
  971. case X86::BI__builtin_ia32_roundpd:
  972. case X86::BI__builtin_ia32_roundps256:
  973. case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
  974. case X86::BI__builtin_ia32_roundss:
  975. case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
  976. case X86::BI__builtin_ia32_cmpps:
  977. case X86::BI__builtin_ia32_cmpss:
  978. case X86::BI__builtin_ia32_cmppd:
  979. case X86::BI__builtin_ia32_cmpsd:
  980. case X86::BI__builtin_ia32_cmpps256:
  981. case X86::BI__builtin_ia32_cmppd256:
  982. case X86::BI__builtin_ia32_cmpps512_mask:
  983. case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
  984. case X86::BI__builtin_ia32_vpcomub:
  985. case X86::BI__builtin_ia32_vpcomuw:
  986. case X86::BI__builtin_ia32_vpcomud:
  987. case X86::BI__builtin_ia32_vpcomuq:
  988. case X86::BI__builtin_ia32_vpcomb:
  989. case X86::BI__builtin_ia32_vpcomw:
  990. case X86::BI__builtin_ia32_vpcomd:
  991. case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
  992. }
  993. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  994. }
  995. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  996. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  997. /// Returns true when the format fits the function and the FormatStringInfo has
  998. /// been populated.
  999. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  1000. FormatStringInfo *FSI) {
  1001. FSI->HasVAListArg = Format->getFirstArg() == 0;
  1002. FSI->FormatIdx = Format->getFormatIdx() - 1;
  1003. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  1004. // The way the format attribute works in GCC, the implicit this argument
  1005. // of member functions is counted. However, it doesn't appear in our own
  1006. // lists, so decrement format_idx in that case.
  1007. if (IsCXXMember) {
  1008. if(FSI->FormatIdx == 0)
  1009. return false;
  1010. --FSI->FormatIdx;
  1011. if (FSI->FirstDataArg != 0)
  1012. --FSI->FirstDataArg;
  1013. }
  1014. return true;
  1015. }
  1016. /// Checks if a the given expression evaluates to null.
  1017. ///
  1018. /// \brief Returns true if the value evaluates to null.
  1019. static bool CheckNonNullExpr(Sema &S,
  1020. const Expr *Expr) {
  1021. // If the expression has non-null type, it doesn't evaluate to null.
  1022. if (auto nullability
  1023. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  1024. if (*nullability == NullabilityKind::NonNull)
  1025. return false;
  1026. }
  1027. // As a special case, transparent unions initialized with zero are
  1028. // considered null for the purposes of the nonnull attribute.
  1029. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  1030. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  1031. if (const CompoundLiteralExpr *CLE =
  1032. dyn_cast<CompoundLiteralExpr>(Expr))
  1033. if (const InitListExpr *ILE =
  1034. dyn_cast<InitListExpr>(CLE->getInitializer()))
  1035. Expr = ILE->getInit(0);
  1036. }
  1037. bool Result;
  1038. return (!Expr->isValueDependent() &&
  1039. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  1040. !Result);
  1041. }
  1042. static void CheckNonNullArgument(Sema &S,
  1043. const Expr *ArgExpr,
  1044. SourceLocation CallSiteLoc) {
  1045. if (CheckNonNullExpr(S, ArgExpr))
  1046. S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  1047. }
  1048. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  1049. FormatStringInfo FSI;
  1050. if ((GetFormatStringType(Format) == FST_NSString) &&
  1051. getFormatStringInfo(Format, false, &FSI)) {
  1052. Idx = FSI.FormatIdx;
  1053. return true;
  1054. }
  1055. return false;
  1056. }
  1057. /// \brief Diagnose use of %s directive in an NSString which is being passed
  1058. /// as formatting string to formatting method.
  1059. static void
  1060. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  1061. const NamedDecl *FDecl,
  1062. Expr **Args,
  1063. unsigned NumArgs) {
  1064. unsigned Idx = 0;
  1065. bool Format = false;
  1066. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  1067. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  1068. Idx = 2;
  1069. Format = true;
  1070. }
  1071. else
  1072. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  1073. if (S.GetFormatNSStringIdx(I, Idx)) {
  1074. Format = true;
  1075. break;
  1076. }
  1077. }
  1078. if (!Format || NumArgs <= Idx)
  1079. return;
  1080. const Expr *FormatExpr = Args[Idx];
  1081. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  1082. FormatExpr = CSCE->getSubExpr();
  1083. const StringLiteral *FormatString;
  1084. if (const ObjCStringLiteral *OSL =
  1085. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  1086. FormatString = OSL->getString();
  1087. else
  1088. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  1089. if (!FormatString)
  1090. return;
  1091. if (S.FormatStringHasSArg(FormatString)) {
  1092. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  1093. << "%s" << 1 << 1;
  1094. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  1095. << FDecl->getDeclName();
  1096. }
  1097. }
  1098. /// Determine whether the given type has a non-null nullability annotation.
  1099. static bool isNonNullType(ASTContext &ctx, QualType type) {
  1100. if (auto nullability = type->getNullability(ctx))
  1101. return *nullability == NullabilityKind::NonNull;
  1102. return false;
  1103. }
  1104. static void CheckNonNullArguments(Sema &S,
  1105. const NamedDecl *FDecl,
  1106. const FunctionProtoType *Proto,
  1107. ArrayRef<const Expr *> Args,
  1108. SourceLocation CallSiteLoc) {
  1109. assert((FDecl || Proto) && "Need a function declaration or prototype");
  1110. // Check the attributes attached to the method/function itself.
  1111. llvm::SmallBitVector NonNullArgs;
  1112. if (FDecl) {
  1113. // Handle the nonnull attribute on the function/method declaration itself.
  1114. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  1115. if (!NonNull->args_size()) {
  1116. // Easy case: all pointer arguments are nonnull.
  1117. for (const auto *Arg : Args)
  1118. if (S.isValidPointerAttrType(Arg->getType()))
  1119. CheckNonNullArgument(S, Arg, CallSiteLoc);
  1120. return;
  1121. }
  1122. for (unsigned Val : NonNull->args()) {
  1123. if (Val >= Args.size())
  1124. continue;
  1125. if (NonNullArgs.empty())
  1126. NonNullArgs.resize(Args.size());
  1127. NonNullArgs.set(Val);
  1128. }
  1129. }
  1130. }
  1131. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  1132. // Handle the nonnull attribute on the parameters of the
  1133. // function/method.
  1134. ArrayRef<ParmVarDecl*> parms;
  1135. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  1136. parms = FD->parameters();
  1137. else
  1138. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  1139. unsigned ParamIndex = 0;
  1140. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  1141. I != E; ++I, ++ParamIndex) {
  1142. const ParmVarDecl *PVD = *I;
  1143. if (PVD->hasAttr<NonNullAttr>() ||
  1144. isNonNullType(S.Context, PVD->getType())) {
  1145. if (NonNullArgs.empty())
  1146. NonNullArgs.resize(Args.size());
  1147. NonNullArgs.set(ParamIndex);
  1148. }
  1149. }
  1150. } else {
  1151. // If we have a non-function, non-method declaration but no
  1152. // function prototype, try to dig out the function prototype.
  1153. if (!Proto) {
  1154. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  1155. QualType type = VD->getType().getNonReferenceType();
  1156. if (auto pointerType = type->getAs<PointerType>())
  1157. type = pointerType->getPointeeType();
  1158. else if (auto blockType = type->getAs<BlockPointerType>())
  1159. type = blockType->getPointeeType();
  1160. // FIXME: data member pointers?
  1161. // Dig out the function prototype, if there is one.
  1162. Proto = type->getAs<FunctionProtoType>();
  1163. }
  1164. }
  1165. // Fill in non-null argument information from the nullability
  1166. // information on the parameter types (if we have them).
  1167. if (Proto) {
  1168. unsigned Index = 0;
  1169. for (auto paramType : Proto->getParamTypes()) {
  1170. if (isNonNullType(S.Context, paramType)) {
  1171. if (NonNullArgs.empty())
  1172. NonNullArgs.resize(Args.size());
  1173. NonNullArgs.set(Index);
  1174. }
  1175. ++Index;
  1176. }
  1177. }
  1178. }
  1179. // Check for non-null arguments.
  1180. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  1181. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  1182. if (NonNullArgs[ArgIndex])
  1183. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  1184. }
  1185. }
  1186. /// Handles the checks for format strings, non-POD arguments to vararg
  1187. /// functions, and NULL arguments passed to non-NULL parameters.
  1188. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  1189. ArrayRef<const Expr *> Args, bool IsMemberFunction,
  1190. SourceLocation Loc, SourceRange Range,
  1191. VariadicCallType CallType) {
  1192. // FIXME: We should check as much as we can in the template definition.
  1193. if (CurContext->isDependentContext())
  1194. return;
  1195. // Printf and scanf checking.
  1196. llvm::SmallBitVector CheckedVarArgs;
  1197. if (FDecl) {
  1198. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  1199. // Only create vector if there are format attributes.
  1200. CheckedVarArgs.resize(Args.size());
  1201. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  1202. CheckedVarArgs);
  1203. }
  1204. }
  1205. // Refuse POD arguments that weren't caught by the format string
  1206. // checks above.
  1207. if (CallType != VariadicDoesNotApply) {
  1208. unsigned NumParams = Proto ? Proto->getNumParams()
  1209. : FDecl && isa<FunctionDecl>(FDecl)
  1210. ? cast<FunctionDecl>(FDecl)->getNumParams()
  1211. : FDecl && isa<ObjCMethodDecl>(FDecl)
  1212. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  1213. : 0;
  1214. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  1215. // Args[ArgIdx] can be null in malformed code.
  1216. if (const Expr *Arg = Args[ArgIdx]) {
  1217. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  1218. checkVariadicArgument(Arg, CallType);
  1219. }
  1220. }
  1221. }
  1222. if (FDecl || Proto) {
  1223. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  1224. // Type safety checking.
  1225. if (FDecl) {
  1226. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  1227. CheckArgumentWithTypeTag(I, Args.data());
  1228. }
  1229. }
  1230. }
  1231. /// CheckConstructorCall - Check a constructor call for correctness and safety
  1232. /// properties not enforced by the C type system.
  1233. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  1234. ArrayRef<const Expr *> Args,
  1235. const FunctionProtoType *Proto,
  1236. SourceLocation Loc) {
  1237. VariadicCallType CallType =
  1238. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  1239. checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
  1240. CallType);
  1241. }
  1242. /// CheckFunctionCall - Check a direct function call for various correctness
  1243. /// and safety properties not strictly enforced by the C type system.
  1244. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  1245. const FunctionProtoType *Proto) {
  1246. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  1247. isa<CXXMethodDecl>(FDecl);
  1248. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  1249. IsMemberOperatorCall;
  1250. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  1251. TheCall->getCallee());
  1252. Expr** Args = TheCall->getArgs();
  1253. unsigned NumArgs = TheCall->getNumArgs();
  1254. if (IsMemberOperatorCall) {
  1255. // If this is a call to a member operator, hide the first argument
  1256. // from checkCall.
  1257. // FIXME: Our choice of AST representation here is less than ideal.
  1258. ++Args;
  1259. --NumArgs;
  1260. }
  1261. checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
  1262. IsMemberFunction, TheCall->getRParenLoc(),
  1263. TheCall->getCallee()->getSourceRange(), CallType);
  1264. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  1265. // None of the checks below are needed for functions that don't have
  1266. // simple names (e.g., C++ conversion functions).
  1267. if (!FnInfo)
  1268. return false;
  1269. CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
  1270. if (getLangOpts().ObjC1)
  1271. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  1272. unsigned CMId = FDecl->getMemoryFunctionKind();
  1273. if (CMId == 0)
  1274. return false;
  1275. // Handle memory setting and copying functions.
  1276. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  1277. CheckStrlcpycatArguments(TheCall, FnInfo);
  1278. else if (CMId == Builtin::BIstrncat)
  1279. CheckStrncatArguments(TheCall, FnInfo);
  1280. else
  1281. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  1282. return false;
  1283. }
  1284. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  1285. ArrayRef<const Expr *> Args) {
  1286. VariadicCallType CallType =
  1287. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  1288. checkCall(Method, nullptr, Args,
  1289. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  1290. CallType);
  1291. return false;
  1292. }
  1293. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  1294. const FunctionProtoType *Proto) {
  1295. QualType Ty;
  1296. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  1297. Ty = V->getType().getNonReferenceType();
  1298. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  1299. Ty = F->getType().getNonReferenceType();
  1300. else
  1301. return false;
  1302. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  1303. !Ty->isFunctionProtoType())
  1304. return false;
  1305. VariadicCallType CallType;
  1306. if (!Proto || !Proto->isVariadic()) {
  1307. CallType = VariadicDoesNotApply;
  1308. } else if (Ty->isBlockPointerType()) {
  1309. CallType = VariadicBlock;
  1310. } else { // Ty->isFunctionPointerType()
  1311. CallType = VariadicFunction;
  1312. }
  1313. checkCall(NDecl, Proto,
  1314. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  1315. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  1316. TheCall->getCallee()->getSourceRange(), CallType);
  1317. return false;
  1318. }
  1319. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  1320. /// such as function pointers returned from functions.
  1321. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  1322. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  1323. TheCall->getCallee());
  1324. checkCall(/*FDecl=*/nullptr, Proto,
  1325. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  1326. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  1327. TheCall->getCallee()->getSourceRange(), CallType);
  1328. return false;
  1329. }
  1330. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  1331. if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
  1332. Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
  1333. return false;
  1334. switch (Op) {
  1335. case AtomicExpr::AO__c11_atomic_init:
  1336. llvm_unreachable("There is no ordering argument for an init");
  1337. case AtomicExpr::AO__c11_atomic_load:
  1338. case AtomicExpr::AO__atomic_load_n:
  1339. case AtomicExpr::AO__atomic_load:
  1340. return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
  1341. Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
  1342. case AtomicExpr::AO__c11_atomic_store:
  1343. case AtomicExpr::AO__atomic_store:
  1344. case AtomicExpr::AO__atomic_store_n:
  1345. return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
  1346. Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
  1347. Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
  1348. default:
  1349. return true;
  1350. }
  1351. }
  1352. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  1353. AtomicExpr::AtomicOp Op) {
  1354. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  1355. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1356. // All these operations take one of the following forms:
  1357. enum {
  1358. // C __c11_atomic_init(A *, C)
  1359. Init,
  1360. // C __c11_atomic_load(A *, int)
  1361. Load,
  1362. // void __atomic_load(A *, CP, int)
  1363. Copy,
  1364. // C __c11_atomic_add(A *, M, int)
  1365. Arithmetic,
  1366. // C __atomic_exchange_n(A *, CP, int)
  1367. Xchg,
  1368. // void __atomic_exchange(A *, C *, CP, int)
  1369. GNUXchg,
  1370. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  1371. C11CmpXchg,
  1372. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  1373. GNUCmpXchg
  1374. } Form = Init;
  1375. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
  1376. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
  1377. // where:
  1378. // C is an appropriate type,
  1379. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  1380. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  1381. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  1382. // the int parameters are for orderings.
  1383. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  1384. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  1385. AtomicExpr::AO__atomic_load,
  1386. "need to update code for modified C11 atomics");
  1387. bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
  1388. Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
  1389. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  1390. Op == AtomicExpr::AO__atomic_store_n ||
  1391. Op == AtomicExpr::AO__atomic_exchange_n ||
  1392. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  1393. bool IsAddSub = false;
  1394. switch (Op) {
  1395. case AtomicExpr::AO__c11_atomic_init:
  1396. Form = Init;
  1397. break;
  1398. case AtomicExpr::AO__c11_atomic_load:
  1399. case AtomicExpr::AO__atomic_load_n:
  1400. Form = Load;
  1401. break;
  1402. case AtomicExpr::AO__c11_atomic_store:
  1403. case AtomicExpr::AO__atomic_load:
  1404. case AtomicExpr::AO__atomic_store:
  1405. case AtomicExpr::AO__atomic_store_n:
  1406. Form = Copy;
  1407. break;
  1408. case AtomicExpr::AO__c11_atomic_fetch_add:
  1409. case AtomicExpr::AO__c11_atomic_fetch_sub:
  1410. case AtomicExpr::AO__atomic_fetch_add:
  1411. case AtomicExpr::AO__atomic_fetch_sub:
  1412. case AtomicExpr::AO__atomic_add_fetch:
  1413. case AtomicExpr::AO__atomic_sub_fetch:
  1414. IsAddSub = true;
  1415. // Fall through.
  1416. case AtomicExpr::AO__c11_atomic_fetch_and:
  1417. case AtomicExpr::AO__c11_atomic_fetch_or:
  1418. case AtomicExpr::AO__c11_atomic_fetch_xor:
  1419. case AtomicExpr::AO__atomic_fetch_and:
  1420. case AtomicExpr::AO__atomic_fetch_or:
  1421. case AtomicExpr::AO__atomic_fetch_xor:
  1422. case AtomicExpr::AO__atomic_fetch_nand:
  1423. case AtomicExpr::AO__atomic_and_fetch:
  1424. case AtomicExpr::AO__atomic_or_fetch:
  1425. case AtomicExpr::AO__atomic_xor_fetch:
  1426. case AtomicExpr::AO__atomic_nand_fetch:
  1427. Form = Arithmetic;
  1428. break;
  1429. case AtomicExpr::AO__c11_atomic_exchange:
  1430. case AtomicExpr::AO__atomic_exchange_n:
  1431. Form = Xchg;
  1432. break;
  1433. case AtomicExpr::AO__atomic_exchange:
  1434. Form = GNUXchg;
  1435. break;
  1436. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  1437. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  1438. Form = C11CmpXchg;
  1439. break;
  1440. case AtomicExpr::AO__atomic_compare_exchange:
  1441. case AtomicExpr::AO__atomic_compare_exchange_n:
  1442. Form = GNUCmpXchg;
  1443. break;
  1444. }
  1445. // Check we have the right number of arguments.
  1446. if (TheCall->getNumArgs() < NumArgs[Form]) {
  1447. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1448. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  1449. << TheCall->getCallee()->getSourceRange();
  1450. return ExprError();
  1451. } else if (TheCall->getNumArgs() > NumArgs[Form]) {
  1452. Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
  1453. diag::err_typecheck_call_too_many_args)
  1454. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  1455. << TheCall->getCallee()->getSourceRange();
  1456. return ExprError();
  1457. }
  1458. // Inspect the first argument of the atomic operation.
  1459. Expr *Ptr = TheCall->getArg(0);
  1460. Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
  1461. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  1462. if (!pointerType) {
  1463. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  1464. << Ptr->getType() << Ptr->getSourceRange();
  1465. return ExprError();
  1466. }
  1467. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  1468. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  1469. QualType ValType = AtomTy; // 'C'
  1470. if (IsC11) {
  1471. if (!AtomTy->isAtomicType()) {
  1472. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  1473. << Ptr->getType() << Ptr->getSourceRange();
  1474. return ExprError();
  1475. }
  1476. if (AtomTy.isConstQualified()) {
  1477. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
  1478. << Ptr->getType() << Ptr->getSourceRange();
  1479. return ExprError();
  1480. }
  1481. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  1482. }
  1483. // For an arithmetic operation, the implied arithmetic must be well-formed.
  1484. if (Form == Arithmetic) {
  1485. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  1486. if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
  1487. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  1488. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  1489. return ExprError();
  1490. }
  1491. if (!IsAddSub && !ValType->isIntegerType()) {
  1492. Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
  1493. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  1494. return ExprError();
  1495. }
  1496. if (IsC11 && ValType->isPointerType() &&
  1497. RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
  1498. diag::err_incomplete_type)) {
  1499. return ExprError();
  1500. }
  1501. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  1502. // For __atomic_*_n operations, the value type must be a scalar integral or
  1503. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  1504. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  1505. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  1506. return ExprError();
  1507. }
  1508. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  1509. !AtomTy->isScalarType()) {
  1510. // For GNU atomics, require a trivially-copyable type. This is not part of
  1511. // the GNU atomics specification, but we enforce it for sanity.
  1512. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
  1513. << Ptr->getType() << Ptr->getSourceRange();
  1514. return ExprError();
  1515. }
  1516. // FIXME: For any builtin other than a load, the ValType must not be
  1517. // const-qualified.
  1518. switch (ValType.getObjCLifetime()) {
  1519. case Qualifiers::OCL_None:
  1520. case Qualifiers::OCL_ExplicitNone:
  1521. // okay
  1522. break;
  1523. case Qualifiers::OCL_Weak:
  1524. case Qualifiers::OCL_Strong:
  1525. case Qualifiers::OCL_Autoreleasing:
  1526. // FIXME: Can this happen? By this point, ValType should be known
  1527. // to be trivially copyable.
  1528. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  1529. << ValType << Ptr->getSourceRange();
  1530. return ExprError();
  1531. }
  1532. // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
  1533. // volatile-ness of the pointee-type inject itself into the result or the
  1534. // other operands.
  1535. ValType.removeLocalVolatile();
  1536. QualType ResultType = ValType;
  1537. if (Form == Copy || Form == GNUXchg || Form == Init)
  1538. ResultType = Context.VoidTy;
  1539. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  1540. ResultType = Context.BoolTy;
  1541. // The type of a parameter passed 'by value'. In the GNU atomics, such
  1542. // arguments are actually passed as pointers.
  1543. QualType ByValType = ValType; // 'CP'
  1544. if (!IsC11 && !IsN)
  1545. ByValType = Ptr->getType();
  1546. // The first argument --- the pointer --- has a fixed type; we
  1547. // deduce the types of the rest of the arguments accordingly. Walk
  1548. // the remaining arguments, converting them to the deduced value type.
  1549. for (unsigned i = 1; i != NumArgs[Form]; ++i) {
  1550. QualType Ty;
  1551. if (i < NumVals[Form] + 1) {
  1552. switch (i) {
  1553. case 1:
  1554. // The second argument is the non-atomic operand. For arithmetic, this
  1555. // is always passed by value, and for a compare_exchange it is always
  1556. // passed by address. For the rest, GNU uses by-address and C11 uses
  1557. // by-value.
  1558. assert(Form != Load);
  1559. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  1560. Ty = ValType;
  1561. else if (Form == Copy || Form == Xchg)
  1562. Ty = ByValType;
  1563. else if (Form == Arithmetic)
  1564. Ty = Context.getPointerDiffType();
  1565. else
  1566. Ty = Context.getPointerType(ValType.getUnqualifiedType());
  1567. break;
  1568. case 2:
  1569. // The third argument to compare_exchange / GNU exchange is a
  1570. // (pointer to a) desired value.
  1571. Ty = ByValType;
  1572. break;
  1573. case 3:
  1574. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  1575. Ty = Context.BoolTy;
  1576. break;
  1577. }
  1578. } else {
  1579. // The order(s) are always converted to int.
  1580. Ty = Context.IntTy;
  1581. }
  1582. InitializedEntity Entity =
  1583. InitializedEntity::InitializeParameter(Context, Ty, false);
  1584. ExprResult Arg = TheCall->getArg(i);
  1585. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1586. if (Arg.isInvalid())
  1587. return true;
  1588. TheCall->setArg(i, Arg.get());
  1589. }
  1590. // Permute the arguments into a 'consistent' order.
  1591. SmallVector<Expr*, 5> SubExprs;
  1592. SubExprs.push_back(Ptr);
  1593. switch (Form) {
  1594. case Init:
  1595. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  1596. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1597. break;
  1598. case Load:
  1599. SubExprs.push_back(TheCall->getArg(1)); // Order
  1600. break;
  1601. case Copy:
  1602. case Arithmetic:
  1603. case Xchg:
  1604. SubExprs.push_back(TheCall->getArg(2)); // Order
  1605. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1606. break;
  1607. case GNUXchg:
  1608. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  1609. SubExprs.push_back(TheCall->getArg(3)); // Order
  1610. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1611. SubExprs.push_back(TheCall->getArg(2)); // Val2
  1612. break;
  1613. case C11CmpXchg:
  1614. SubExprs.push_back(TheCall->getArg(3)); // Order
  1615. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1616. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  1617. SubExprs.push_back(TheCall->getArg(2)); // Val2
  1618. break;
  1619. case GNUCmpXchg:
  1620. SubExprs.push_back(TheCall->getArg(4)); // Order
  1621. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1622. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  1623. SubExprs.push_back(TheCall->getArg(2)); // Val2
  1624. SubExprs.push_back(TheCall->getArg(3)); // Weak
  1625. break;
  1626. }
  1627. if (SubExprs.size() >= 2 && Form != Init) {
  1628. llvm::APSInt Result(32);
  1629. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  1630. !isValidOrderingForOp(Result.getSExtValue(), Op))
  1631. Diag(SubExprs[1]->getLocStart(),
  1632. diag::warn_atomic_op_has_invalid_memory_order)
  1633. << SubExprs[1]->getSourceRange();
  1634. }
  1635. AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  1636. SubExprs, ResultType, Op,
  1637. TheCall->getRParenLoc());
  1638. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  1639. (Op == AtomicExpr::AO__c11_atomic_store)) &&
  1640. Context.AtomicUsesUnsupportedLibcall(AE))
  1641. Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
  1642. ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
  1643. return AE;
  1644. }
  1645. /// checkBuiltinArgument - Given a call to a builtin function, perform
  1646. /// normal type-checking on the given argument, updating the call in
  1647. /// place. This is useful when a builtin function requires custom
  1648. /// type-checking for some of its arguments but not necessarily all of
  1649. /// them.
  1650. ///
  1651. /// Returns true on error.
  1652. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  1653. FunctionDecl *Fn = E->getDirectCallee();
  1654. assert(Fn && "builtin call without direct callee!");
  1655. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  1656. InitializedEntity Entity =
  1657. InitializedEntity::InitializeParameter(S.Context, Param);
  1658. ExprResult Arg = E->getArg(0);
  1659. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1660. if (Arg.isInvalid())
  1661. return true;
  1662. E->setArg(ArgIndex, Arg.get());
  1663. return false;
  1664. }
  1665. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  1666. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  1667. /// type of its first argument. The main ActOnCallExpr routines have already
  1668. /// promoted the types of arguments because all of these calls are prototyped as
  1669. /// void(...).
  1670. ///
  1671. /// This function goes through and does final semantic checking for these
  1672. /// builtins,
  1673. ExprResult
  1674. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  1675. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  1676. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1677. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  1678. // Ensure that we have at least one argument to do type inference from.
  1679. if (TheCall->getNumArgs() < 1) {
  1680. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  1681. << 0 << 1 << TheCall->getNumArgs()
  1682. << TheCall->getCallee()->getSourceRange();
  1683. return ExprError();
  1684. }
  1685. // Inspect the first argument of the atomic builtin. This should always be
  1686. // a pointer type, whose element is an integral scalar or pointer type.
  1687. // Because it is a pointer type, we don't have to worry about any implicit
  1688. // casts here.
  1689. // FIXME: We don't allow floating point scalars as input.
  1690. Expr *FirstArg = TheCall->getArg(0);
  1691. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  1692. if (FirstArgResult.isInvalid())
  1693. return ExprError();
  1694. FirstArg = FirstArgResult.get();
  1695. TheCall->setArg(0, FirstArg);
  1696. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  1697. if (!pointerType) {
  1698. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  1699. << FirstArg->getType() << FirstArg->getSourceRange();
  1700. return ExprError();
  1701. }
  1702. QualType ValType = pointerType->getPointeeType();
  1703. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1704. !ValType->isBlockPointerType()) {
  1705. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  1706. << FirstArg->getType() << FirstArg->getSourceRange();
  1707. return ExprError();
  1708. }
  1709. switch (ValType.getObjCLifetime()) {
  1710. case Qualifiers::OCL_None:
  1711. case Qualifiers::OCL_ExplicitNone:
  1712. // okay
  1713. break;
  1714. case Qualifiers::OCL_Weak:
  1715. case Qualifiers::OCL_Strong:
  1716. case Qualifiers::OCL_Autoreleasing:
  1717. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  1718. << ValType << FirstArg->getSourceRange();
  1719. return ExprError();
  1720. }
  1721. // Strip any qualifiers off ValType.
  1722. ValType = ValType.getUnqualifiedType();
  1723. // The majority of builtins return a value, but a few have special return
  1724. // types, so allow them to override appropriately below.
  1725. QualType ResultType = ValType;
  1726. // We need to figure out which concrete builtin this maps onto. For example,
  1727. // __sync_fetch_and_add with a 2 byte object turns into
  1728. // __sync_fetch_and_add_2.
  1729. #define BUILTIN_ROW(x) \
  1730. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  1731. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  1732. static const unsigned BuiltinIndices[][5] = {
  1733. BUILTIN_ROW(__sync_fetch_and_add),
  1734. BUILTIN_ROW(__sync_fetch_and_sub),
  1735. BUILTIN_ROW(__sync_fetch_and_or),
  1736. BUILTIN_ROW(__sync_fetch_and_and),
  1737. BUILTIN_ROW(__sync_fetch_and_xor),
  1738. BUILTIN_ROW(__sync_fetch_and_nand),
  1739. BUILTIN_ROW(__sync_add_and_fetch),
  1740. BUILTIN_ROW(__sync_sub_and_fetch),
  1741. BUILTIN_ROW(__sync_and_and_fetch),
  1742. BUILTIN_ROW(__sync_or_and_fetch),
  1743. BUILTIN_ROW(__sync_xor_and_fetch),
  1744. BUILTIN_ROW(__sync_nand_and_fetch),
  1745. BUILTIN_ROW(__sync_val_compare_and_swap),
  1746. BUILTIN_ROW(__sync_bool_compare_and_swap),
  1747. BUILTIN_ROW(__sync_lock_test_and_set),
  1748. BUILTIN_ROW(__sync_lock_release),
  1749. BUILTIN_ROW(__sync_swap)
  1750. };
  1751. #undef BUILTIN_ROW
  1752. // Determine the index of the size.
  1753. unsigned SizeIndex;
  1754. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  1755. case 1: SizeIndex = 0; break;
  1756. case 2: SizeIndex = 1; break;
  1757. case 4: SizeIndex = 2; break;
  1758. case 8: SizeIndex = 3; break;
  1759. case 16: SizeIndex = 4; break;
  1760. default:
  1761. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  1762. << FirstArg->getType() << FirstArg->getSourceRange();
  1763. return ExprError();
  1764. }
  1765. // Each of these builtins has one pointer argument, followed by some number of
  1766. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  1767. // that we ignore. Find out which row of BuiltinIndices to read from as well
  1768. // as the number of fixed args.
  1769. unsigned BuiltinID = FDecl->getBuiltinID();
  1770. unsigned BuiltinIndex, NumFixed = 1;
  1771. bool WarnAboutSemanticsChange = false;
  1772. switch (BuiltinID) {
  1773. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  1774. case Builtin::BI__sync_fetch_and_add:
  1775. case Builtin::BI__sync_fetch_and_add_1:
  1776. case Builtin::BI__sync_fetch_and_add_2:
  1777. case Builtin::BI__sync_fetch_and_add_4:
  1778. case Builtin::BI__sync_fetch_and_add_8:
  1779. case Builtin::BI__sync_fetch_and_add_16:
  1780. BuiltinIndex = 0;
  1781. break;
  1782. case Builtin::BI__sync_fetch_and_sub:
  1783. case Builtin::BI__sync_fetch_and_sub_1:
  1784. case Builtin::BI__sync_fetch_and_sub_2:
  1785. case Builtin::BI__sync_fetch_and_sub_4:
  1786. case Builtin::BI__sync_fetch_and_sub_8:
  1787. case Builtin::BI__sync_fetch_and_sub_16:
  1788. BuiltinIndex = 1;
  1789. break;
  1790. case Builtin::BI__sync_fetch_and_or:
  1791. case Builtin::BI__sync_fetch_and_or_1:
  1792. case Builtin::BI__sync_fetch_and_or_2:
  1793. case Builtin::BI__sync_fetch_and_or_4:
  1794. case Builtin::BI__sync_fetch_and_or_8:
  1795. case Builtin::BI__sync_fetch_and_or_16:
  1796. BuiltinIndex = 2;
  1797. break;
  1798. case Builtin::BI__sync_fetch_and_and:
  1799. case Builtin::BI__sync_fetch_and_and_1:
  1800. case Builtin::BI__sync_fetch_and_and_2:
  1801. case Builtin::BI__sync_fetch_and_and_4:
  1802. case Builtin::BI__sync_fetch_and_and_8:
  1803. case Builtin::BI__sync_fetch_and_and_16:
  1804. BuiltinIndex = 3;
  1805. break;
  1806. case Builtin::BI__sync_fetch_and_xor:
  1807. case Builtin::BI__sync_fetch_and_xor_1:
  1808. case Builtin::BI__sync_fetch_and_xor_2:
  1809. case Builtin::BI__sync_fetch_and_xor_4:
  1810. case Builtin::BI__sync_fetch_and_xor_8:
  1811. case Builtin::BI__sync_fetch_and_xor_16:
  1812. BuiltinIndex = 4;
  1813. break;
  1814. case Builtin::BI__sync_fetch_and_nand:
  1815. case Builtin::BI__sync_fetch_and_nand_1:
  1816. case Builtin::BI__sync_fetch_and_nand_2:
  1817. case Builtin::BI__sync_fetch_and_nand_4:
  1818. case Builtin::BI__sync_fetch_and_nand_8:
  1819. case Builtin::BI__sync_fetch_and_nand_16:
  1820. BuiltinIndex = 5;
  1821. WarnAboutSemanticsChange = true;
  1822. break;
  1823. case Builtin::BI__sync_add_and_fetch:
  1824. case Builtin::BI__sync_add_and_fetch_1:
  1825. case Builtin::BI__sync_add_and_fetch_2:
  1826. case Builtin::BI__sync_add_and_fetch_4:
  1827. case Builtin::BI__sync_add_and_fetch_8:
  1828. case Builtin::BI__sync_add_and_fetch_16:
  1829. BuiltinIndex = 6;
  1830. break;
  1831. case Builtin::BI__sync_sub_and_fetch:
  1832. case Builtin::BI__sync_sub_and_fetch_1:
  1833. case Builtin::BI__sync_sub_and_fetch_2:
  1834. case Builtin::BI__sync_sub_and_fetch_4:
  1835. case Builtin::BI__sync_sub_and_fetch_8:
  1836. case Builtin::BI__sync_sub_and_fetch_16:
  1837. BuiltinIndex = 7;
  1838. break;
  1839. case Builtin::BI__sync_and_and_fetch:
  1840. case Builtin::BI__sync_and_and_fetch_1:
  1841. case Builtin::BI__sync_and_and_fetch_2:
  1842. case Builtin::BI__sync_and_and_fetch_4:
  1843. case Builtin::BI__sync_and_and_fetch_8:
  1844. case Builtin::BI__sync_and_and_fetch_16:
  1845. BuiltinIndex = 8;
  1846. break;
  1847. case Builtin::BI__sync_or_and_fetch:
  1848. case Builtin::BI__sync_or_and_fetch_1:
  1849. case Builtin::BI__sync_or_and_fetch_2:
  1850. case Builtin::BI__sync_or_and_fetch_4:
  1851. case Builtin::BI__sync_or_and_fetch_8:
  1852. case Builtin::BI__sync_or_and_fetch_16:
  1853. BuiltinIndex = 9;
  1854. break;
  1855. case Builtin::BI__sync_xor_and_fetch:
  1856. case Builtin::BI__sync_xor_and_fetch_1:
  1857. case Builtin::BI__sync_xor_and_fetch_2:
  1858. case Builtin::BI__sync_xor_and_fetch_4:
  1859. case Builtin::BI__sync_xor_and_fetch_8:
  1860. case Builtin::BI__sync_xor_and_fetch_16:
  1861. BuiltinIndex = 10;
  1862. break;
  1863. case Builtin::BI__sync_nand_and_fetch:
  1864. case Builtin::BI__sync_nand_and_fetch_1:
  1865. case Builtin::BI__sync_nand_and_fetch_2:
  1866. case Builtin::BI__sync_nand_and_fetch_4:
  1867. case Builtin::BI__sync_nand_and_fetch_8:
  1868. case Builtin::BI__sync_nand_and_fetch_16:
  1869. BuiltinIndex = 11;
  1870. WarnAboutSemanticsChange = true;
  1871. break;
  1872. case Builtin::BI__sync_val_compare_and_swap:
  1873. case Builtin::BI__sync_val_compare_and_swap_1:
  1874. case Builtin::BI__sync_val_compare_and_swap_2:
  1875. case Builtin::BI__sync_val_compare_and_swap_4:
  1876. case Builtin::BI__sync_val_compare_and_swap_8:
  1877. case Builtin::BI__sync_val_compare_and_swap_16:
  1878. BuiltinIndex = 12;
  1879. NumFixed = 2;
  1880. break;
  1881. case Builtin::BI__sync_bool_compare_and_swap:
  1882. case Builtin::BI__sync_bool_compare_and_swap_1:
  1883. case Builtin::BI__sync_bool_compare_and_swap_2:
  1884. case Builtin::BI__sync_bool_compare_and_swap_4:
  1885. case Builtin::BI__sync_bool_compare_and_swap_8:
  1886. case Builtin::BI__sync_bool_compare_and_swap_16:
  1887. BuiltinIndex = 13;
  1888. NumFixed = 2;
  1889. ResultType = Context.BoolTy;
  1890. break;
  1891. case Builtin::BI__sync_lock_test_and_set:
  1892. case Builtin::BI__sync_lock_test_and_set_1:
  1893. case Builtin::BI__sync_lock_test_and_set_2:
  1894. case Builtin::BI__sync_lock_test_and_set_4:
  1895. case Builtin::BI__sync_lock_test_and_set_8:
  1896. case Builtin::BI__sync_lock_test_and_set_16:
  1897. BuiltinIndex = 14;
  1898. break;
  1899. case Builtin::BI__sync_lock_release:
  1900. case Builtin::BI__sync_lock_release_1:
  1901. case Builtin::BI__sync_lock_release_2:
  1902. case Builtin::BI__sync_lock_release_4:
  1903. case Builtin::BI__sync_lock_release_8:
  1904. case Builtin::BI__sync_lock_release_16:
  1905. BuiltinIndex = 15;
  1906. NumFixed = 0;
  1907. ResultType = Context.VoidTy;
  1908. break;
  1909. case Builtin::BI__sync_swap:
  1910. case Builtin::BI__sync_swap_1:
  1911. case Builtin::BI__sync_swap_2:
  1912. case Builtin::BI__sync_swap_4:
  1913. case Builtin::BI__sync_swap_8:
  1914. case Builtin::BI__sync_swap_16:
  1915. BuiltinIndex = 16;
  1916. break;
  1917. }
  1918. // Now that we know how many fixed arguments we expect, first check that we
  1919. // have at least that many.
  1920. if (TheCall->getNumArgs() < 1+NumFixed) {
  1921. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  1922. << 0 << 1+NumFixed << TheCall->getNumArgs()
  1923. << TheCall->getCallee()->getSourceRange();
  1924. return ExprError();
  1925. }
  1926. if (WarnAboutSemanticsChange) {
  1927. Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
  1928. << TheCall->getCallee()->getSourceRange();
  1929. }
  1930. // Get the decl for the concrete builtin from this, we can tell what the
  1931. // concrete integer type we should convert to is.
  1932. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  1933. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  1934. FunctionDecl *NewBuiltinDecl;
  1935. if (NewBuiltinID == BuiltinID)
  1936. NewBuiltinDecl = FDecl;
  1937. else {
  1938. // Perform builtin lookup to avoid redeclaring it.
  1939. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  1940. LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
  1941. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  1942. assert(Res.getFoundDecl());
  1943. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  1944. if (!NewBuiltinDecl)
  1945. return ExprError();
  1946. }
  1947. // The first argument --- the pointer --- has a fixed type; we
  1948. // deduce the types of the rest of the arguments accordingly. Walk
  1949. // the remaining arguments, converting them to the deduced value type.
  1950. for (unsigned i = 0; i != NumFixed; ++i) {
  1951. ExprResult Arg = TheCall->getArg(i+1);
  1952. // GCC does an implicit conversion to the pointer or integer ValType. This
  1953. // can fail in some cases (1i -> int**), check for this error case now.
  1954. // Initialize the argument.
  1955. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  1956. ValType, /*consume*/ false);
  1957. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1958. if (Arg.isInvalid())
  1959. return ExprError();
  1960. // Okay, we have something that *can* be converted to the right type. Check
  1961. // to see if there is a potentially weird extension going on here. This can
  1962. // happen when you do an atomic operation on something like an char* and
  1963. // pass in 42. The 42 gets converted to char. This is even more strange
  1964. // for things like 45.123 -> char, etc.
  1965. // FIXME: Do this check.
  1966. TheCall->setArg(i+1, Arg.get());
  1967. }
  1968. ASTContext& Context = this->getASTContext();
  1969. // Create a new DeclRefExpr to refer to the new decl.
  1970. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  1971. Context,
  1972. DRE->getQualifierLoc(),
  1973. SourceLocation(),
  1974. NewBuiltinDecl,
  1975. /*enclosing*/ false,
  1976. DRE->getLocation(),
  1977. Context.BuiltinFnTy,
  1978. DRE->getValueKind());
  1979. // Set the callee in the CallExpr.
  1980. // FIXME: This loses syntactic information.
  1981. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  1982. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  1983. CK_BuiltinFnToFnPtr);
  1984. TheCall->setCallee(PromotedCall.get());
  1985. // Change the result type of the call to match the original value type. This
  1986. // is arbitrary, but the codegen for these builtins ins design to handle it
  1987. // gracefully.
  1988. TheCall->setType(ResultType);
  1989. return TheCallResult;
  1990. }
  1991. /// SemaBuiltinNontemporalOverloaded - We have a call to
  1992. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  1993. /// overloaded function based on the pointer type of its last argument.
  1994. ///
  1995. /// This function goes through and does final semantic checking for these
  1996. /// builtins.
  1997. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  1998. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  1999. DeclRefExpr *DRE =
  2000. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  2001. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  2002. unsigned BuiltinID = FDecl->getBuiltinID();
  2003. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  2004. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  2005. "Unexpected nontemporal load/store builtin!");
  2006. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  2007. unsigned numArgs = isStore ? 2 : 1;
  2008. // Ensure that we have the proper number of arguments.
  2009. if (checkArgCount(*this, TheCall, numArgs))
  2010. return ExprError();
  2011. // Inspect the last argument of the nontemporal builtin. This should always
  2012. // be a pointer type, from which we imply the type of the memory access.
  2013. // Because it is a pointer type, we don't have to worry about any implicit
  2014. // casts here.
  2015. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  2016. ExprResult PointerArgResult =
  2017. DefaultFunctionArrayLvalueConversion(PointerArg);
  2018. if (PointerArgResult.isInvalid())
  2019. return ExprError();
  2020. PointerArg = PointerArgResult.get();
  2021. TheCall->setArg(numArgs - 1, PointerArg);
  2022. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  2023. if (!pointerType) {
  2024. Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
  2025. << PointerArg->getType() << PointerArg->getSourceRange();
  2026. return ExprError();
  2027. }
  2028. QualType ValType = pointerType->getPointeeType();
  2029. // Strip any qualifiers off ValType.
  2030. ValType = ValType.getUnqualifiedType();
  2031. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  2032. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  2033. !ValType->isVectorType()) {
  2034. Diag(DRE->getLocStart(),
  2035. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  2036. << PointerArg->getType() << PointerArg->getSourceRange();
  2037. return ExprError();
  2038. }
  2039. if (!isStore) {
  2040. TheCall->setType(ValType);
  2041. return TheCallResult;
  2042. }
  2043. ExprResult ValArg = TheCall->getArg(0);
  2044. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  2045. Context, ValType, /*consume*/ false);
  2046. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  2047. if (ValArg.isInvalid())
  2048. return ExprError();
  2049. TheCall->setArg(0, ValArg.get());
  2050. TheCall->setType(Context.VoidTy);
  2051. return TheCallResult;
  2052. }
  2053. /// CheckObjCString - Checks that the argument to the builtin
  2054. /// CFString constructor is correct
  2055. /// Note: It might also make sense to do the UTF-16 conversion here (would
  2056. /// simplify the backend).
  2057. bool Sema::CheckObjCString(Expr *Arg) {
  2058. Arg = Arg->IgnoreParenCasts();
  2059. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  2060. if (!Literal || !Literal->isAscii()) {
  2061. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  2062. << Arg->getSourceRange();
  2063. return true;
  2064. }
  2065. if (Literal->containsNonAsciiOrNull()) {
  2066. StringRef String = Literal->getString();
  2067. unsigned NumBytes = String.size();
  2068. SmallVector<UTF16, 128> ToBuf(NumBytes);
  2069. const UTF8 *FromPtr = (const UTF8 *)String.data();
  2070. UTF16 *ToPtr = &ToBuf[0];
  2071. ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  2072. &ToPtr, ToPtr + NumBytes,
  2073. strictConversion);
  2074. // Check for conversion failure.
  2075. if (Result != conversionOK)
  2076. Diag(Arg->getLocStart(),
  2077. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  2078. }
  2079. return false;
  2080. }
  2081. /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
  2082. /// Emit an error and return true on failure, return false on success.
  2083. bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
  2084. Expr *Fn = TheCall->getCallee();
  2085. if (TheCall->getNumArgs() > 2) {
  2086. Diag(TheCall->getArg(2)->getLocStart(),
  2087. diag::err_typecheck_call_too_many_args)
  2088. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  2089. << Fn->getSourceRange()
  2090. << SourceRange(TheCall->getArg(2)->getLocStart(),
  2091. (*(TheCall->arg_end()-1))->getLocEnd());
  2092. return true;
  2093. }
  2094. if (TheCall->getNumArgs() < 2) {
  2095. return Diag(TheCall->getLocEnd(),
  2096. diag::err_typecheck_call_too_few_args_at_least)
  2097. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  2098. }
  2099. // Type-check the first argument normally.
  2100. if (checkBuiltinArgument(*this, TheCall, 0))
  2101. return true;
  2102. // Determine whether the current function is variadic or not.
  2103. BlockScopeInfo *CurBlock = getCurBlock();
  2104. bool isVariadic;
  2105. if (CurBlock)
  2106. isVariadic = CurBlock->TheDecl->isVariadic();
  2107. else if (FunctionDecl *FD = getCurFunctionDecl())
  2108. isVariadic = FD->isVariadic();
  2109. else
  2110. isVariadic = getCurMethodDecl()->isVariadic();
  2111. if (!isVariadic) {
  2112. Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
  2113. return true;
  2114. }
  2115. // Verify that the second argument to the builtin is the last argument of the
  2116. // current function or method.
  2117. bool SecondArgIsLastNamedArgument = false;
  2118. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  2119. // These are valid if SecondArgIsLastNamedArgument is false after the next
  2120. // block.
  2121. QualType Type;
  2122. SourceLocation ParamLoc;
  2123. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  2124. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  2125. // FIXME: This isn't correct for methods (results in bogus warning).
  2126. // Get the last formal in the current function.
  2127. const ParmVarDecl *LastArg;
  2128. if (CurBlock)
  2129. LastArg = *(CurBlock->TheDecl->param_end()-1);
  2130. else if (FunctionDecl *FD = getCurFunctionDecl())
  2131. LastArg = *(FD->param_end()-1);
  2132. else
  2133. LastArg = *(getCurMethodDecl()->param_end()-1);
  2134. SecondArgIsLastNamedArgument = PV == LastArg;
  2135. Type = PV->getType();
  2136. ParamLoc = PV->getLocation();
  2137. }
  2138. }
  2139. if (!SecondArgIsLastNamedArgument)
  2140. Diag(TheCall->getArg(1)->getLocStart(),
  2141. diag::warn_second_parameter_of_va_start_not_last_named_argument);
  2142. else if (Type->isReferenceType()) {
  2143. Diag(Arg->getLocStart(),
  2144. diag::warn_va_start_of_reference_type_is_undefined);
  2145. Diag(ParamLoc, diag::note_parameter_type) << Type;
  2146. }
  2147. TheCall->setType(Context.VoidTy);
  2148. return false;
  2149. }
  2150. bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
  2151. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  2152. // const char *named_addr);
  2153. Expr *Func = Call->getCallee();
  2154. if (Call->getNumArgs() < 3)
  2155. return Diag(Call->getLocEnd(),
  2156. diag::err_typecheck_call_too_few_args_at_least)
  2157. << 0 /*function call*/ << 3 << Call->getNumArgs();
  2158. // Determine whether the current function is variadic or not.
  2159. bool IsVariadic;
  2160. if (BlockScopeInfo *CurBlock = getCurBlock())
  2161. IsVariadic = CurBlock->TheDecl->isVariadic();
  2162. else if (FunctionDecl *FD = getCurFunctionDecl())
  2163. IsVariadic = FD->isVariadic();
  2164. else if (ObjCMethodDecl *MD = getCurMethodDecl())
  2165. IsVariadic = MD->isVariadic();
  2166. else
  2167. llvm_unreachable("unexpected statement type");
  2168. if (!IsVariadic) {
  2169. Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
  2170. return true;
  2171. }
  2172. // Type-check the first argument normally.
  2173. if (checkBuiltinArgument(*this, Call, 0))
  2174. return true;
  2175. const struct {
  2176. unsigned ArgNo;
  2177. QualType Type;
  2178. } ArgumentTypes[] = {
  2179. { 1, Context.getPointerType(Context.CharTy.withConst()) },
  2180. { 2, Context.getSizeType() },
  2181. };
  2182. for (const auto &AT : ArgumentTypes) {
  2183. const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
  2184. if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
  2185. continue;
  2186. Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
  2187. << Arg->getType() << AT.Type << 1 /* different class */
  2188. << 0 /* qualifier difference */ << 3 /* parameter mismatch */
  2189. << AT.ArgNo + 1 << Arg->getType() << AT.Type;
  2190. }
  2191. return false;
  2192. }
  2193. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  2194. /// friends. This is declared to take (...), so we have to check everything.
  2195. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  2196. if (TheCall->getNumArgs() < 2)
  2197. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  2198. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  2199. if (TheCall->getNumArgs() > 2)
  2200. return Diag(TheCall->getArg(2)->getLocStart(),
  2201. diag::err_typecheck_call_too_many_args)
  2202. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  2203. << SourceRange(TheCall->getArg(2)->getLocStart(),
  2204. (*(TheCall->arg_end()-1))->getLocEnd());
  2205. ExprResult OrigArg0 = TheCall->getArg(0);
  2206. ExprResult OrigArg1 = TheCall->getArg(1);
  2207. // Do standard promotions between the two arguments, returning their common
  2208. // type.
  2209. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  2210. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  2211. return true;
  2212. // Make sure any conversions are pushed back into the call; this is
  2213. // type safe since unordered compare builtins are declared as "_Bool
  2214. // foo(...)".
  2215. TheCall->setArg(0, OrigArg0.get());
  2216. TheCall->setArg(1, OrigArg1.get());
  2217. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  2218. return false;
  2219. // If the common type isn't a real floating type, then the arguments were
  2220. // invalid for this operation.
  2221. if (Res.isNull() || !Res->isRealFloatingType())
  2222. return Diag(OrigArg0.get()->getLocStart(),
  2223. diag::err_typecheck_call_invalid_ordered_compare)
  2224. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  2225. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  2226. return false;
  2227. }
  2228. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  2229. /// __builtin_isnan and friends. This is declared to take (...), so we have
  2230. /// to check everything. We expect the last argument to be a floating point
  2231. /// value.
  2232. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  2233. if (TheCall->getNumArgs() < NumArgs)
  2234. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  2235. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  2236. if (TheCall->getNumArgs() > NumArgs)
  2237. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  2238. diag::err_typecheck_call_too_many_args)
  2239. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  2240. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  2241. (*(TheCall->arg_end()-1))->getLocEnd());
  2242. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  2243. if (OrigArg->isTypeDependent())
  2244. return false;
  2245. // This operation requires a non-_Complex floating-point number.
  2246. if (!OrigArg->getType()->isRealFloatingType())
  2247. return Diag(OrigArg->getLocStart(),
  2248. diag::err_typecheck_call_invalid_unary_fp)
  2249. << OrigArg->getType() << OrigArg->getSourceRange();
  2250. // If this is an implicit conversion from float -> double, remove it.
  2251. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  2252. Expr *CastArg = Cast->getSubExpr();
  2253. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  2254. assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
  2255. "promotion from float to double is the only expected cast here");
  2256. Cast->setSubExpr(nullptr);
  2257. TheCall->setArg(NumArgs-1, CastArg);
  2258. }
  2259. }
  2260. return false;
  2261. }
  2262. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  2263. // This is declared to take (...), so we have to check everything.
  2264. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  2265. if (TheCall->getNumArgs() < 2)
  2266. return ExprError(Diag(TheCall->getLocEnd(),
  2267. diag::err_typecheck_call_too_few_args_at_least)
  2268. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  2269. << TheCall->getSourceRange());
  2270. // Determine which of the following types of shufflevector we're checking:
  2271. // 1) unary, vector mask: (lhs, mask)
  2272. // 2) binary, vector mask: (lhs, rhs, mask)
  2273. // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
  2274. QualType resType = TheCall->getArg(0)->getType();
  2275. unsigned numElements = 0;
  2276. if (!TheCall->getArg(0)->isTypeDependent() &&
  2277. !TheCall->getArg(1)->isTypeDependent()) {
  2278. QualType LHSType = TheCall->getArg(0)->getType();
  2279. QualType RHSType = TheCall->getArg(1)->getType();
  2280. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  2281. return ExprError(Diag(TheCall->getLocStart(),
  2282. diag::err_shufflevector_non_vector)
  2283. << SourceRange(TheCall->getArg(0)->getLocStart(),
  2284. TheCall->getArg(1)->getLocEnd()));
  2285. numElements = LHSType->getAs<VectorType>()->getNumElements();
  2286. unsigned numResElements = TheCall->getNumArgs() - 2;
  2287. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  2288. // with mask. If so, verify that RHS is an integer vector type with the
  2289. // same number of elts as lhs.
  2290. if (TheCall->getNumArgs() == 2) {
  2291. if (!RHSType->hasIntegerRepresentation() ||
  2292. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  2293. return ExprError(Diag(TheCall->getLocStart(),
  2294. diag::err_shufflevector_incompatible_vector)
  2295. << SourceRange(TheCall->getArg(1)->getLocStart(),
  2296. TheCall->getArg(1)->getLocEnd()));
  2297. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  2298. return ExprError(Diag(TheCall->getLocStart(),
  2299. diag::err_shufflevector_incompatible_vector)
  2300. << SourceRange(TheCall->getArg(0)->getLocStart(),
  2301. TheCall->getArg(1)->getLocEnd()));
  2302. } else if (numElements != numResElements) {
  2303. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  2304. resType = Context.getVectorType(eltType, numResElements,
  2305. VectorType::GenericVector);
  2306. }
  2307. }
  2308. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  2309. if (TheCall->getArg(i)->isTypeDependent() ||
  2310. TheCall->getArg(i)->isValueDependent())
  2311. continue;
  2312. llvm::APSInt Result(32);
  2313. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  2314. return ExprError(Diag(TheCall->getLocStart(),
  2315. diag::err_shufflevector_nonconstant_argument)
  2316. << TheCall->getArg(i)->getSourceRange());
  2317. // Allow -1 which will be translated to undef in the IR.
  2318. if (Result.isSigned() && Result.isAllOnesValue())
  2319. continue;
  2320. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  2321. return ExprError(Diag(TheCall->getLocStart(),
  2322. diag::err_shufflevector_argument_too_large)
  2323. << TheCall->getArg(i)->getSourceRange());
  2324. }
  2325. SmallVector<Expr*, 32> exprs;
  2326. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  2327. exprs.push_back(TheCall->getArg(i));
  2328. TheCall->setArg(i, nullptr);
  2329. }
  2330. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  2331. TheCall->getCallee()->getLocStart(),
  2332. TheCall->getRParenLoc());
  2333. }
  2334. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  2335. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  2336. SourceLocation BuiltinLoc,
  2337. SourceLocation RParenLoc) {
  2338. ExprValueKind VK = VK_RValue;
  2339. ExprObjectKind OK = OK_Ordinary;
  2340. QualType DstTy = TInfo->getType();
  2341. QualType SrcTy = E->getType();
  2342. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  2343. return ExprError(Diag(BuiltinLoc,
  2344. diag::err_convertvector_non_vector)
  2345. << E->getSourceRange());
  2346. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  2347. return ExprError(Diag(BuiltinLoc,
  2348. diag::err_convertvector_non_vector_type));
  2349. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  2350. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  2351. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  2352. if (SrcElts != DstElts)
  2353. return ExprError(Diag(BuiltinLoc,
  2354. diag::err_convertvector_incompatible_vector)
  2355. << E->getSourceRange());
  2356. }
  2357. return new (Context)
  2358. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  2359. }
  2360. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  2361. // This is declared to take (const void*, ...) and can take two
  2362. // optional constant int args.
  2363. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  2364. unsigned NumArgs = TheCall->getNumArgs();
  2365. if (NumArgs > 3)
  2366. return Diag(TheCall->getLocEnd(),
  2367. diag::err_typecheck_call_too_many_args_at_most)
  2368. << 0 /*function call*/ << 3 << NumArgs
  2369. << TheCall->getSourceRange();
  2370. // Argument 0 is checked for us and the remaining arguments must be
  2371. // constant integers.
  2372. for (unsigned i = 1; i != NumArgs; ++i)
  2373. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  2374. return true;
  2375. return false;
  2376. }
  2377. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  2378. // __assume does not evaluate its arguments, and should warn if its argument
  2379. // has side effects.
  2380. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  2381. Expr *Arg = TheCall->getArg(0);
  2382. if (Arg->isInstantiationDependent()) return false;
  2383. if (Arg->HasSideEffects(Context))
  2384. Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
  2385. << Arg->getSourceRange()
  2386. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  2387. return false;
  2388. }
  2389. /// Handle __builtin_assume_aligned. This is declared
  2390. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  2391. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  2392. unsigned NumArgs = TheCall->getNumArgs();
  2393. if (NumArgs > 3)
  2394. return Diag(TheCall->getLocEnd(),
  2395. diag::err_typecheck_call_too_many_args_at_most)
  2396. << 0 /*function call*/ << 3 << NumArgs
  2397. << TheCall->getSourceRange();
  2398. // The alignment must be a constant integer.
  2399. Expr *Arg = TheCall->getArg(1);
  2400. // We can't check the value of a dependent argument.
  2401. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  2402. llvm::APSInt Result;
  2403. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  2404. return true;
  2405. if (!Result.isPowerOf2())
  2406. return Diag(TheCall->getLocStart(),
  2407. diag::err_alignment_not_power_of_two)
  2408. << Arg->getSourceRange();
  2409. }
  2410. if (NumArgs > 2) {
  2411. ExprResult Arg(TheCall->getArg(2));
  2412. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  2413. Context.getSizeType(), false);
  2414. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  2415. if (Arg.isInvalid()) return true;
  2416. TheCall->setArg(2, Arg.get());
  2417. }
  2418. return false;
  2419. }
  2420. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  2421. /// TheCall is a constant expression.
  2422. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  2423. llvm::APSInt &Result) {
  2424. Expr *Arg = TheCall->getArg(ArgNum);
  2425. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  2426. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  2427. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  2428. if (!Arg->isIntegerConstantExpr(Result, Context))
  2429. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  2430. << FDecl->getDeclName() << Arg->getSourceRange();
  2431. return false;
  2432. }
  2433. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  2434. /// TheCall is a constant expression in the range [Low, High].
  2435. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  2436. int Low, int High) {
  2437. llvm::APSInt Result;
  2438. // We can't check the value of a dependent argument.
  2439. Expr *Arg = TheCall->getArg(ArgNum);
  2440. if (Arg->isTypeDependent() || Arg->isValueDependent())
  2441. return false;
  2442. // Check constant-ness first.
  2443. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  2444. return true;
  2445. if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
  2446. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  2447. << Low << High << Arg->getSourceRange();
  2448. return false;
  2449. }
  2450. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  2451. /// TheCall is an ARM/AArch64 special register string literal.
  2452. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  2453. int ArgNum, unsigned ExpectedFieldNum,
  2454. bool AllowName) {
  2455. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  2456. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  2457. BuiltinID == ARM::BI__builtin_arm_rsr ||
  2458. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  2459. BuiltinID == ARM::BI__builtin_arm_wsr ||
  2460. BuiltinID == ARM::BI__builtin_arm_wsrp;
  2461. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  2462. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  2463. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  2464. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  2465. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  2466. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  2467. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  2468. // We can't check the value of a dependent argument.
  2469. Expr *Arg = TheCall->getArg(ArgNum);
  2470. if (Arg->isTypeDependent() || Arg->isValueDependent())
  2471. return false;
  2472. // Check if the argument is a string literal.
  2473. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  2474. return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  2475. << Arg->getSourceRange();
  2476. // Check the type of special register given.
  2477. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  2478. SmallVector<StringRef, 6> Fields;
  2479. Reg.split(Fields, ":");
  2480. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  2481. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  2482. << Arg->getSourceRange();
  2483. // If the string is the name of a register then we cannot check that it is
  2484. // valid here but if the string is of one the forms described in ACLE then we
  2485. // can check that the supplied fields are integers and within the valid
  2486. // ranges.
  2487. if (Fields.size() > 1) {
  2488. bool FiveFields = Fields.size() == 5;
  2489. bool ValidString = true;
  2490. if (IsARMBuiltin) {
  2491. ValidString &= Fields[0].startswith_lower("cp") ||
  2492. Fields[0].startswith_lower("p");
  2493. if (ValidString)
  2494. Fields[0] =
  2495. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  2496. ValidString &= Fields[2].startswith_lower("c");
  2497. if (ValidString)
  2498. Fields[2] = Fields[2].drop_front(1);
  2499. if (FiveFields) {
  2500. ValidString &= Fields[3].startswith_lower("c");
  2501. if (ValidString)
  2502. Fields[3] = Fields[3].drop_front(1);
  2503. }
  2504. }
  2505. SmallVector<int, 5> Ranges;
  2506. if (FiveFields)
  2507. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
  2508. else
  2509. Ranges.append({15, 7, 15});
  2510. for (unsigned i=0; i<Fields.size(); ++i) {
  2511. int IntField;
  2512. ValidString &= !Fields[i].getAsInteger(10, IntField);
  2513. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  2514. }
  2515. if (!ValidString)
  2516. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  2517. << Arg->getSourceRange();
  2518. } else if (IsAArch64Builtin && Fields.size() == 1) {
  2519. // If the register name is one of those that appear in the condition below
  2520. // and the special register builtin being used is one of the write builtins,
  2521. // then we require that the argument provided for writing to the register
  2522. // is an integer constant expression. This is because it will be lowered to
  2523. // an MSR (immediate) instruction, so we need to know the immediate at
  2524. // compile time.
  2525. if (TheCall->getNumArgs() != 2)
  2526. return false;
  2527. std::string RegLower = Reg.lower();
  2528. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  2529. RegLower != "pan" && RegLower != "uao")
  2530. return false;
  2531. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  2532. }
  2533. return false;
  2534. }
  2535. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  2536. /// This checks that the target supports __builtin_cpu_supports and
  2537. /// that the string argument is constant and valid.
  2538. bool Sema::SemaBuiltinCpuSupports(CallExpr *TheCall) {
  2539. Expr *Arg = TheCall->getArg(0);
  2540. // Check if the argument is a string literal.
  2541. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  2542. return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  2543. << Arg->getSourceRange();
  2544. // Check the contents of the string.
  2545. StringRef Feature =
  2546. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  2547. if (!Context.getTargetInfo().validateCpuSupports(Feature))
  2548. return Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
  2549. << Arg->getSourceRange();
  2550. return false;
  2551. }
  2552. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  2553. /// This checks that the target supports __builtin_longjmp and
  2554. /// that val is a constant 1.
  2555. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  2556. if (!Context.getTargetInfo().hasSjLjLowering())
  2557. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
  2558. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  2559. Expr *Arg = TheCall->getArg(1);
  2560. llvm::APSInt Result;
  2561. // TODO: This is less than ideal. Overload this to take a value.
  2562. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  2563. return true;
  2564. if (Result != 1)
  2565. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  2566. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  2567. return false;
  2568. }
  2569. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  2570. /// This checks that the target supports __builtin_setjmp.
  2571. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  2572. if (!Context.getTargetInfo().hasSjLjLowering())
  2573. return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
  2574. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  2575. return false;
  2576. }
  2577. namespace {
  2578. enum StringLiteralCheckType {
  2579. SLCT_NotALiteral,
  2580. SLCT_UncheckedLiteral,
  2581. SLCT_CheckedLiteral
  2582. };
  2583. }
  2584. // Determine if an expression is a string literal or constant string.
  2585. // If this function returns false on the arguments to a function expecting a
  2586. // format string, we will usually need to emit a warning.
  2587. // True string literals are then checked by CheckFormatString.
  2588. static StringLiteralCheckType
  2589. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  2590. bool HasVAListArg, unsigned format_idx,
  2591. unsigned firstDataArg, Sema::FormatStringType Type,
  2592. Sema::VariadicCallType CallType, bool InFunctionCall,
  2593. llvm::SmallBitVector &CheckedVarArgs) {
  2594. tryAgain:
  2595. if (E->isTypeDependent() || E->isValueDependent())
  2596. return SLCT_NotALiteral;
  2597. E = E->IgnoreParenCasts();
  2598. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  2599. // Technically -Wformat-nonliteral does not warn about this case.
  2600. // The behavior of printf and friends in this case is implementation
  2601. // dependent. Ideally if the format string cannot be null then
  2602. // it should have a 'nonnull' attribute in the function prototype.
  2603. return SLCT_UncheckedLiteral;
  2604. switch (E->getStmtClass()) {
  2605. case Stmt::BinaryConditionalOperatorClass:
  2606. case Stmt::ConditionalOperatorClass: {
  2607. // The expression is a literal if both sub-expressions were, and it was
  2608. // completely checked only if both sub-expressions were checked.
  2609. const AbstractConditionalOperator *C =
  2610. cast<AbstractConditionalOperator>(E);
  2611. StringLiteralCheckType Left =
  2612. checkFormatStringExpr(S, C->getTrueExpr(), Args,
  2613. HasVAListArg, format_idx, firstDataArg,
  2614. Type, CallType, InFunctionCall, CheckedVarArgs);
  2615. if (Left == SLCT_NotALiteral)
  2616. return SLCT_NotALiteral;
  2617. StringLiteralCheckType Right =
  2618. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  2619. HasVAListArg, format_idx, firstDataArg,
  2620. Type, CallType, InFunctionCall, CheckedVarArgs);
  2621. return Left < Right ? Left : Right;
  2622. }
  2623. case Stmt::ImplicitCastExprClass: {
  2624. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  2625. goto tryAgain;
  2626. }
  2627. case Stmt::OpaqueValueExprClass:
  2628. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  2629. E = src;
  2630. goto tryAgain;
  2631. }
  2632. return SLCT_NotALiteral;
  2633. case Stmt::PredefinedExprClass:
  2634. // While __func__, etc., are technically not string literals, they
  2635. // cannot contain format specifiers and thus are not a security
  2636. // liability.
  2637. return SLCT_UncheckedLiteral;
  2638. case Stmt::DeclRefExprClass: {
  2639. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  2640. // As an exception, do not flag errors for variables binding to
  2641. // const string literals.
  2642. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  2643. bool isConstant = false;
  2644. QualType T = DR->getType();
  2645. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  2646. isConstant = AT->getElementType().isConstant(S.Context);
  2647. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  2648. isConstant = T.isConstant(S.Context) &&
  2649. PT->getPointeeType().isConstant(S.Context);
  2650. } else if (T->isObjCObjectPointerType()) {
  2651. // In ObjC, there is usually no "const ObjectPointer" type,
  2652. // so don't check if the pointee type is constant.
  2653. isConstant = T.isConstant(S.Context);
  2654. }
  2655. if (isConstant) {
  2656. if (const Expr *Init = VD->getAnyInitializer()) {
  2657. // Look through initializers like const char c[] = { "foo" }
  2658. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  2659. if (InitList->isStringLiteralInit())
  2660. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  2661. }
  2662. return checkFormatStringExpr(S, Init, Args,
  2663. HasVAListArg, format_idx,
  2664. firstDataArg, Type, CallType,
  2665. /*InFunctionCall*/false, CheckedVarArgs);
  2666. }
  2667. }
  2668. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  2669. // special check to see if the format string is a function parameter
  2670. // of the function calling the printf function. If the function
  2671. // has an attribute indicating it is a printf-like function, then we
  2672. // should suppress warnings concerning non-literals being used in a call
  2673. // to a vprintf function. For example:
  2674. //
  2675. // void
  2676. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  2677. // va_list ap;
  2678. // va_start(ap, fmt);
  2679. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  2680. // ...
  2681. // }
  2682. if (HasVAListArg) {
  2683. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  2684. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  2685. int PVIndex = PV->getFunctionScopeIndex() + 1;
  2686. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  2687. // adjust for implicit parameter
  2688. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  2689. if (MD->isInstance())
  2690. ++PVIndex;
  2691. // We also check if the formats are compatible.
  2692. // We can't pass a 'scanf' string to a 'printf' function.
  2693. if (PVIndex == PVFormat->getFormatIdx() &&
  2694. Type == S.GetFormatStringType(PVFormat))
  2695. return SLCT_UncheckedLiteral;
  2696. }
  2697. }
  2698. }
  2699. }
  2700. }
  2701. return SLCT_NotALiteral;
  2702. }
  2703. case Stmt::CallExprClass:
  2704. case Stmt::CXXMemberCallExprClass: {
  2705. const CallExpr *CE = cast<CallExpr>(E);
  2706. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  2707. if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
  2708. unsigned ArgIndex = FA->getFormatIdx();
  2709. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  2710. if (MD->isInstance())
  2711. --ArgIndex;
  2712. const Expr *Arg = CE->getArg(ArgIndex - 1);
  2713. return checkFormatStringExpr(S, Arg, Args,
  2714. HasVAListArg, format_idx, firstDataArg,
  2715. Type, CallType, InFunctionCall,
  2716. CheckedVarArgs);
  2717. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  2718. unsigned BuiltinID = FD->getBuiltinID();
  2719. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  2720. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  2721. const Expr *Arg = CE->getArg(0);
  2722. return checkFormatStringExpr(S, Arg, Args,
  2723. HasVAListArg, format_idx,
  2724. firstDataArg, Type, CallType,
  2725. InFunctionCall, CheckedVarArgs);
  2726. }
  2727. }
  2728. }
  2729. return SLCT_NotALiteral;
  2730. }
  2731. case Stmt::ObjCStringLiteralClass:
  2732. case Stmt::StringLiteralClass: {
  2733. const StringLiteral *StrE = nullptr;
  2734. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  2735. StrE = ObjCFExpr->getString();
  2736. else
  2737. StrE = cast<StringLiteral>(E);
  2738. if (StrE) {
  2739. S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
  2740. Type, InFunctionCall, CallType, CheckedVarArgs);
  2741. return SLCT_CheckedLiteral;
  2742. }
  2743. return SLCT_NotALiteral;
  2744. }
  2745. default:
  2746. return SLCT_NotALiteral;
  2747. }
  2748. }
  2749. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  2750. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  2751. .Case("scanf", FST_Scanf)
  2752. .Cases("printf", "printf0", FST_Printf)
  2753. .Cases("NSString", "CFString", FST_NSString)
  2754. .Case("strftime", FST_Strftime)
  2755. .Case("strfmon", FST_Strfmon)
  2756. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  2757. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  2758. .Case("os_trace", FST_OSTrace)
  2759. .Default(FST_Unknown);
  2760. }
  2761. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  2762. /// functions) for correct use of format strings.
  2763. /// Returns true if a format string has been fully checked.
  2764. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  2765. ArrayRef<const Expr *> Args,
  2766. bool IsCXXMember,
  2767. VariadicCallType CallType,
  2768. SourceLocation Loc, SourceRange Range,
  2769. llvm::SmallBitVector &CheckedVarArgs) {
  2770. FormatStringInfo FSI;
  2771. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  2772. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  2773. FSI.FirstDataArg, GetFormatStringType(Format),
  2774. CallType, Loc, Range, CheckedVarArgs);
  2775. return false;
  2776. }
  2777. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  2778. bool HasVAListArg, unsigned format_idx,
  2779. unsigned firstDataArg, FormatStringType Type,
  2780. VariadicCallType CallType,
  2781. SourceLocation Loc, SourceRange Range,
  2782. llvm::SmallBitVector &CheckedVarArgs) {
  2783. // CHECK: printf/scanf-like function is called with no format string.
  2784. if (format_idx >= Args.size()) {
  2785. Diag(Loc, diag::warn_missing_format_string) << Range;
  2786. return false;
  2787. }
  2788. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  2789. // CHECK: format string is not a string literal.
  2790. //
  2791. // Dynamically generated format strings are difficult to
  2792. // automatically vet at compile time. Requiring that format strings
  2793. // are string literals: (1) permits the checking of format strings by
  2794. // the compiler and thereby (2) can practically remove the source of
  2795. // many format string exploits.
  2796. // Format string can be either ObjC string (e.g. @"%d") or
  2797. // C string (e.g. "%d")
  2798. // ObjC string uses the same format specifiers as C string, so we can use
  2799. // the same format string checking logic for both ObjC and C strings.
  2800. StringLiteralCheckType CT =
  2801. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  2802. format_idx, firstDataArg, Type, CallType,
  2803. /*IsFunctionCall*/true, CheckedVarArgs);
  2804. if (CT != SLCT_NotALiteral)
  2805. // Literal format string found, check done!
  2806. return CT == SLCT_CheckedLiteral;
  2807. // Strftime is particular as it always uses a single 'time' argument,
  2808. // so it is safe to pass a non-literal string.
  2809. if (Type == FST_Strftime)
  2810. return false;
  2811. // Do not emit diag when the string param is a macro expansion and the
  2812. // format is either NSString or CFString. This is a hack to prevent
  2813. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  2814. // which are usually used in place of NS and CF string literals.
  2815. if (Type == FST_NSString &&
  2816. SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
  2817. return false;
  2818. // If there are no arguments specified, warn with -Wformat-security, otherwise
  2819. // warn only with -Wformat-nonliteral.
  2820. if (Args.size() == firstDataArg)
  2821. Diag(Args[format_idx]->getLocStart(),
  2822. diag::warn_format_nonliteral_noargs)
  2823. << OrigFormatExpr->getSourceRange();
  2824. else
  2825. Diag(Args[format_idx]->getLocStart(),
  2826. diag::warn_format_nonliteral)
  2827. << OrigFormatExpr->getSourceRange();
  2828. return false;
  2829. }
  2830. namespace {
  2831. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  2832. protected:
  2833. Sema &S;
  2834. const StringLiteral *FExpr;
  2835. const Expr *OrigFormatExpr;
  2836. const unsigned FirstDataArg;
  2837. const unsigned NumDataArgs;
  2838. const char *Beg; // Start of format string.
  2839. const bool HasVAListArg;
  2840. ArrayRef<const Expr *> Args;
  2841. unsigned FormatIdx;
  2842. llvm::SmallBitVector CoveredArgs;
  2843. bool usesPositionalArgs;
  2844. bool atFirstArg;
  2845. bool inFunctionCall;
  2846. Sema::VariadicCallType CallType;
  2847. llvm::SmallBitVector &CheckedVarArgs;
  2848. public:
  2849. CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
  2850. const Expr *origFormatExpr, unsigned firstDataArg,
  2851. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  2852. ArrayRef<const Expr *> Args,
  2853. unsigned formatIdx, bool inFunctionCall,
  2854. Sema::VariadicCallType callType,
  2855. llvm::SmallBitVector &CheckedVarArgs)
  2856. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
  2857. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
  2858. Beg(beg), HasVAListArg(hasVAListArg),
  2859. Args(Args), FormatIdx(formatIdx),
  2860. usesPositionalArgs(false), atFirstArg(true),
  2861. inFunctionCall(inFunctionCall), CallType(callType),
  2862. CheckedVarArgs(CheckedVarArgs) {
  2863. CoveredArgs.resize(numDataArgs);
  2864. CoveredArgs.reset();
  2865. }
  2866. void DoneProcessing();
  2867. void HandleIncompleteSpecifier(const char *startSpecifier,
  2868. unsigned specifierLen) override;
  2869. void HandleInvalidLengthModifier(
  2870. const analyze_format_string::FormatSpecifier &FS,
  2871. const analyze_format_string::ConversionSpecifier &CS,
  2872. const char *startSpecifier, unsigned specifierLen,
  2873. unsigned DiagID);
  2874. void HandleNonStandardLengthModifier(
  2875. const analyze_format_string::FormatSpecifier &FS,
  2876. const char *startSpecifier, unsigned specifierLen);
  2877. void HandleNonStandardConversionSpecifier(
  2878. const analyze_format_string::ConversionSpecifier &CS,
  2879. const char *startSpecifier, unsigned specifierLen);
  2880. void HandlePosition(const char *startPos, unsigned posLen) override;
  2881. void HandleInvalidPosition(const char *startSpecifier,
  2882. unsigned specifierLen,
  2883. analyze_format_string::PositionContext p) override;
  2884. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  2885. void HandleNullChar(const char *nullCharacter) override;
  2886. template <typename Range>
  2887. static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
  2888. const Expr *ArgumentExpr,
  2889. PartialDiagnostic PDiag,
  2890. SourceLocation StringLoc,
  2891. bool IsStringLocation, Range StringRange,
  2892. ArrayRef<FixItHint> Fixit = None);
  2893. protected:
  2894. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  2895. const char *startSpec,
  2896. unsigned specifierLen,
  2897. const char *csStart, unsigned csLen);
  2898. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  2899. const char *startSpec,
  2900. unsigned specifierLen);
  2901. SourceRange getFormatStringRange();
  2902. CharSourceRange getSpecifierRange(const char *startSpecifier,
  2903. unsigned specifierLen);
  2904. SourceLocation getLocationOfByte(const char *x);
  2905. const Expr *getDataArg(unsigned i) const;
  2906. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  2907. const analyze_format_string::ConversionSpecifier &CS,
  2908. const char *startSpecifier, unsigned specifierLen,
  2909. unsigned argIndex);
  2910. template <typename Range>
  2911. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  2912. bool IsStringLocation, Range StringRange,
  2913. ArrayRef<FixItHint> Fixit = None);
  2914. };
  2915. }
  2916. SourceRange CheckFormatHandler::getFormatStringRange() {
  2917. return OrigFormatExpr->getSourceRange();
  2918. }
  2919. CharSourceRange CheckFormatHandler::
  2920. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  2921. SourceLocation Start = getLocationOfByte(startSpecifier);
  2922. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  2923. // Advance the end SourceLocation by one due to half-open ranges.
  2924. End = End.getLocWithOffset(1);
  2925. return CharSourceRange::getCharRange(Start, End);
  2926. }
  2927. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  2928. return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
  2929. }
  2930. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  2931. unsigned specifierLen){
  2932. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  2933. getLocationOfByte(startSpecifier),
  2934. /*IsStringLocation*/true,
  2935. getSpecifierRange(startSpecifier, specifierLen));
  2936. }
  2937. void CheckFormatHandler::HandleInvalidLengthModifier(
  2938. const analyze_format_string::FormatSpecifier &FS,
  2939. const analyze_format_string::ConversionSpecifier &CS,
  2940. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  2941. using namespace analyze_format_string;
  2942. const LengthModifier &LM = FS.getLengthModifier();
  2943. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  2944. // See if we know how to fix this length modifier.
  2945. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  2946. if (FixedLM) {
  2947. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  2948. getLocationOfByte(LM.getStart()),
  2949. /*IsStringLocation*/true,
  2950. getSpecifierRange(startSpecifier, specifierLen));
  2951. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  2952. << FixedLM->toString()
  2953. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  2954. } else {
  2955. FixItHint Hint;
  2956. if (DiagID == diag::warn_format_nonsensical_length)
  2957. Hint = FixItHint::CreateRemoval(LMRange);
  2958. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  2959. getLocationOfByte(LM.getStart()),
  2960. /*IsStringLocation*/true,
  2961. getSpecifierRange(startSpecifier, specifierLen),
  2962. Hint);
  2963. }
  2964. }
  2965. void CheckFormatHandler::HandleNonStandardLengthModifier(
  2966. const analyze_format_string::FormatSpecifier &FS,
  2967. const char *startSpecifier, unsigned specifierLen) {
  2968. using namespace analyze_format_string;
  2969. const LengthModifier &LM = FS.getLengthModifier();
  2970. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  2971. // See if we know how to fix this length modifier.
  2972. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  2973. if (FixedLM) {
  2974. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2975. << LM.toString() << 0,
  2976. getLocationOfByte(LM.getStart()),
  2977. /*IsStringLocation*/true,
  2978. getSpecifierRange(startSpecifier, specifierLen));
  2979. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  2980. << FixedLM->toString()
  2981. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  2982. } else {
  2983. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2984. << LM.toString() << 0,
  2985. getLocationOfByte(LM.getStart()),
  2986. /*IsStringLocation*/true,
  2987. getSpecifierRange(startSpecifier, specifierLen));
  2988. }
  2989. }
  2990. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  2991. const analyze_format_string::ConversionSpecifier &CS,
  2992. const char *startSpecifier, unsigned specifierLen) {
  2993. using namespace analyze_format_string;
  2994. // See if we know how to fix this conversion specifier.
  2995. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  2996. if (FixedCS) {
  2997. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2998. << CS.toString() << /*conversion specifier*/1,
  2999. getLocationOfByte(CS.getStart()),
  3000. /*IsStringLocation*/true,
  3001. getSpecifierRange(startSpecifier, specifierLen));
  3002. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  3003. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  3004. << FixedCS->toString()
  3005. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  3006. } else {
  3007. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  3008. << CS.toString() << /*conversion specifier*/1,
  3009. getLocationOfByte(CS.getStart()),
  3010. /*IsStringLocation*/true,
  3011. getSpecifierRange(startSpecifier, specifierLen));
  3012. }
  3013. }
  3014. void CheckFormatHandler::HandlePosition(const char *startPos,
  3015. unsigned posLen) {
  3016. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  3017. getLocationOfByte(startPos),
  3018. /*IsStringLocation*/true,
  3019. getSpecifierRange(startPos, posLen));
  3020. }
  3021. void
  3022. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  3023. analyze_format_string::PositionContext p) {
  3024. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  3025. << (unsigned) p,
  3026. getLocationOfByte(startPos), /*IsStringLocation*/true,
  3027. getSpecifierRange(startPos, posLen));
  3028. }
  3029. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  3030. unsigned posLen) {
  3031. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  3032. getLocationOfByte(startPos),
  3033. /*IsStringLocation*/true,
  3034. getSpecifierRange(startPos, posLen));
  3035. }
  3036. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  3037. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  3038. // The presence of a null character is likely an error.
  3039. EmitFormatDiagnostic(
  3040. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  3041. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  3042. getFormatStringRange());
  3043. }
  3044. }
  3045. // Note that this may return NULL if there was an error parsing or building
  3046. // one of the argument expressions.
  3047. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  3048. return Args[FirstDataArg + i];
  3049. }
  3050. void CheckFormatHandler::DoneProcessing() {
  3051. // Does the number of data arguments exceed the number of
  3052. // format conversions in the format string?
  3053. if (!HasVAListArg) {
  3054. // Find any arguments that weren't covered.
  3055. CoveredArgs.flip();
  3056. signed notCoveredArg = CoveredArgs.find_first();
  3057. if (notCoveredArg >= 0) {
  3058. assert((unsigned)notCoveredArg < NumDataArgs);
  3059. if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
  3060. SourceLocation Loc = E->getLocStart();
  3061. if (!S.getSourceManager().isInSystemMacro(Loc)) {
  3062. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
  3063. Loc, /*IsStringLocation*/false,
  3064. getFormatStringRange());
  3065. }
  3066. }
  3067. }
  3068. }
  3069. }
  3070. bool
  3071. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  3072. SourceLocation Loc,
  3073. const char *startSpec,
  3074. unsigned specifierLen,
  3075. const char *csStart,
  3076. unsigned csLen) {
  3077. bool keepGoing = true;
  3078. if (argIndex < NumDataArgs) {
  3079. // Consider the argument coverered, even though the specifier doesn't
  3080. // make sense.
  3081. CoveredArgs.set(argIndex);
  3082. }
  3083. else {
  3084. // If argIndex exceeds the number of data arguments we
  3085. // don't issue a warning because that is just a cascade of warnings (and
  3086. // they may have intended '%%' anyway). We don't want to continue processing
  3087. // the format string after this point, however, as we will like just get
  3088. // gibberish when trying to match arguments.
  3089. keepGoing = false;
  3090. }
  3091. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
  3092. << StringRef(csStart, csLen),
  3093. Loc, /*IsStringLocation*/true,
  3094. getSpecifierRange(startSpec, specifierLen));
  3095. return keepGoing;
  3096. }
  3097. void
  3098. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  3099. const char *startSpec,
  3100. unsigned specifierLen) {
  3101. EmitFormatDiagnostic(
  3102. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  3103. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  3104. }
  3105. bool
  3106. CheckFormatHandler::CheckNumArgs(
  3107. const analyze_format_string::FormatSpecifier &FS,
  3108. const analyze_format_string::ConversionSpecifier &CS,
  3109. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  3110. if (argIndex >= NumDataArgs) {
  3111. PartialDiagnostic PDiag = FS.usesPositionalArg()
  3112. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  3113. << (argIndex+1) << NumDataArgs)
  3114. : S.PDiag(diag::warn_printf_insufficient_data_args);
  3115. EmitFormatDiagnostic(
  3116. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  3117. getSpecifierRange(startSpecifier, specifierLen));
  3118. return false;
  3119. }
  3120. return true;
  3121. }
  3122. template<typename Range>
  3123. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  3124. SourceLocation Loc,
  3125. bool IsStringLocation,
  3126. Range StringRange,
  3127. ArrayRef<FixItHint> FixIt) {
  3128. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  3129. Loc, IsStringLocation, StringRange, FixIt);
  3130. }
  3131. /// \brief If the format string is not within the funcion call, emit a note
  3132. /// so that the function call and string are in diagnostic messages.
  3133. ///
  3134. /// \param InFunctionCall if true, the format string is within the function
  3135. /// call and only one diagnostic message will be produced. Otherwise, an
  3136. /// extra note will be emitted pointing to location of the format string.
  3137. ///
  3138. /// \param ArgumentExpr the expression that is passed as the format string
  3139. /// argument in the function call. Used for getting locations when two
  3140. /// diagnostics are emitted.
  3141. ///
  3142. /// \param PDiag the callee should already have provided any strings for the
  3143. /// diagnostic message. This function only adds locations and fixits
  3144. /// to diagnostics.
  3145. ///
  3146. /// \param Loc primary location for diagnostic. If two diagnostics are
  3147. /// required, one will be at Loc and a new SourceLocation will be created for
  3148. /// the other one.
  3149. ///
  3150. /// \param IsStringLocation if true, Loc points to the format string should be
  3151. /// used for the note. Otherwise, Loc points to the argument list and will
  3152. /// be used with PDiag.
  3153. ///
  3154. /// \param StringRange some or all of the string to highlight. This is
  3155. /// templated so it can accept either a CharSourceRange or a SourceRange.
  3156. ///
  3157. /// \param FixIt optional fix it hint for the format string.
  3158. template<typename Range>
  3159. void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
  3160. const Expr *ArgumentExpr,
  3161. PartialDiagnostic PDiag,
  3162. SourceLocation Loc,
  3163. bool IsStringLocation,
  3164. Range StringRange,
  3165. ArrayRef<FixItHint> FixIt) {
  3166. if (InFunctionCall) {
  3167. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  3168. D << StringRange;
  3169. D << FixIt;
  3170. } else {
  3171. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  3172. << ArgumentExpr->getSourceRange();
  3173. const Sema::SemaDiagnosticBuilder &Note =
  3174. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  3175. diag::note_format_string_defined);
  3176. Note << StringRange;
  3177. Note << FixIt;
  3178. }
  3179. }
  3180. //===--- CHECK: Printf format string checking ------------------------------===//
  3181. namespace {
  3182. class CheckPrintfHandler : public CheckFormatHandler {
  3183. bool ObjCContext;
  3184. public:
  3185. CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
  3186. const Expr *origFormatExpr, unsigned firstDataArg,
  3187. unsigned numDataArgs, bool isObjC,
  3188. const char *beg, bool hasVAListArg,
  3189. ArrayRef<const Expr *> Args,
  3190. unsigned formatIdx, bool inFunctionCall,
  3191. Sema::VariadicCallType CallType,
  3192. llvm::SmallBitVector &CheckedVarArgs)
  3193. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  3194. numDataArgs, beg, hasVAListArg, Args,
  3195. formatIdx, inFunctionCall, CallType, CheckedVarArgs),
  3196. ObjCContext(isObjC)
  3197. {}
  3198. bool HandleInvalidPrintfConversionSpecifier(
  3199. const analyze_printf::PrintfSpecifier &FS,
  3200. const char *startSpecifier,
  3201. unsigned specifierLen) override;
  3202. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  3203. const char *startSpecifier,
  3204. unsigned specifierLen) override;
  3205. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  3206. const char *StartSpecifier,
  3207. unsigned SpecifierLen,
  3208. const Expr *E);
  3209. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  3210. const char *startSpecifier, unsigned specifierLen);
  3211. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  3212. const analyze_printf::OptionalAmount &Amt,
  3213. unsigned type,
  3214. const char *startSpecifier, unsigned specifierLen);
  3215. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  3216. const analyze_printf::OptionalFlag &flag,
  3217. const char *startSpecifier, unsigned specifierLen);
  3218. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  3219. const analyze_printf::OptionalFlag &ignoredFlag,
  3220. const analyze_printf::OptionalFlag &flag,
  3221. const char *startSpecifier, unsigned specifierLen);
  3222. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  3223. const Expr *E);
  3224. void HandleEmptyObjCModifierFlag(const char *startFlag,
  3225. unsigned flagLen) override;
  3226. void HandleInvalidObjCModifierFlag(const char *startFlag,
  3227. unsigned flagLen) override;
  3228. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  3229. const char *flagsEnd,
  3230. const char *conversionPosition)
  3231. override;
  3232. };
  3233. }
  3234. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  3235. const analyze_printf::PrintfSpecifier &FS,
  3236. const char *startSpecifier,
  3237. unsigned specifierLen) {
  3238. const analyze_printf::PrintfConversionSpecifier &CS =
  3239. FS.getConversionSpecifier();
  3240. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  3241. getLocationOfByte(CS.getStart()),
  3242. startSpecifier, specifierLen,
  3243. CS.getStart(), CS.getLength());
  3244. }
  3245. bool CheckPrintfHandler::HandleAmount(
  3246. const analyze_format_string::OptionalAmount &Amt,
  3247. unsigned k, const char *startSpecifier,
  3248. unsigned specifierLen) {
  3249. if (Amt.hasDataArgument()) {
  3250. if (!HasVAListArg) {
  3251. unsigned argIndex = Amt.getArgIndex();
  3252. if (argIndex >= NumDataArgs) {
  3253. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  3254. << k,
  3255. getLocationOfByte(Amt.getStart()),
  3256. /*IsStringLocation*/true,
  3257. getSpecifierRange(startSpecifier, specifierLen));
  3258. // Don't do any more checking. We will just emit
  3259. // spurious errors.
  3260. return false;
  3261. }
  3262. // Type check the data argument. It should be an 'int'.
  3263. // Although not in conformance with C99, we also allow the argument to be
  3264. // an 'unsigned int' as that is a reasonably safe case. GCC also
  3265. // doesn't emit a warning for that case.
  3266. CoveredArgs.set(argIndex);
  3267. const Expr *Arg = getDataArg(argIndex);
  3268. if (!Arg)
  3269. return false;
  3270. QualType T = Arg->getType();
  3271. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  3272. assert(AT.isValid());
  3273. if (!AT.matchesType(S.Context, T)) {
  3274. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  3275. << k << AT.getRepresentativeTypeName(S.Context)
  3276. << T << Arg->getSourceRange(),
  3277. getLocationOfByte(Amt.getStart()),
  3278. /*IsStringLocation*/true,
  3279. getSpecifierRange(startSpecifier, specifierLen));
  3280. // Don't do any more checking. We will just emit
  3281. // spurious errors.
  3282. return false;
  3283. }
  3284. }
  3285. }
  3286. return true;
  3287. }
  3288. void CheckPrintfHandler::HandleInvalidAmount(
  3289. const analyze_printf::PrintfSpecifier &FS,
  3290. const analyze_printf::OptionalAmount &Amt,
  3291. unsigned type,
  3292. const char *startSpecifier,
  3293. unsigned specifierLen) {
  3294. const analyze_printf::PrintfConversionSpecifier &CS =
  3295. FS.getConversionSpecifier();
  3296. FixItHint fixit =
  3297. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  3298. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  3299. Amt.getConstantLength()))
  3300. : FixItHint();
  3301. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  3302. << type << CS.toString(),
  3303. getLocationOfByte(Amt.getStart()),
  3304. /*IsStringLocation*/true,
  3305. getSpecifierRange(startSpecifier, specifierLen),
  3306. fixit);
  3307. }
  3308. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  3309. const analyze_printf::OptionalFlag &flag,
  3310. const char *startSpecifier,
  3311. unsigned specifierLen) {
  3312. // Warn about pointless flag with a fixit removal.
  3313. const analyze_printf::PrintfConversionSpecifier &CS =
  3314. FS.getConversionSpecifier();
  3315. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  3316. << flag.toString() << CS.toString(),
  3317. getLocationOfByte(flag.getPosition()),
  3318. /*IsStringLocation*/true,
  3319. getSpecifierRange(startSpecifier, specifierLen),
  3320. FixItHint::CreateRemoval(
  3321. getSpecifierRange(flag.getPosition(), 1)));
  3322. }
  3323. void CheckPrintfHandler::HandleIgnoredFlag(
  3324. const analyze_printf::PrintfSpecifier &FS,
  3325. const analyze_printf::OptionalFlag &ignoredFlag,
  3326. const analyze_printf::OptionalFlag &flag,
  3327. const char *startSpecifier,
  3328. unsigned specifierLen) {
  3329. // Warn about ignored flag with a fixit removal.
  3330. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  3331. << ignoredFlag.toString() << flag.toString(),
  3332. getLocationOfByte(ignoredFlag.getPosition()),
  3333. /*IsStringLocation*/true,
  3334. getSpecifierRange(startSpecifier, specifierLen),
  3335. FixItHint::CreateRemoval(
  3336. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  3337. }
  3338. // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  3339. // bool IsStringLocation, Range StringRange,
  3340. // ArrayRef<FixItHint> Fixit = None);
  3341. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  3342. unsigned flagLen) {
  3343. // Warn about an empty flag.
  3344. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  3345. getLocationOfByte(startFlag),
  3346. /*IsStringLocation*/true,
  3347. getSpecifierRange(startFlag, flagLen));
  3348. }
  3349. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  3350. unsigned flagLen) {
  3351. // Warn about an invalid flag.
  3352. auto Range = getSpecifierRange(startFlag, flagLen);
  3353. StringRef flag(startFlag, flagLen);
  3354. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  3355. getLocationOfByte(startFlag),
  3356. /*IsStringLocation*/true,
  3357. Range, FixItHint::CreateRemoval(Range));
  3358. }
  3359. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  3360. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  3361. // Warn about using '[...]' without a '@' conversion.
  3362. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  3363. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  3364. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  3365. getLocationOfByte(conversionPosition),
  3366. /*IsStringLocation*/true,
  3367. Range, FixItHint::CreateRemoval(Range));
  3368. }
  3369. // Determines if the specified is a C++ class or struct containing
  3370. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  3371. // "c_str()").
  3372. template<typename MemberKind>
  3373. static llvm::SmallPtrSet<MemberKind*, 1>
  3374. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  3375. const RecordType *RT = Ty->getAs<RecordType>();
  3376. llvm::SmallPtrSet<MemberKind*, 1> Results;
  3377. if (!RT)
  3378. return Results;
  3379. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  3380. if (!RD || !RD->getDefinition())
  3381. return Results;
  3382. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  3383. Sema::LookupMemberName);
  3384. R.suppressDiagnostics();
  3385. // We just need to include all members of the right kind turned up by the
  3386. // filter, at this point.
  3387. if (S.LookupQualifiedName(R, RT->getDecl()))
  3388. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  3389. NamedDecl *decl = (*I)->getUnderlyingDecl();
  3390. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  3391. Results.insert(FK);
  3392. }
  3393. return Results;
  3394. }
  3395. /// Check if we could call '.c_str()' on an object.
  3396. ///
  3397. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  3398. /// allow the call, or if it would be ambiguous).
  3399. bool Sema::hasCStrMethod(const Expr *E) {
  3400. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  3401. MethodSet Results =
  3402. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  3403. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  3404. MI != ME; ++MI)
  3405. if ((*MI)->getMinRequiredArguments() == 0)
  3406. return true;
  3407. return false;
  3408. }
  3409. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  3410. // better diagnostic if so. AT is assumed to be valid.
  3411. // Returns true when a c_str() conversion method is found.
  3412. bool CheckPrintfHandler::checkForCStrMembers(
  3413. const analyze_printf::ArgType &AT, const Expr *E) {
  3414. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  3415. MethodSet Results =
  3416. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  3417. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  3418. MI != ME; ++MI) {
  3419. const CXXMethodDecl *Method = *MI;
  3420. if (Method->getMinRequiredArguments() == 0 &&
  3421. AT.matchesType(S.Context, Method->getReturnType())) {
  3422. // FIXME: Suggest parens if the expression needs them.
  3423. SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
  3424. S.Diag(E->getLocStart(), diag::note_printf_c_str)
  3425. << "c_str()"
  3426. << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  3427. return true;
  3428. }
  3429. }
  3430. return false;
  3431. }
  3432. bool
  3433. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  3434. &FS,
  3435. const char *startSpecifier,
  3436. unsigned specifierLen) {
  3437. using namespace analyze_format_string;
  3438. using namespace analyze_printf;
  3439. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  3440. if (FS.consumesDataArgument()) {
  3441. if (atFirstArg) {
  3442. atFirstArg = false;
  3443. usesPositionalArgs = FS.usesPositionalArg();
  3444. }
  3445. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  3446. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  3447. startSpecifier, specifierLen);
  3448. return false;
  3449. }
  3450. }
  3451. // First check if the field width, precision, and conversion specifier
  3452. // have matching data arguments.
  3453. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  3454. startSpecifier, specifierLen)) {
  3455. return false;
  3456. }
  3457. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  3458. startSpecifier, specifierLen)) {
  3459. return false;
  3460. }
  3461. if (!CS.consumesDataArgument()) {
  3462. // FIXME: Technically specifying a precision or field width here
  3463. // makes no sense. Worth issuing a warning at some point.
  3464. return true;
  3465. }
  3466. // Consume the argument.
  3467. unsigned argIndex = FS.getArgIndex();
  3468. if (argIndex < NumDataArgs) {
  3469. // The check to see if the argIndex is valid will come later.
  3470. // We set the bit here because we may exit early from this
  3471. // function if we encounter some other error.
  3472. CoveredArgs.set(argIndex);
  3473. }
  3474. // FreeBSD kernel extensions.
  3475. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  3476. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  3477. // We need at least two arguments.
  3478. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  3479. return false;
  3480. // Claim the second argument.
  3481. CoveredArgs.set(argIndex + 1);
  3482. // Type check the first argument (int for %b, pointer for %D)
  3483. const Expr *Ex = getDataArg(argIndex);
  3484. const analyze_printf::ArgType &AT =
  3485. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  3486. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  3487. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  3488. EmitFormatDiagnostic(
  3489. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  3490. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  3491. << false << Ex->getSourceRange(),
  3492. Ex->getLocStart(), /*IsStringLocation*/false,
  3493. getSpecifierRange(startSpecifier, specifierLen));
  3494. // Type check the second argument (char * for both %b and %D)
  3495. Ex = getDataArg(argIndex + 1);
  3496. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  3497. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  3498. EmitFormatDiagnostic(
  3499. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  3500. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  3501. << false << Ex->getSourceRange(),
  3502. Ex->getLocStart(), /*IsStringLocation*/false,
  3503. getSpecifierRange(startSpecifier, specifierLen));
  3504. return true;
  3505. }
  3506. // Check for using an Objective-C specific conversion specifier
  3507. // in a non-ObjC literal.
  3508. if (!ObjCContext && CS.isObjCArg()) {
  3509. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  3510. specifierLen);
  3511. }
  3512. // Check for invalid use of field width
  3513. if (!FS.hasValidFieldWidth()) {
  3514. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  3515. startSpecifier, specifierLen);
  3516. }
  3517. // Check for invalid use of precision
  3518. if (!FS.hasValidPrecision()) {
  3519. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  3520. startSpecifier, specifierLen);
  3521. }
  3522. // Check each flag does not conflict with any other component.
  3523. if (!FS.hasValidThousandsGroupingPrefix())
  3524. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  3525. if (!FS.hasValidLeadingZeros())
  3526. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  3527. if (!FS.hasValidPlusPrefix())
  3528. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  3529. if (!FS.hasValidSpacePrefix())
  3530. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  3531. if (!FS.hasValidAlternativeForm())
  3532. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  3533. if (!FS.hasValidLeftJustified())
  3534. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  3535. // Check that flags are not ignored by another flag
  3536. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  3537. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  3538. startSpecifier, specifierLen);
  3539. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  3540. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  3541. startSpecifier, specifierLen);
  3542. // Check the length modifier is valid with the given conversion specifier.
  3543. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  3544. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3545. diag::warn_format_nonsensical_length);
  3546. else if (!FS.hasStandardLengthModifier())
  3547. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  3548. else if (!FS.hasStandardLengthConversionCombination())
  3549. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3550. diag::warn_format_non_standard_conversion_spec);
  3551. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  3552. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  3553. // The remaining checks depend on the data arguments.
  3554. if (HasVAListArg)
  3555. return true;
  3556. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  3557. return false;
  3558. const Expr *Arg = getDataArg(argIndex);
  3559. if (!Arg)
  3560. return true;
  3561. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  3562. }
  3563. static bool requiresParensToAddCast(const Expr *E) {
  3564. // FIXME: We should have a general way to reason about operator
  3565. // precedence and whether parens are actually needed here.
  3566. // Take care of a few common cases where they aren't.
  3567. const Expr *Inside = E->IgnoreImpCasts();
  3568. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  3569. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  3570. switch (Inside->getStmtClass()) {
  3571. case Stmt::ArraySubscriptExprClass:
  3572. case Stmt::CallExprClass:
  3573. case Stmt::CharacterLiteralClass:
  3574. case Stmt::CXXBoolLiteralExprClass:
  3575. case Stmt::DeclRefExprClass:
  3576. case Stmt::FloatingLiteralClass:
  3577. case Stmt::IntegerLiteralClass:
  3578. case Stmt::MemberExprClass:
  3579. case Stmt::ObjCArrayLiteralClass:
  3580. case Stmt::ObjCBoolLiteralExprClass:
  3581. case Stmt::ObjCBoxedExprClass:
  3582. case Stmt::ObjCDictionaryLiteralClass:
  3583. case Stmt::ObjCEncodeExprClass:
  3584. case Stmt::ObjCIvarRefExprClass:
  3585. case Stmt::ObjCMessageExprClass:
  3586. case Stmt::ObjCPropertyRefExprClass:
  3587. case Stmt::ObjCStringLiteralClass:
  3588. case Stmt::ObjCSubscriptRefExprClass:
  3589. case Stmt::ParenExprClass:
  3590. case Stmt::StringLiteralClass:
  3591. case Stmt::UnaryOperatorClass:
  3592. return false;
  3593. default:
  3594. return true;
  3595. }
  3596. }
  3597. static std::pair<QualType, StringRef>
  3598. shouldNotPrintDirectly(const ASTContext &Context,
  3599. QualType IntendedTy,
  3600. const Expr *E) {
  3601. // Use a 'while' to peel off layers of typedefs.
  3602. QualType TyTy = IntendedTy;
  3603. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  3604. StringRef Name = UserTy->getDecl()->getName();
  3605. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  3606. .Case("NSInteger", Context.LongTy)
  3607. .Case("NSUInteger", Context.UnsignedLongTy)
  3608. .Case("SInt32", Context.IntTy)
  3609. .Case("UInt32", Context.UnsignedIntTy)
  3610. .Default(QualType());
  3611. if (!CastTy.isNull())
  3612. return std::make_pair(CastTy, Name);
  3613. TyTy = UserTy->desugar();
  3614. }
  3615. // Strip parens if necessary.
  3616. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  3617. return shouldNotPrintDirectly(Context,
  3618. PE->getSubExpr()->getType(),
  3619. PE->getSubExpr());
  3620. // If this is a conditional expression, then its result type is constructed
  3621. // via usual arithmetic conversions and thus there might be no necessary
  3622. // typedef sugar there. Recurse to operands to check for NSInteger &
  3623. // Co. usage condition.
  3624. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  3625. QualType TrueTy, FalseTy;
  3626. StringRef TrueName, FalseName;
  3627. std::tie(TrueTy, TrueName) =
  3628. shouldNotPrintDirectly(Context,
  3629. CO->getTrueExpr()->getType(),
  3630. CO->getTrueExpr());
  3631. std::tie(FalseTy, FalseName) =
  3632. shouldNotPrintDirectly(Context,
  3633. CO->getFalseExpr()->getType(),
  3634. CO->getFalseExpr());
  3635. if (TrueTy == FalseTy)
  3636. return std::make_pair(TrueTy, TrueName);
  3637. else if (TrueTy.isNull())
  3638. return std::make_pair(FalseTy, FalseName);
  3639. else if (FalseTy.isNull())
  3640. return std::make_pair(TrueTy, TrueName);
  3641. }
  3642. return std::make_pair(QualType(), StringRef());
  3643. }
  3644. bool
  3645. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  3646. const char *StartSpecifier,
  3647. unsigned SpecifierLen,
  3648. const Expr *E) {
  3649. using namespace analyze_format_string;
  3650. using namespace analyze_printf;
  3651. // Now type check the data expression that matches the
  3652. // format specifier.
  3653. const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
  3654. ObjCContext);
  3655. if (!AT.isValid())
  3656. return true;
  3657. QualType ExprTy = E->getType();
  3658. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  3659. ExprTy = TET->getUnderlyingExpr()->getType();
  3660. }
  3661. analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
  3662. if (match == analyze_printf::ArgType::Match) {
  3663. return true;
  3664. }
  3665. // Look through argument promotions for our error message's reported type.
  3666. // This includes the integral and floating promotions, but excludes array
  3667. // and function pointer decay; seeing that an argument intended to be a
  3668. // string has type 'char [6]' is probably more confusing than 'char *'.
  3669. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  3670. if (ICE->getCastKind() == CK_IntegralCast ||
  3671. ICE->getCastKind() == CK_FloatingCast) {
  3672. E = ICE->getSubExpr();
  3673. ExprTy = E->getType();
  3674. // Check if we didn't match because of an implicit cast from a 'char'
  3675. // or 'short' to an 'int'. This is done because printf is a varargs
  3676. // function.
  3677. if (ICE->getType() == S.Context.IntTy ||
  3678. ICE->getType() == S.Context.UnsignedIntTy) {
  3679. // All further checking is done on the subexpression.
  3680. if (AT.matchesType(S.Context, ExprTy))
  3681. return true;
  3682. }
  3683. }
  3684. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  3685. // Special case for 'a', which has type 'int' in C.
  3686. // Note, however, that we do /not/ want to treat multibyte constants like
  3687. // 'MooV' as characters! This form is deprecated but still exists.
  3688. if (ExprTy == S.Context.IntTy)
  3689. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  3690. ExprTy = S.Context.CharTy;
  3691. }
  3692. // Look through enums to their underlying type.
  3693. bool IsEnum = false;
  3694. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  3695. ExprTy = EnumTy->getDecl()->getIntegerType();
  3696. IsEnum = true;
  3697. }
  3698. // %C in an Objective-C context prints a unichar, not a wchar_t.
  3699. // If the argument is an integer of some kind, believe the %C and suggest
  3700. // a cast instead of changing the conversion specifier.
  3701. QualType IntendedTy = ExprTy;
  3702. if (ObjCContext &&
  3703. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  3704. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  3705. !ExprTy->isCharType()) {
  3706. // 'unichar' is defined as a typedef of unsigned short, but we should
  3707. // prefer using the typedef if it is visible.
  3708. IntendedTy = S.Context.UnsignedShortTy;
  3709. // While we are here, check if the value is an IntegerLiteral that happens
  3710. // to be within the valid range.
  3711. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  3712. const llvm::APInt &V = IL->getValue();
  3713. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  3714. return true;
  3715. }
  3716. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
  3717. Sema::LookupOrdinaryName);
  3718. if (S.LookupName(Result, S.getCurScope())) {
  3719. NamedDecl *ND = Result.getFoundDecl();
  3720. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  3721. if (TD->getUnderlyingType() == IntendedTy)
  3722. IntendedTy = S.Context.getTypedefType(TD);
  3723. }
  3724. }
  3725. }
  3726. // Special-case some of Darwin's platform-independence types by suggesting
  3727. // casts to primitive types that are known to be large enough.
  3728. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  3729. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  3730. QualType CastTy;
  3731. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  3732. if (!CastTy.isNull()) {
  3733. IntendedTy = CastTy;
  3734. ShouldNotPrintDirectly = true;
  3735. }
  3736. }
  3737. // We may be able to offer a FixItHint if it is a supported type.
  3738. PrintfSpecifier fixedFS = FS;
  3739. bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
  3740. S.Context, ObjCContext);
  3741. if (success) {
  3742. // Get the fix string from the fixed format specifier
  3743. SmallString<16> buf;
  3744. llvm::raw_svector_ostream os(buf);
  3745. fixedFS.toString(os);
  3746. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  3747. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  3748. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  3749. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  3750. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  3751. }
  3752. // In this case, the specifier is wrong and should be changed to match
  3753. // the argument.
  3754. EmitFormatDiagnostic(S.PDiag(diag)
  3755. << AT.getRepresentativeTypeName(S.Context)
  3756. << IntendedTy << IsEnum << E->getSourceRange(),
  3757. E->getLocStart(),
  3758. /*IsStringLocation*/ false, SpecRange,
  3759. FixItHint::CreateReplacement(SpecRange, os.str()));
  3760. } else {
  3761. // The canonical type for formatting this value is different from the
  3762. // actual type of the expression. (This occurs, for example, with Darwin's
  3763. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  3764. // should be printed as 'long' for 64-bit compatibility.)
  3765. // Rather than emitting a normal format/argument mismatch, we want to
  3766. // add a cast to the recommended type (and correct the format string
  3767. // if necessary).
  3768. SmallString<16> CastBuf;
  3769. llvm::raw_svector_ostream CastFix(CastBuf);
  3770. CastFix << "(";
  3771. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  3772. CastFix << ")";
  3773. SmallVector<FixItHint,4> Hints;
  3774. if (!AT.matchesType(S.Context, IntendedTy))
  3775. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  3776. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  3777. // If there's already a cast present, just replace it.
  3778. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  3779. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  3780. } else if (!requiresParensToAddCast(E)) {
  3781. // If the expression has high enough precedence,
  3782. // just write the C-style cast.
  3783. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  3784. CastFix.str()));
  3785. } else {
  3786. // Otherwise, add parens around the expression as well as the cast.
  3787. CastFix << "(";
  3788. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  3789. CastFix.str()));
  3790. SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
  3791. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  3792. }
  3793. if (ShouldNotPrintDirectly) {
  3794. // The expression has a type that should not be printed directly.
  3795. // We extract the name from the typedef because we don't want to show
  3796. // the underlying type in the diagnostic.
  3797. StringRef Name;
  3798. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  3799. Name = TypedefTy->getDecl()->getName();
  3800. else
  3801. Name = CastTyName;
  3802. EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
  3803. << Name << IntendedTy << IsEnum
  3804. << E->getSourceRange(),
  3805. E->getLocStart(), /*IsStringLocation=*/false,
  3806. SpecRange, Hints);
  3807. } else {
  3808. // In this case, the expression could be printed using a different
  3809. // specifier, but we've decided that the specifier is probably correct
  3810. // and we should cast instead. Just use the normal warning message.
  3811. EmitFormatDiagnostic(
  3812. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  3813. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  3814. << E->getSourceRange(),
  3815. E->getLocStart(), /*IsStringLocation*/false,
  3816. SpecRange, Hints);
  3817. }
  3818. }
  3819. } else {
  3820. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  3821. SpecifierLen);
  3822. // Since the warning for passing non-POD types to variadic functions
  3823. // was deferred until now, we emit a warning for non-POD
  3824. // arguments here.
  3825. switch (S.isValidVarArgType(ExprTy)) {
  3826. case Sema::VAK_Valid:
  3827. case Sema::VAK_ValidInCXX11: {
  3828. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  3829. if (match == analyze_printf::ArgType::NoMatchPedantic) {
  3830. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  3831. }
  3832. EmitFormatDiagnostic(
  3833. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  3834. << IsEnum << CSR << E->getSourceRange(),
  3835. E->getLocStart(), /*IsStringLocation*/ false, CSR);
  3836. break;
  3837. }
  3838. case Sema::VAK_Undefined:
  3839. case Sema::VAK_MSVCUndefined:
  3840. EmitFormatDiagnostic(
  3841. S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  3842. << S.getLangOpts().CPlusPlus11
  3843. << ExprTy
  3844. << CallType
  3845. << AT.getRepresentativeTypeName(S.Context)
  3846. << CSR
  3847. << E->getSourceRange(),
  3848. E->getLocStart(), /*IsStringLocation*/false, CSR);
  3849. checkForCStrMembers(AT, E);
  3850. break;
  3851. case Sema::VAK_Invalid:
  3852. if (ExprTy->isObjCObjectType())
  3853. EmitFormatDiagnostic(
  3854. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  3855. << S.getLangOpts().CPlusPlus11
  3856. << ExprTy
  3857. << CallType
  3858. << AT.getRepresentativeTypeName(S.Context)
  3859. << CSR
  3860. << E->getSourceRange(),
  3861. E->getLocStart(), /*IsStringLocation*/false, CSR);
  3862. else
  3863. // FIXME: If this is an initializer list, suggest removing the braces
  3864. // or inserting a cast to the target type.
  3865. S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
  3866. << isa<InitListExpr>(E) << ExprTy << CallType
  3867. << AT.getRepresentativeTypeName(S.Context)
  3868. << E->getSourceRange();
  3869. break;
  3870. }
  3871. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  3872. "format string specifier index out of range");
  3873. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  3874. }
  3875. return true;
  3876. }
  3877. //===--- CHECK: Scanf format string checking ------------------------------===//
  3878. namespace {
  3879. class CheckScanfHandler : public CheckFormatHandler {
  3880. public:
  3881. CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
  3882. const Expr *origFormatExpr, unsigned firstDataArg,
  3883. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  3884. ArrayRef<const Expr *> Args,
  3885. unsigned formatIdx, bool inFunctionCall,
  3886. Sema::VariadicCallType CallType,
  3887. llvm::SmallBitVector &CheckedVarArgs)
  3888. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  3889. numDataArgs, beg, hasVAListArg,
  3890. Args, formatIdx, inFunctionCall, CallType,
  3891. CheckedVarArgs)
  3892. {}
  3893. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  3894. const char *startSpecifier,
  3895. unsigned specifierLen) override;
  3896. bool HandleInvalidScanfConversionSpecifier(
  3897. const analyze_scanf::ScanfSpecifier &FS,
  3898. const char *startSpecifier,
  3899. unsigned specifierLen) override;
  3900. void HandleIncompleteScanList(const char *start, const char *end) override;
  3901. };
  3902. }
  3903. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  3904. const char *end) {
  3905. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  3906. getLocationOfByte(end), /*IsStringLocation*/true,
  3907. getSpecifierRange(start, end - start));
  3908. }
  3909. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  3910. const analyze_scanf::ScanfSpecifier &FS,
  3911. const char *startSpecifier,
  3912. unsigned specifierLen) {
  3913. const analyze_scanf::ScanfConversionSpecifier &CS =
  3914. FS.getConversionSpecifier();
  3915. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  3916. getLocationOfByte(CS.getStart()),
  3917. startSpecifier, specifierLen,
  3918. CS.getStart(), CS.getLength());
  3919. }
  3920. bool CheckScanfHandler::HandleScanfSpecifier(
  3921. const analyze_scanf::ScanfSpecifier &FS,
  3922. const char *startSpecifier,
  3923. unsigned specifierLen) {
  3924. using namespace analyze_scanf;
  3925. using namespace analyze_format_string;
  3926. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  3927. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  3928. // be used to decide if we are using positional arguments consistently.
  3929. if (FS.consumesDataArgument()) {
  3930. if (atFirstArg) {
  3931. atFirstArg = false;
  3932. usesPositionalArgs = FS.usesPositionalArg();
  3933. }
  3934. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  3935. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  3936. startSpecifier, specifierLen);
  3937. return false;
  3938. }
  3939. }
  3940. // Check if the field with is non-zero.
  3941. const OptionalAmount &Amt = FS.getFieldWidth();
  3942. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  3943. if (Amt.getConstantAmount() == 0) {
  3944. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  3945. Amt.getConstantLength());
  3946. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  3947. getLocationOfByte(Amt.getStart()),
  3948. /*IsStringLocation*/true, R,
  3949. FixItHint::CreateRemoval(R));
  3950. }
  3951. }
  3952. if (!FS.consumesDataArgument()) {
  3953. // FIXME: Technically specifying a precision or field width here
  3954. // makes no sense. Worth issuing a warning at some point.
  3955. return true;
  3956. }
  3957. // Consume the argument.
  3958. unsigned argIndex = FS.getArgIndex();
  3959. if (argIndex < NumDataArgs) {
  3960. // The check to see if the argIndex is valid will come later.
  3961. // We set the bit here because we may exit early from this
  3962. // function if we encounter some other error.
  3963. CoveredArgs.set(argIndex);
  3964. }
  3965. // Check the length modifier is valid with the given conversion specifier.
  3966. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  3967. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3968. diag::warn_format_nonsensical_length);
  3969. else if (!FS.hasStandardLengthModifier())
  3970. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  3971. else if (!FS.hasStandardLengthConversionCombination())
  3972. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3973. diag::warn_format_non_standard_conversion_spec);
  3974. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  3975. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  3976. // The remaining checks depend on the data arguments.
  3977. if (HasVAListArg)
  3978. return true;
  3979. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  3980. return false;
  3981. // Check that the argument type matches the format specifier.
  3982. const Expr *Ex = getDataArg(argIndex);
  3983. if (!Ex)
  3984. return true;
  3985. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  3986. if (!AT.isValid()) {
  3987. return true;
  3988. }
  3989. analyze_format_string::ArgType::MatchKind match =
  3990. AT.matchesType(S.Context, Ex->getType());
  3991. if (match == analyze_format_string::ArgType::Match) {
  3992. return true;
  3993. }
  3994. ScanfSpecifier fixedFS = FS;
  3995. bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  3996. S.getLangOpts(), S.Context);
  3997. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  3998. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  3999. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  4000. }
  4001. if (success) {
  4002. // Get the fix string from the fixed format specifier.
  4003. SmallString<128> buf;
  4004. llvm::raw_svector_ostream os(buf);
  4005. fixedFS.toString(os);
  4006. EmitFormatDiagnostic(
  4007. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
  4008. << Ex->getType() << false << Ex->getSourceRange(),
  4009. Ex->getLocStart(),
  4010. /*IsStringLocation*/ false,
  4011. getSpecifierRange(startSpecifier, specifierLen),
  4012. FixItHint::CreateReplacement(
  4013. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  4014. } else {
  4015. EmitFormatDiagnostic(S.PDiag(diag)
  4016. << AT.getRepresentativeTypeName(S.Context)
  4017. << Ex->getType() << false << Ex->getSourceRange(),
  4018. Ex->getLocStart(),
  4019. /*IsStringLocation*/ false,
  4020. getSpecifierRange(startSpecifier, specifierLen));
  4021. }
  4022. return true;
  4023. }
  4024. void Sema::CheckFormatString(const StringLiteral *FExpr,
  4025. const Expr *OrigFormatExpr,
  4026. ArrayRef<const Expr *> Args,
  4027. bool HasVAListArg, unsigned format_idx,
  4028. unsigned firstDataArg, FormatStringType Type,
  4029. bool inFunctionCall, VariadicCallType CallType,
  4030. llvm::SmallBitVector &CheckedVarArgs) {
  4031. // CHECK: is the format string a wide literal?
  4032. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  4033. CheckFormatHandler::EmitFormatDiagnostic(
  4034. *this, inFunctionCall, Args[format_idx],
  4035. PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  4036. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  4037. return;
  4038. }
  4039. // Str - The format string. NOTE: this is NOT null-terminated!
  4040. StringRef StrRef = FExpr->getString();
  4041. const char *Str = StrRef.data();
  4042. // Account for cases where the string literal is truncated in a declaration.
  4043. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  4044. assert(T && "String literal not of constant array type!");
  4045. size_t TypeSize = T->getSize().getZExtValue();
  4046. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  4047. const unsigned numDataArgs = Args.size() - firstDataArg;
  4048. // Emit a warning if the string literal is truncated and does not contain an
  4049. // embedded null character.
  4050. if (TypeSize <= StrRef.size() &&
  4051. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  4052. CheckFormatHandler::EmitFormatDiagnostic(
  4053. *this, inFunctionCall, Args[format_idx],
  4054. PDiag(diag::warn_printf_format_string_not_null_terminated),
  4055. FExpr->getLocStart(),
  4056. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  4057. return;
  4058. }
  4059. // CHECK: empty format string?
  4060. if (StrLen == 0 && numDataArgs > 0) {
  4061. CheckFormatHandler::EmitFormatDiagnostic(
  4062. *this, inFunctionCall, Args[format_idx],
  4063. PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  4064. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  4065. return;
  4066. }
  4067. if (Type == FST_Printf || Type == FST_NSString ||
  4068. Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
  4069. CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
  4070. numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
  4071. Str, HasVAListArg, Args, format_idx,
  4072. inFunctionCall, CallType, CheckedVarArgs);
  4073. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  4074. getLangOpts(),
  4075. Context.getTargetInfo(),
  4076. Type == FST_FreeBSDKPrintf))
  4077. H.DoneProcessing();
  4078. } else if (Type == FST_Scanf) {
  4079. CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
  4080. Str, HasVAListArg, Args, format_idx,
  4081. inFunctionCall, CallType, CheckedVarArgs);
  4082. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  4083. getLangOpts(),
  4084. Context.getTargetInfo()))
  4085. H.DoneProcessing();
  4086. } // TODO: handle other formats
  4087. }
  4088. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  4089. // Str - The format string. NOTE: this is NOT null-terminated!
  4090. StringRef StrRef = FExpr->getString();
  4091. const char *Str = StrRef.data();
  4092. // Account for cases where the string literal is truncated in a declaration.
  4093. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  4094. assert(T && "String literal not of constant array type!");
  4095. size_t TypeSize = T->getSize().getZExtValue();
  4096. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  4097. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  4098. getLangOpts(),
  4099. Context.getTargetInfo());
  4100. }
  4101. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  4102. // Returns the related absolute value function that is larger, of 0 if one
  4103. // does not exist.
  4104. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  4105. switch (AbsFunction) {
  4106. default:
  4107. return 0;
  4108. case Builtin::BI__builtin_abs:
  4109. return Builtin::BI__builtin_labs;
  4110. case Builtin::BI__builtin_labs:
  4111. return Builtin::BI__builtin_llabs;
  4112. case Builtin::BI__builtin_llabs:
  4113. return 0;
  4114. case Builtin::BI__builtin_fabsf:
  4115. return Builtin::BI__builtin_fabs;
  4116. case Builtin::BI__builtin_fabs:
  4117. return Builtin::BI__builtin_fabsl;
  4118. case Builtin::BI__builtin_fabsl:
  4119. return 0;
  4120. case Builtin::BI__builtin_cabsf:
  4121. return Builtin::BI__builtin_cabs;
  4122. case Builtin::BI__builtin_cabs:
  4123. return Builtin::BI__builtin_cabsl;
  4124. case Builtin::BI__builtin_cabsl:
  4125. return 0;
  4126. case Builtin::BIabs:
  4127. return Builtin::BIlabs;
  4128. case Builtin::BIlabs:
  4129. return Builtin::BIllabs;
  4130. case Builtin::BIllabs:
  4131. return 0;
  4132. case Builtin::BIfabsf:
  4133. return Builtin::BIfabs;
  4134. case Builtin::BIfabs:
  4135. return Builtin::BIfabsl;
  4136. case Builtin::BIfabsl:
  4137. return 0;
  4138. case Builtin::BIcabsf:
  4139. return Builtin::BIcabs;
  4140. case Builtin::BIcabs:
  4141. return Builtin::BIcabsl;
  4142. case Builtin::BIcabsl:
  4143. return 0;
  4144. }
  4145. }
  4146. // Returns the argument type of the absolute value function.
  4147. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  4148. unsigned AbsType) {
  4149. if (AbsType == 0)
  4150. return QualType();
  4151. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  4152. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  4153. if (Error != ASTContext::GE_None)
  4154. return QualType();
  4155. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  4156. if (!FT)
  4157. return QualType();
  4158. if (FT->getNumParams() != 1)
  4159. return QualType();
  4160. return FT->getParamType(0);
  4161. }
  4162. // Returns the best absolute value function, or zero, based on type and
  4163. // current absolute value function.
  4164. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  4165. unsigned AbsFunctionKind) {
  4166. unsigned BestKind = 0;
  4167. uint64_t ArgSize = Context.getTypeSize(ArgType);
  4168. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  4169. Kind = getLargerAbsoluteValueFunction(Kind)) {
  4170. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  4171. if (Context.getTypeSize(ParamType) >= ArgSize) {
  4172. if (BestKind == 0)
  4173. BestKind = Kind;
  4174. else if (Context.hasSameType(ParamType, ArgType)) {
  4175. BestKind = Kind;
  4176. break;
  4177. }
  4178. }
  4179. }
  4180. return BestKind;
  4181. }
  4182. enum AbsoluteValueKind {
  4183. AVK_Integer,
  4184. AVK_Floating,
  4185. AVK_Complex
  4186. };
  4187. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  4188. if (T->isIntegralOrEnumerationType())
  4189. return AVK_Integer;
  4190. if (T->isRealFloatingType())
  4191. return AVK_Floating;
  4192. if (T->isAnyComplexType())
  4193. return AVK_Complex;
  4194. llvm_unreachable("Type not integer, floating, or complex");
  4195. }
  4196. // Changes the absolute value function to a different type. Preserves whether
  4197. // the function is a builtin.
  4198. static unsigned changeAbsFunction(unsigned AbsKind,
  4199. AbsoluteValueKind ValueKind) {
  4200. switch (ValueKind) {
  4201. case AVK_Integer:
  4202. switch (AbsKind) {
  4203. default:
  4204. return 0;
  4205. case Builtin::BI__builtin_fabsf:
  4206. case Builtin::BI__builtin_fabs:
  4207. case Builtin::BI__builtin_fabsl:
  4208. case Builtin::BI__builtin_cabsf:
  4209. case Builtin::BI__builtin_cabs:
  4210. case Builtin::BI__builtin_cabsl:
  4211. return Builtin::BI__builtin_abs;
  4212. case Builtin::BIfabsf:
  4213. case Builtin::BIfabs:
  4214. case Builtin::BIfabsl:
  4215. case Builtin::BIcabsf:
  4216. case Builtin::BIcabs:
  4217. case Builtin::BIcabsl:
  4218. return Builtin::BIabs;
  4219. }
  4220. case AVK_Floating:
  4221. switch (AbsKind) {
  4222. default:
  4223. return 0;
  4224. case Builtin::BI__builtin_abs:
  4225. case Builtin::BI__builtin_labs:
  4226. case Builtin::BI__builtin_llabs:
  4227. case Builtin::BI__builtin_cabsf:
  4228. case Builtin::BI__builtin_cabs:
  4229. case Builtin::BI__builtin_cabsl:
  4230. return Builtin::BI__builtin_fabsf;
  4231. case Builtin::BIabs:
  4232. case Builtin::BIlabs:
  4233. case Builtin::BIllabs:
  4234. case Builtin::BIcabsf:
  4235. case Builtin::BIcabs:
  4236. case Builtin::BIcabsl:
  4237. return Builtin::BIfabsf;
  4238. }
  4239. case AVK_Complex:
  4240. switch (AbsKind) {
  4241. default:
  4242. return 0;
  4243. case Builtin::BI__builtin_abs:
  4244. case Builtin::BI__builtin_labs:
  4245. case Builtin::BI__builtin_llabs:
  4246. case Builtin::BI__builtin_fabsf:
  4247. case Builtin::BI__builtin_fabs:
  4248. case Builtin::BI__builtin_fabsl:
  4249. return Builtin::BI__builtin_cabsf;
  4250. case Builtin::BIabs:
  4251. case Builtin::BIlabs:
  4252. case Builtin::BIllabs:
  4253. case Builtin::BIfabsf:
  4254. case Builtin::BIfabs:
  4255. case Builtin::BIfabsl:
  4256. return Builtin::BIcabsf;
  4257. }
  4258. }
  4259. llvm_unreachable("Unable to convert function");
  4260. }
  4261. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  4262. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  4263. if (!FnInfo)
  4264. return 0;
  4265. switch (FDecl->getBuiltinID()) {
  4266. default:
  4267. return 0;
  4268. case Builtin::BI__builtin_abs:
  4269. case Builtin::BI__builtin_fabs:
  4270. case Builtin::BI__builtin_fabsf:
  4271. case Builtin::BI__builtin_fabsl:
  4272. case Builtin::BI__builtin_labs:
  4273. case Builtin::BI__builtin_llabs:
  4274. case Builtin::BI__builtin_cabs:
  4275. case Builtin::BI__builtin_cabsf:
  4276. case Builtin::BI__builtin_cabsl:
  4277. case Builtin::BIabs:
  4278. case Builtin::BIlabs:
  4279. case Builtin::BIllabs:
  4280. case Builtin::BIfabs:
  4281. case Builtin::BIfabsf:
  4282. case Builtin::BIfabsl:
  4283. case Builtin::BIcabs:
  4284. case Builtin::BIcabsf:
  4285. case Builtin::BIcabsl:
  4286. return FDecl->getBuiltinID();
  4287. }
  4288. llvm_unreachable("Unknown Builtin type");
  4289. }
  4290. // If the replacement is valid, emit a note with replacement function.
  4291. // Additionally, suggest including the proper header if not already included.
  4292. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  4293. unsigned AbsKind, QualType ArgType) {
  4294. bool EmitHeaderHint = true;
  4295. const char *HeaderName = nullptr;
  4296. const char *FunctionName = nullptr;
  4297. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  4298. FunctionName = "std::abs";
  4299. if (ArgType->isIntegralOrEnumerationType()) {
  4300. HeaderName = "cstdlib";
  4301. } else if (ArgType->isRealFloatingType()) {
  4302. HeaderName = "cmath";
  4303. } else {
  4304. llvm_unreachable("Invalid Type");
  4305. }
  4306. // Lookup all std::abs
  4307. if (NamespaceDecl *Std = S.getStdNamespace()) {
  4308. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  4309. R.suppressDiagnostics();
  4310. S.LookupQualifiedName(R, Std);
  4311. for (const auto *I : R) {
  4312. const FunctionDecl *FDecl = nullptr;
  4313. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  4314. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  4315. } else {
  4316. FDecl = dyn_cast<FunctionDecl>(I);
  4317. }
  4318. if (!FDecl)
  4319. continue;
  4320. // Found std::abs(), check that they are the right ones.
  4321. if (FDecl->getNumParams() != 1)
  4322. continue;
  4323. // Check that the parameter type can handle the argument.
  4324. QualType ParamType = FDecl->getParamDecl(0)->getType();
  4325. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  4326. S.Context.getTypeSize(ArgType) <=
  4327. S.Context.getTypeSize(ParamType)) {
  4328. // Found a function, don't need the header hint.
  4329. EmitHeaderHint = false;
  4330. break;
  4331. }
  4332. }
  4333. }
  4334. } else {
  4335. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  4336. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  4337. if (HeaderName) {
  4338. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  4339. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  4340. R.suppressDiagnostics();
  4341. S.LookupName(R, S.getCurScope());
  4342. if (R.isSingleResult()) {
  4343. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  4344. if (FD && FD->getBuiltinID() == AbsKind) {
  4345. EmitHeaderHint = false;
  4346. } else {
  4347. return;
  4348. }
  4349. } else if (!R.empty()) {
  4350. return;
  4351. }
  4352. }
  4353. }
  4354. S.Diag(Loc, diag::note_replace_abs_function)
  4355. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  4356. if (!HeaderName)
  4357. return;
  4358. if (!EmitHeaderHint)
  4359. return;
  4360. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  4361. << FunctionName;
  4362. }
  4363. static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
  4364. if (!FDecl)
  4365. return false;
  4366. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
  4367. return false;
  4368. const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
  4369. while (ND && ND->isInlineNamespace()) {
  4370. ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
  4371. }
  4372. if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
  4373. return false;
  4374. if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
  4375. return false;
  4376. return true;
  4377. }
  4378. // Warn when using the wrong abs() function.
  4379. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  4380. const FunctionDecl *FDecl,
  4381. IdentifierInfo *FnInfo) {
  4382. if (Call->getNumArgs() != 1)
  4383. return;
  4384. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  4385. bool IsStdAbs = IsFunctionStdAbs(FDecl);
  4386. if (AbsKind == 0 && !IsStdAbs)
  4387. return;
  4388. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  4389. QualType ParamType = Call->getArg(0)->getType();
  4390. // Unsigned types cannot be negative. Suggest removing the absolute value
  4391. // function call.
  4392. if (ArgType->isUnsignedIntegerType()) {
  4393. const char *FunctionName =
  4394. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  4395. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  4396. Diag(Call->getExprLoc(), diag::note_remove_abs)
  4397. << FunctionName
  4398. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  4399. return;
  4400. }
  4401. // std::abs has overloads which prevent most of the absolute value problems
  4402. // from occurring.
  4403. if (IsStdAbs)
  4404. return;
  4405. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  4406. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  4407. // The argument and parameter are the same kind. Check if they are the right
  4408. // size.
  4409. if (ArgValueKind == ParamValueKind) {
  4410. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  4411. return;
  4412. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  4413. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  4414. << FDecl << ArgType << ParamType;
  4415. if (NewAbsKind == 0)
  4416. return;
  4417. emitReplacement(*this, Call->getExprLoc(),
  4418. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  4419. return;
  4420. }
  4421. // ArgValueKind != ParamValueKind
  4422. // The wrong type of absolute value function was used. Attempt to find the
  4423. // proper one.
  4424. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  4425. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  4426. if (NewAbsKind == 0)
  4427. return;
  4428. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  4429. << FDecl << ParamValueKind << ArgValueKind;
  4430. emitReplacement(*this, Call->getExprLoc(),
  4431. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  4432. return;
  4433. }
  4434. //===--- CHECK: Standard memory functions ---------------------------------===//
  4435. /// \brief Takes the expression passed to the size_t parameter of functions
  4436. /// such as memcmp, strncat, etc and warns if it's a comparison.
  4437. ///
  4438. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  4439. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  4440. IdentifierInfo *FnName,
  4441. SourceLocation FnLoc,
  4442. SourceLocation RParenLoc) {
  4443. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  4444. if (!Size)
  4445. return false;
  4446. // if E is binop and op is >, <, >=, <=, ==, &&, ||:
  4447. if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
  4448. return false;
  4449. SourceRange SizeRange = Size->getSourceRange();
  4450. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  4451. << SizeRange << FnName;
  4452. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  4453. << FnName << FixItHint::CreateInsertion(
  4454. S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
  4455. << FixItHint::CreateRemoval(RParenLoc);
  4456. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  4457. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  4458. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  4459. ")");
  4460. return true;
  4461. }
  4462. /// \brief Determine whether the given type is or contains a dynamic class type
  4463. /// (e.g., whether it has a vtable).
  4464. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  4465. bool &IsContained) {
  4466. // Look through array types while ignoring qualifiers.
  4467. const Type *Ty = T->getBaseElementTypeUnsafe();
  4468. IsContained = false;
  4469. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  4470. RD = RD ? RD->getDefinition() : nullptr;
  4471. if (!RD)
  4472. return nullptr;
  4473. if (RD->isDynamicClass())
  4474. return RD;
  4475. // Check all the fields. If any bases were dynamic, the class is dynamic.
  4476. // It's impossible for a class to transitively contain itself by value, so
  4477. // infinite recursion is impossible.
  4478. for (auto *FD : RD->fields()) {
  4479. bool SubContained;
  4480. if (const CXXRecordDecl *ContainedRD =
  4481. getContainedDynamicClass(FD->getType(), SubContained)) {
  4482. IsContained = true;
  4483. return ContainedRD;
  4484. }
  4485. }
  4486. return nullptr;
  4487. }
  4488. /// \brief If E is a sizeof expression, returns its argument expression,
  4489. /// otherwise returns NULL.
  4490. static const Expr *getSizeOfExprArg(const Expr *E) {
  4491. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  4492. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  4493. if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
  4494. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  4495. return nullptr;
  4496. }
  4497. /// \brief If E is a sizeof expression, returns its argument type.
  4498. static QualType getSizeOfArgType(const Expr *E) {
  4499. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  4500. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  4501. if (SizeOf->getKind() == clang::UETT_SizeOf)
  4502. return SizeOf->getTypeOfArgument();
  4503. return QualType();
  4504. }
  4505. /// \brief Check for dangerous or invalid arguments to memset().
  4506. ///
  4507. /// This issues warnings on known problematic, dangerous or unspecified
  4508. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  4509. /// function calls.
  4510. ///
  4511. /// \param Call The call expression to diagnose.
  4512. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  4513. unsigned BId,
  4514. IdentifierInfo *FnName) {
  4515. assert(BId != 0);
  4516. // It is possible to have a non-standard definition of memset. Validate
  4517. // we have enough arguments, and if not, abort further checking.
  4518. unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
  4519. if (Call->getNumArgs() < ExpectedNumArgs)
  4520. return;
  4521. unsigned LastArg = (BId == Builtin::BImemset ||
  4522. BId == Builtin::BIstrndup ? 1 : 2);
  4523. unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
  4524. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  4525. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  4526. Call->getLocStart(), Call->getRParenLoc()))
  4527. return;
  4528. // We have special checking when the length is a sizeof expression.
  4529. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  4530. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  4531. llvm::FoldingSetNodeID SizeOfArgID;
  4532. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  4533. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  4534. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  4535. QualType DestTy = Dest->getType();
  4536. QualType PointeeTy;
  4537. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  4538. PointeeTy = DestPtrTy->getPointeeType();
  4539. // Never warn about void type pointers. This can be used to suppress
  4540. // false positives.
  4541. if (PointeeTy->isVoidType())
  4542. continue;
  4543. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  4544. // actually comparing the expressions for equality. Because computing the
  4545. // expression IDs can be expensive, we only do this if the diagnostic is
  4546. // enabled.
  4547. if (SizeOfArg &&
  4548. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  4549. SizeOfArg->getExprLoc())) {
  4550. // We only compute IDs for expressions if the warning is enabled, and
  4551. // cache the sizeof arg's ID.
  4552. if (SizeOfArgID == llvm::FoldingSetNodeID())
  4553. SizeOfArg->Profile(SizeOfArgID, Context, true);
  4554. llvm::FoldingSetNodeID DestID;
  4555. Dest->Profile(DestID, Context, true);
  4556. if (DestID == SizeOfArgID) {
  4557. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  4558. // over sizeof(src) as well.
  4559. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  4560. StringRef ReadableName = FnName->getName();
  4561. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  4562. if (UnaryOp->getOpcode() == UO_AddrOf)
  4563. ActionIdx = 1; // If its an address-of operator, just remove it.
  4564. if (!PointeeTy->isIncompleteType() &&
  4565. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  4566. ActionIdx = 2; // If the pointee's size is sizeof(char),
  4567. // suggest an explicit length.
  4568. // If the function is defined as a builtin macro, do not show macro
  4569. // expansion.
  4570. SourceLocation SL = SizeOfArg->getExprLoc();
  4571. SourceRange DSR = Dest->getSourceRange();
  4572. SourceRange SSR = SizeOfArg->getSourceRange();
  4573. SourceManager &SM = getSourceManager();
  4574. if (SM.isMacroArgExpansion(SL)) {
  4575. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  4576. SL = SM.getSpellingLoc(SL);
  4577. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  4578. SM.getSpellingLoc(DSR.getEnd()));
  4579. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  4580. SM.getSpellingLoc(SSR.getEnd()));
  4581. }
  4582. DiagRuntimeBehavior(SL, SizeOfArg,
  4583. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  4584. << ReadableName
  4585. << PointeeTy
  4586. << DestTy
  4587. << DSR
  4588. << SSR);
  4589. DiagRuntimeBehavior(SL, SizeOfArg,
  4590. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  4591. << ActionIdx
  4592. << SSR);
  4593. break;
  4594. }
  4595. }
  4596. // Also check for cases where the sizeof argument is the exact same
  4597. // type as the memory argument, and where it points to a user-defined
  4598. // record type.
  4599. if (SizeOfArgTy != QualType()) {
  4600. if (PointeeTy->isRecordType() &&
  4601. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  4602. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  4603. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  4604. << FnName << SizeOfArgTy << ArgIdx
  4605. << PointeeTy << Dest->getSourceRange()
  4606. << LenExpr->getSourceRange());
  4607. break;
  4608. }
  4609. }
  4610. } else if (DestTy->isArrayType()) {
  4611. PointeeTy = DestTy;
  4612. }
  4613. if (PointeeTy == QualType())
  4614. continue;
  4615. // Always complain about dynamic classes.
  4616. bool IsContained;
  4617. if (const CXXRecordDecl *ContainedRD =
  4618. getContainedDynamicClass(PointeeTy, IsContained)) {
  4619. unsigned OperationType = 0;
  4620. // "overwritten" if we're warning about the destination for any call
  4621. // but memcmp; otherwise a verb appropriate to the call.
  4622. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  4623. if (BId == Builtin::BImemcpy)
  4624. OperationType = 1;
  4625. else if(BId == Builtin::BImemmove)
  4626. OperationType = 2;
  4627. else if (BId == Builtin::BImemcmp)
  4628. OperationType = 3;
  4629. }
  4630. DiagRuntimeBehavior(
  4631. Dest->getExprLoc(), Dest,
  4632. PDiag(diag::warn_dyn_class_memaccess)
  4633. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  4634. << FnName << IsContained << ContainedRD << OperationType
  4635. << Call->getCallee()->getSourceRange());
  4636. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  4637. BId != Builtin::BImemset)
  4638. DiagRuntimeBehavior(
  4639. Dest->getExprLoc(), Dest,
  4640. PDiag(diag::warn_arc_object_memaccess)
  4641. << ArgIdx << FnName << PointeeTy
  4642. << Call->getCallee()->getSourceRange());
  4643. else
  4644. continue;
  4645. DiagRuntimeBehavior(
  4646. Dest->getExprLoc(), Dest,
  4647. PDiag(diag::note_bad_memaccess_silence)
  4648. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  4649. break;
  4650. }
  4651. }
  4652. // A little helper routine: ignore addition and subtraction of integer literals.
  4653. // This intentionally does not ignore all integer constant expressions because
  4654. // we don't want to remove sizeof().
  4655. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  4656. Ex = Ex->IgnoreParenCasts();
  4657. for (;;) {
  4658. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  4659. if (!BO || !BO->isAdditiveOp())
  4660. break;
  4661. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  4662. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  4663. if (isa<IntegerLiteral>(RHS))
  4664. Ex = LHS;
  4665. else if (isa<IntegerLiteral>(LHS))
  4666. Ex = RHS;
  4667. else
  4668. break;
  4669. }
  4670. return Ex;
  4671. }
  4672. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  4673. ASTContext &Context) {
  4674. // Only handle constant-sized or VLAs, but not flexible members.
  4675. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  4676. // Only issue the FIXIT for arrays of size > 1.
  4677. if (CAT->getSize().getSExtValue() <= 1)
  4678. return false;
  4679. } else if (!Ty->isVariableArrayType()) {
  4680. return false;
  4681. }
  4682. return true;
  4683. }
  4684. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  4685. // be the size of the source, instead of the destination.
  4686. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  4687. IdentifierInfo *FnName) {
  4688. // Don't crash if the user has the wrong number of arguments
  4689. unsigned NumArgs = Call->getNumArgs();
  4690. if ((NumArgs != 3) && (NumArgs != 4))
  4691. return;
  4692. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  4693. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  4694. const Expr *CompareWithSrc = nullptr;
  4695. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  4696. Call->getLocStart(), Call->getRParenLoc()))
  4697. return;
  4698. // Look for 'strlcpy(dst, x, sizeof(x))'
  4699. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  4700. CompareWithSrc = Ex;
  4701. else {
  4702. // Look for 'strlcpy(dst, x, strlen(x))'
  4703. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  4704. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  4705. SizeCall->getNumArgs() == 1)
  4706. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  4707. }
  4708. }
  4709. if (!CompareWithSrc)
  4710. return;
  4711. // Determine if the argument to sizeof/strlen is equal to the source
  4712. // argument. In principle there's all kinds of things you could do
  4713. // here, for instance creating an == expression and evaluating it with
  4714. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  4715. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  4716. if (!SrcArgDRE)
  4717. return;
  4718. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  4719. if (!CompareWithSrcDRE ||
  4720. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  4721. return;
  4722. const Expr *OriginalSizeArg = Call->getArg(2);
  4723. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  4724. << OriginalSizeArg->getSourceRange() << FnName;
  4725. // Output a FIXIT hint if the destination is an array (rather than a
  4726. // pointer to an array). This could be enhanced to handle some
  4727. // pointers if we know the actual size, like if DstArg is 'array+2'
  4728. // we could say 'sizeof(array)-2'.
  4729. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  4730. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  4731. return;
  4732. SmallString<128> sizeString;
  4733. llvm::raw_svector_ostream OS(sizeString);
  4734. OS << "sizeof(";
  4735. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  4736. OS << ")";
  4737. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  4738. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  4739. OS.str());
  4740. }
  4741. /// Check if two expressions refer to the same declaration.
  4742. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  4743. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  4744. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  4745. return D1->getDecl() == D2->getDecl();
  4746. return false;
  4747. }
  4748. static const Expr *getStrlenExprArg(const Expr *E) {
  4749. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  4750. const FunctionDecl *FD = CE->getDirectCallee();
  4751. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  4752. return nullptr;
  4753. return CE->getArg(0)->IgnoreParenCasts();
  4754. }
  4755. return nullptr;
  4756. }
  4757. // Warn on anti-patterns as the 'size' argument to strncat.
  4758. // The correct size argument should look like following:
  4759. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  4760. void Sema::CheckStrncatArguments(const CallExpr *CE,
  4761. IdentifierInfo *FnName) {
  4762. // Don't crash if the user has the wrong number of arguments.
  4763. if (CE->getNumArgs() < 3)
  4764. return;
  4765. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  4766. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  4767. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  4768. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
  4769. CE->getRParenLoc()))
  4770. return;
  4771. // Identify common expressions, which are wrongly used as the size argument
  4772. // to strncat and may lead to buffer overflows.
  4773. unsigned PatternType = 0;
  4774. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  4775. // - sizeof(dst)
  4776. if (referToTheSameDecl(SizeOfArg, DstArg))
  4777. PatternType = 1;
  4778. // - sizeof(src)
  4779. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  4780. PatternType = 2;
  4781. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  4782. if (BE->getOpcode() == BO_Sub) {
  4783. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  4784. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  4785. // - sizeof(dst) - strlen(dst)
  4786. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  4787. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  4788. PatternType = 1;
  4789. // - sizeof(src) - (anything)
  4790. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  4791. PatternType = 2;
  4792. }
  4793. }
  4794. if (PatternType == 0)
  4795. return;
  4796. // Generate the diagnostic.
  4797. SourceLocation SL = LenArg->getLocStart();
  4798. SourceRange SR = LenArg->getSourceRange();
  4799. SourceManager &SM = getSourceManager();
  4800. // If the function is defined as a builtin macro, do not show macro expansion.
  4801. if (SM.isMacroArgExpansion(SL)) {
  4802. SL = SM.getSpellingLoc(SL);
  4803. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  4804. SM.getSpellingLoc(SR.getEnd()));
  4805. }
  4806. // Check if the destination is an array (rather than a pointer to an array).
  4807. QualType DstTy = DstArg->getType();
  4808. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  4809. Context);
  4810. if (!isKnownSizeArray) {
  4811. if (PatternType == 1)
  4812. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  4813. else
  4814. Diag(SL, diag::warn_strncat_src_size) << SR;
  4815. return;
  4816. }
  4817. if (PatternType == 1)
  4818. Diag(SL, diag::warn_strncat_large_size) << SR;
  4819. else
  4820. Diag(SL, diag::warn_strncat_src_size) << SR;
  4821. SmallString<128> sizeString;
  4822. llvm::raw_svector_ostream OS(sizeString);
  4823. OS << "sizeof(";
  4824. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  4825. OS << ") - ";
  4826. OS << "strlen(";
  4827. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  4828. OS << ") - 1";
  4829. Diag(SL, diag::note_strncat_wrong_size)
  4830. << FixItHint::CreateReplacement(SR, OS.str());
  4831. }
  4832. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  4833. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  4834. Decl *ParentDecl);
  4835. static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
  4836. Decl *ParentDecl);
  4837. /// CheckReturnStackAddr - Check if a return statement returns the address
  4838. /// of a stack variable.
  4839. static void
  4840. CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
  4841. SourceLocation ReturnLoc) {
  4842. Expr *stackE = nullptr;
  4843. SmallVector<DeclRefExpr *, 8> refVars;
  4844. // Perform checking for returned stack addresses, local blocks,
  4845. // label addresses or references to temporaries.
  4846. if (lhsType->isPointerType() ||
  4847. (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  4848. stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
  4849. } else if (lhsType->isReferenceType()) {
  4850. stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
  4851. }
  4852. if (!stackE)
  4853. return; // Nothing suspicious was found.
  4854. SourceLocation diagLoc;
  4855. SourceRange diagRange;
  4856. if (refVars.empty()) {
  4857. diagLoc = stackE->getLocStart();
  4858. diagRange = stackE->getSourceRange();
  4859. } else {
  4860. // We followed through a reference variable. 'stackE' contains the
  4861. // problematic expression but we will warn at the return statement pointing
  4862. // at the reference variable. We will later display the "trail" of
  4863. // reference variables using notes.
  4864. diagLoc = refVars[0]->getLocStart();
  4865. diagRange = refVars[0]->getSourceRange();
  4866. }
  4867. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
  4868. S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
  4869. : diag::warn_ret_stack_addr)
  4870. << DR->getDecl()->getDeclName() << diagRange;
  4871. } else if (isa<BlockExpr>(stackE)) { // local block.
  4872. S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  4873. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  4874. S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  4875. } else { // local temporary.
  4876. S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
  4877. : diag::warn_ret_local_temp_addr)
  4878. << diagRange;
  4879. }
  4880. // Display the "trail" of reference variables that we followed until we
  4881. // found the problematic expression using notes.
  4882. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  4883. VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  4884. // If this var binds to another reference var, show the range of the next
  4885. // var, otherwise the var binds to the problematic expression, in which case
  4886. // show the range of the expression.
  4887. SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
  4888. : stackE->getSourceRange();
  4889. S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  4890. << VD->getDeclName() << range;
  4891. }
  4892. }
  4893. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  4894. /// check if the expression in a return statement evaluates to an address
  4895. /// to a location on the stack, a local block, an address of a label, or a
  4896. /// reference to local temporary. The recursion is used to traverse the
  4897. /// AST of the return expression, with recursion backtracking when we
  4898. /// encounter a subexpression that (1) clearly does not lead to one of the
  4899. /// above problematic expressions (2) is something we cannot determine leads to
  4900. /// a problematic expression based on such local checking.
  4901. ///
  4902. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  4903. /// the expression that they point to. Such variables are added to the
  4904. /// 'refVars' vector so that we know what the reference variable "trail" was.
  4905. ///
  4906. /// EvalAddr processes expressions that are pointers that are used as
  4907. /// references (and not L-values). EvalVal handles all other values.
  4908. /// At the base case of the recursion is a check for the above problematic
  4909. /// expressions.
  4910. ///
  4911. /// This implementation handles:
  4912. ///
  4913. /// * pointer-to-pointer casts
  4914. /// * implicit conversions from array references to pointers
  4915. /// * taking the address of fields
  4916. /// * arbitrary interplay between "&" and "*" operators
  4917. /// * pointer arithmetic from an address of a stack variable
  4918. /// * taking the address of an array element where the array is on the stack
  4919. static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  4920. Decl *ParentDecl) {
  4921. if (E->isTypeDependent())
  4922. return nullptr;
  4923. // We should only be called for evaluating pointer expressions.
  4924. assert((E->getType()->isAnyPointerType() ||
  4925. E->getType()->isBlockPointerType() ||
  4926. E->getType()->isObjCQualifiedIdType()) &&
  4927. "EvalAddr only works on pointers");
  4928. E = E->IgnoreParens();
  4929. // Our "symbolic interpreter" is just a dispatch off the currently
  4930. // viewed AST node. We then recursively traverse the AST by calling
  4931. // EvalAddr and EvalVal appropriately.
  4932. switch (E->getStmtClass()) {
  4933. case Stmt::DeclRefExprClass: {
  4934. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  4935. // If we leave the immediate function, the lifetime isn't about to end.
  4936. if (DR->refersToEnclosingVariableOrCapture())
  4937. return nullptr;
  4938. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  4939. // If this is a reference variable, follow through to the expression that
  4940. // it points to.
  4941. if (V->hasLocalStorage() &&
  4942. V->getType()->isReferenceType() && V->hasInit()) {
  4943. // Add the reference variable to the "trail".
  4944. refVars.push_back(DR);
  4945. return EvalAddr(V->getInit(), refVars, ParentDecl);
  4946. }
  4947. return nullptr;
  4948. }
  4949. case Stmt::UnaryOperatorClass: {
  4950. // The only unary operator that make sense to handle here
  4951. // is AddrOf. All others don't make sense as pointers.
  4952. UnaryOperator *U = cast<UnaryOperator>(E);
  4953. if (U->getOpcode() == UO_AddrOf)
  4954. return EvalVal(U->getSubExpr(), refVars, ParentDecl);
  4955. else
  4956. return nullptr;
  4957. }
  4958. case Stmt::BinaryOperatorClass: {
  4959. // Handle pointer arithmetic. All other binary operators are not valid
  4960. // in this context.
  4961. BinaryOperator *B = cast<BinaryOperator>(E);
  4962. BinaryOperatorKind op = B->getOpcode();
  4963. if (op != BO_Add && op != BO_Sub)
  4964. return nullptr;
  4965. Expr *Base = B->getLHS();
  4966. // Determine which argument is the real pointer base. It could be
  4967. // the RHS argument instead of the LHS.
  4968. if (!Base->getType()->isPointerType()) Base = B->getRHS();
  4969. assert (Base->getType()->isPointerType());
  4970. return EvalAddr(Base, refVars, ParentDecl);
  4971. }
  4972. // For conditional operators we need to see if either the LHS or RHS are
  4973. // valid DeclRefExpr*s. If one of them is valid, we return it.
  4974. case Stmt::ConditionalOperatorClass: {
  4975. ConditionalOperator *C = cast<ConditionalOperator>(E);
  4976. // Handle the GNU extension for missing LHS.
  4977. // FIXME: That isn't a ConditionalOperator, so doesn't get here.
  4978. if (Expr *LHSExpr = C->getLHS()) {
  4979. // In C++, we can have a throw-expression, which has 'void' type.
  4980. if (!LHSExpr->getType()->isVoidType())
  4981. if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
  4982. return LHS;
  4983. }
  4984. // In C++, we can have a throw-expression, which has 'void' type.
  4985. if (C->getRHS()->getType()->isVoidType())
  4986. return nullptr;
  4987. return EvalAddr(C->getRHS(), refVars, ParentDecl);
  4988. }
  4989. case Stmt::BlockExprClass:
  4990. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  4991. return E; // local block.
  4992. return nullptr;
  4993. case Stmt::AddrLabelExprClass:
  4994. return E; // address of label.
  4995. case Stmt::ExprWithCleanupsClass:
  4996. return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  4997. ParentDecl);
  4998. // For casts, we need to handle conversions from arrays to
  4999. // pointer values, and pointer-to-pointer conversions.
  5000. case Stmt::ImplicitCastExprClass:
  5001. case Stmt::CStyleCastExprClass:
  5002. case Stmt::CXXFunctionalCastExprClass:
  5003. case Stmt::ObjCBridgedCastExprClass:
  5004. case Stmt::CXXStaticCastExprClass:
  5005. case Stmt::CXXDynamicCastExprClass:
  5006. case Stmt::CXXConstCastExprClass:
  5007. case Stmt::CXXReinterpretCastExprClass: {
  5008. Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  5009. switch (cast<CastExpr>(E)->getCastKind()) {
  5010. case CK_LValueToRValue:
  5011. case CK_NoOp:
  5012. case CK_BaseToDerived:
  5013. case CK_DerivedToBase:
  5014. case CK_UncheckedDerivedToBase:
  5015. case CK_Dynamic:
  5016. case CK_CPointerToObjCPointerCast:
  5017. case CK_BlockPointerToObjCPointerCast:
  5018. case CK_AnyPointerToBlockPointerCast:
  5019. return EvalAddr(SubExpr, refVars, ParentDecl);
  5020. case CK_ArrayToPointerDecay:
  5021. return EvalVal(SubExpr, refVars, ParentDecl);
  5022. case CK_BitCast:
  5023. if (SubExpr->getType()->isAnyPointerType() ||
  5024. SubExpr->getType()->isBlockPointerType() ||
  5025. SubExpr->getType()->isObjCQualifiedIdType())
  5026. return EvalAddr(SubExpr, refVars, ParentDecl);
  5027. else
  5028. return nullptr;
  5029. default:
  5030. return nullptr;
  5031. }
  5032. }
  5033. case Stmt::MaterializeTemporaryExprClass:
  5034. if (Expr *Result = EvalAddr(
  5035. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  5036. refVars, ParentDecl))
  5037. return Result;
  5038. return E;
  5039. // Everything else: we simply don't reason about them.
  5040. default:
  5041. return nullptr;
  5042. }
  5043. }
  5044. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  5045. /// See the comments for EvalAddr for more details.
  5046. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  5047. Decl *ParentDecl) {
  5048. do {
  5049. // We should only be called for evaluating non-pointer expressions, or
  5050. // expressions with a pointer type that are not used as references but instead
  5051. // are l-values (e.g., DeclRefExpr with a pointer type).
  5052. // Our "symbolic interpreter" is just a dispatch off the currently
  5053. // viewed AST node. We then recursively traverse the AST by calling
  5054. // EvalAddr and EvalVal appropriately.
  5055. E = E->IgnoreParens();
  5056. switch (E->getStmtClass()) {
  5057. case Stmt::ImplicitCastExprClass: {
  5058. ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  5059. if (IE->getValueKind() == VK_LValue) {
  5060. E = IE->getSubExpr();
  5061. continue;
  5062. }
  5063. return nullptr;
  5064. }
  5065. case Stmt::ExprWithCleanupsClass:
  5066. return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
  5067. case Stmt::DeclRefExprClass: {
  5068. // When we hit a DeclRefExpr we are looking at code that refers to a
  5069. // variable's name. If it's not a reference variable we check if it has
  5070. // local storage within the function, and if so, return the expression.
  5071. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  5072. // If we leave the immediate function, the lifetime isn't about to end.
  5073. if (DR->refersToEnclosingVariableOrCapture())
  5074. return nullptr;
  5075. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
  5076. // Check if it refers to itself, e.g. "int& i = i;".
  5077. if (V == ParentDecl)
  5078. return DR;
  5079. if (V->hasLocalStorage()) {
  5080. if (!V->getType()->isReferenceType())
  5081. return DR;
  5082. // Reference variable, follow through to the expression that
  5083. // it points to.
  5084. if (V->hasInit()) {
  5085. // Add the reference variable to the "trail".
  5086. refVars.push_back(DR);
  5087. return EvalVal(V->getInit(), refVars, V);
  5088. }
  5089. }
  5090. }
  5091. return nullptr;
  5092. }
  5093. case Stmt::UnaryOperatorClass: {
  5094. // The only unary operator that make sense to handle here
  5095. // is Deref. All others don't resolve to a "name." This includes
  5096. // handling all sorts of rvalues passed to a unary operator.
  5097. UnaryOperator *U = cast<UnaryOperator>(E);
  5098. if (U->getOpcode() == UO_Deref)
  5099. return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
  5100. return nullptr;
  5101. }
  5102. case Stmt::ArraySubscriptExprClass: {
  5103. // Array subscripts are potential references to data on the stack. We
  5104. // retrieve the DeclRefExpr* for the array variable if it indeed
  5105. // has local storage.
  5106. return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
  5107. }
  5108. case Stmt::OMPArraySectionExprClass: {
  5109. return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
  5110. ParentDecl);
  5111. }
  5112. case Stmt::ConditionalOperatorClass: {
  5113. // For conditional operators we need to see if either the LHS or RHS are
  5114. // non-NULL Expr's. If one is non-NULL, we return it.
  5115. ConditionalOperator *C = cast<ConditionalOperator>(E);
  5116. // Handle the GNU extension for missing LHS.
  5117. if (Expr *LHSExpr = C->getLHS()) {
  5118. // In C++, we can have a throw-expression, which has 'void' type.
  5119. if (!LHSExpr->getType()->isVoidType())
  5120. if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
  5121. return LHS;
  5122. }
  5123. // In C++, we can have a throw-expression, which has 'void' type.
  5124. if (C->getRHS()->getType()->isVoidType())
  5125. return nullptr;
  5126. return EvalVal(C->getRHS(), refVars, ParentDecl);
  5127. }
  5128. // Accesses to members are potential references to data on the stack.
  5129. case Stmt::MemberExprClass: {
  5130. MemberExpr *M = cast<MemberExpr>(E);
  5131. // Check for indirect access. We only want direct field accesses.
  5132. if (M->isArrow())
  5133. return nullptr;
  5134. // Check whether the member type is itself a reference, in which case
  5135. // we're not going to refer to the member, but to what the member refers to.
  5136. if (M->getMemberDecl()->getType()->isReferenceType())
  5137. return nullptr;
  5138. return EvalVal(M->getBase(), refVars, ParentDecl);
  5139. }
  5140. case Stmt::MaterializeTemporaryExprClass:
  5141. if (Expr *Result = EvalVal(
  5142. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  5143. refVars, ParentDecl))
  5144. return Result;
  5145. return E;
  5146. default:
  5147. // Check that we don't return or take the address of a reference to a
  5148. // temporary. This is only useful in C++.
  5149. if (!E->isTypeDependent() && E->isRValue())
  5150. return E;
  5151. // Everything else: we simply don't reason about them.
  5152. return nullptr;
  5153. }
  5154. } while (true);
  5155. }
  5156. void
  5157. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  5158. SourceLocation ReturnLoc,
  5159. bool isObjCMethod,
  5160. const AttrVec *Attrs,
  5161. const FunctionDecl *FD) {
  5162. CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
  5163. // Check if the return value is null but should not be.
  5164. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  5165. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  5166. CheckNonNullExpr(*this, RetValExp))
  5167. Diag(ReturnLoc, diag::warn_null_ret)
  5168. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  5169. // C++11 [basic.stc.dynamic.allocation]p4:
  5170. // If an allocation function declared with a non-throwing
  5171. // exception-specification fails to allocate storage, it shall return
  5172. // a null pointer. Any other allocation function that fails to allocate
  5173. // storage shall indicate failure only by throwing an exception [...]
  5174. if (FD) {
  5175. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  5176. if (Op == OO_New || Op == OO_Array_New) {
  5177. const FunctionProtoType *Proto
  5178. = FD->getType()->castAs<FunctionProtoType>();
  5179. if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
  5180. CheckNonNullExpr(*this, RetValExp))
  5181. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  5182. << FD << getLangOpts().CPlusPlus11;
  5183. }
  5184. }
  5185. }
  5186. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  5187. /// Check for comparisons of floating point operands using != and ==.
  5188. /// Issue a warning if these are no self-comparisons, as they are not likely
  5189. /// to do what the programmer intended.
  5190. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  5191. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  5192. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  5193. // Special case: check for x == x (which is OK).
  5194. // Do not emit warnings for such cases.
  5195. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  5196. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  5197. if (DRL->getDecl() == DRR->getDecl())
  5198. return;
  5199. // Special case: check for comparisons against literals that can be exactly
  5200. // represented by APFloat. In such cases, do not emit a warning. This
  5201. // is a heuristic: often comparison against such literals are used to
  5202. // detect if a value in a variable has not changed. This clearly can
  5203. // lead to false negatives.
  5204. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  5205. if (FLL->isExact())
  5206. return;
  5207. } else
  5208. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  5209. if (FLR->isExact())
  5210. return;
  5211. // Check for comparisons with builtin types.
  5212. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  5213. if (CL->getBuiltinCallee())
  5214. return;
  5215. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  5216. if (CR->getBuiltinCallee())
  5217. return;
  5218. // Emit the diagnostic.
  5219. Diag(Loc, diag::warn_floatingpoint_eq)
  5220. << LHS->getSourceRange() << RHS->getSourceRange();
  5221. }
  5222. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  5223. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  5224. namespace {
  5225. /// Structure recording the 'active' range of an integer-valued
  5226. /// expression.
  5227. struct IntRange {
  5228. /// The number of bits active in the int.
  5229. unsigned Width;
  5230. /// True if the int is known not to have negative values.
  5231. bool NonNegative;
  5232. IntRange(unsigned Width, bool NonNegative)
  5233. : Width(Width), NonNegative(NonNegative)
  5234. {}
  5235. /// Returns the range of the bool type.
  5236. static IntRange forBoolType() {
  5237. return IntRange(1, true);
  5238. }
  5239. /// Returns the range of an opaque value of the given integral type.
  5240. static IntRange forValueOfType(ASTContext &C, QualType T) {
  5241. return forValueOfCanonicalType(C,
  5242. T->getCanonicalTypeInternal().getTypePtr());
  5243. }
  5244. /// Returns the range of an opaque value of a canonical integral type.
  5245. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  5246. assert(T->isCanonicalUnqualified());
  5247. if (const VectorType *VT = dyn_cast<VectorType>(T))
  5248. T = VT->getElementType().getTypePtr();
  5249. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  5250. T = CT->getElementType().getTypePtr();
  5251. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  5252. T = AT->getValueType().getTypePtr();
  5253. // For enum types, use the known bit width of the enumerators.
  5254. if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  5255. EnumDecl *Enum = ET->getDecl();
  5256. if (!Enum->isCompleteDefinition())
  5257. return IntRange(C.getIntWidth(QualType(T, 0)), false);
  5258. unsigned NumPositive = Enum->getNumPositiveBits();
  5259. unsigned NumNegative = Enum->getNumNegativeBits();
  5260. if (NumNegative == 0)
  5261. return IntRange(NumPositive, true/*NonNegative*/);
  5262. else
  5263. return IntRange(std::max(NumPositive + 1, NumNegative),
  5264. false/*NonNegative*/);
  5265. }
  5266. const BuiltinType *BT = cast<BuiltinType>(T);
  5267. assert(BT->isInteger());
  5268. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  5269. }
  5270. /// Returns the "target" range of a canonical integral type, i.e.
  5271. /// the range of values expressible in the type.
  5272. ///
  5273. /// This matches forValueOfCanonicalType except that enums have the
  5274. /// full range of their type, not the range of their enumerators.
  5275. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  5276. assert(T->isCanonicalUnqualified());
  5277. if (const VectorType *VT = dyn_cast<VectorType>(T))
  5278. T = VT->getElementType().getTypePtr();
  5279. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  5280. T = CT->getElementType().getTypePtr();
  5281. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  5282. T = AT->getValueType().getTypePtr();
  5283. if (const EnumType *ET = dyn_cast<EnumType>(T))
  5284. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  5285. const BuiltinType *BT = cast<BuiltinType>(T);
  5286. assert(BT->isInteger());
  5287. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  5288. }
  5289. /// Returns the supremum of two ranges: i.e. their conservative merge.
  5290. static IntRange join(IntRange L, IntRange R) {
  5291. return IntRange(std::max(L.Width, R.Width),
  5292. L.NonNegative && R.NonNegative);
  5293. }
  5294. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  5295. static IntRange meet(IntRange L, IntRange R) {
  5296. return IntRange(std::min(L.Width, R.Width),
  5297. L.NonNegative || R.NonNegative);
  5298. }
  5299. };
  5300. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  5301. unsigned MaxWidth) {
  5302. if (value.isSigned() && value.isNegative())
  5303. return IntRange(value.getMinSignedBits(), false);
  5304. if (value.getBitWidth() > MaxWidth)
  5305. value = value.trunc(MaxWidth);
  5306. // isNonNegative() just checks the sign bit without considering
  5307. // signedness.
  5308. return IntRange(value.getActiveBits(), true);
  5309. }
  5310. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  5311. unsigned MaxWidth) {
  5312. if (result.isInt())
  5313. return GetValueRange(C, result.getInt(), MaxWidth);
  5314. if (result.isVector()) {
  5315. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  5316. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  5317. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  5318. R = IntRange::join(R, El);
  5319. }
  5320. return R;
  5321. }
  5322. if (result.isComplexInt()) {
  5323. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  5324. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  5325. return IntRange::join(R, I);
  5326. }
  5327. // This can happen with lossless casts to intptr_t of "based" lvalues.
  5328. // Assume it might use arbitrary bits.
  5329. // FIXME: The only reason we need to pass the type in here is to get
  5330. // the sign right on this one case. It would be nice if APValue
  5331. // preserved this.
  5332. assert(result.isLValue() || result.isAddrLabelDiff());
  5333. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  5334. }
  5335. static QualType GetExprType(Expr *E) {
  5336. QualType Ty = E->getType();
  5337. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  5338. Ty = AtomicRHS->getValueType();
  5339. return Ty;
  5340. }
  5341. /// Pseudo-evaluate the given integer expression, estimating the
  5342. /// range of values it might take.
  5343. ///
  5344. /// \param MaxWidth - the width to which the value will be truncated
  5345. static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
  5346. E = E->IgnoreParens();
  5347. // Try a full evaluation first.
  5348. Expr::EvalResult result;
  5349. if (E->EvaluateAsRValue(result, C))
  5350. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  5351. // I think we only want to look through implicit casts here; if the
  5352. // user has an explicit widening cast, we should treat the value as
  5353. // being of the new, wider type.
  5354. if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
  5355. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  5356. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  5357. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  5358. bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
  5359. // Assume that non-integer casts can span the full range of the type.
  5360. if (!isIntegerCast)
  5361. return OutputTypeRange;
  5362. IntRange SubRange
  5363. = GetExprRange(C, CE->getSubExpr(),
  5364. std::min(MaxWidth, OutputTypeRange.Width));
  5365. // Bail out if the subexpr's range is as wide as the cast type.
  5366. if (SubRange.Width >= OutputTypeRange.Width)
  5367. return OutputTypeRange;
  5368. // Otherwise, we take the smaller width, and we're non-negative if
  5369. // either the output type or the subexpr is.
  5370. return IntRange(SubRange.Width,
  5371. SubRange.NonNegative || OutputTypeRange.NonNegative);
  5372. }
  5373. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  5374. // If we can fold the condition, just take that operand.
  5375. bool CondResult;
  5376. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  5377. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  5378. : CO->getFalseExpr(),
  5379. MaxWidth);
  5380. // Otherwise, conservatively merge.
  5381. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  5382. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  5383. return IntRange::join(L, R);
  5384. }
  5385. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  5386. switch (BO->getOpcode()) {
  5387. // Boolean-valued operations are single-bit and positive.
  5388. case BO_LAnd:
  5389. case BO_LOr:
  5390. case BO_LT:
  5391. case BO_GT:
  5392. case BO_LE:
  5393. case BO_GE:
  5394. case BO_EQ:
  5395. case BO_NE:
  5396. return IntRange::forBoolType();
  5397. // The type of the assignments is the type of the LHS, so the RHS
  5398. // is not necessarily the same type.
  5399. case BO_MulAssign:
  5400. case BO_DivAssign:
  5401. case BO_RemAssign:
  5402. case BO_AddAssign:
  5403. case BO_SubAssign:
  5404. case BO_XorAssign:
  5405. case BO_OrAssign:
  5406. // TODO: bitfields?
  5407. return IntRange::forValueOfType(C, GetExprType(E));
  5408. // Simple assignments just pass through the RHS, which will have
  5409. // been coerced to the LHS type.
  5410. case BO_Assign:
  5411. // TODO: bitfields?
  5412. return GetExprRange(C, BO->getRHS(), MaxWidth);
  5413. // Operations with opaque sources are black-listed.
  5414. case BO_PtrMemD:
  5415. case BO_PtrMemI:
  5416. return IntRange::forValueOfType(C, GetExprType(E));
  5417. // Bitwise-and uses the *infinum* of the two source ranges.
  5418. case BO_And:
  5419. case BO_AndAssign:
  5420. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  5421. GetExprRange(C, BO->getRHS(), MaxWidth));
  5422. // Left shift gets black-listed based on a judgement call.
  5423. case BO_Shl:
  5424. // ...except that we want to treat '1 << (blah)' as logically
  5425. // positive. It's an important idiom.
  5426. if (IntegerLiteral *I
  5427. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  5428. if (I->getValue() == 1) {
  5429. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  5430. return IntRange(R.Width, /*NonNegative*/ true);
  5431. }
  5432. }
  5433. // fallthrough
  5434. case BO_ShlAssign:
  5435. return IntRange::forValueOfType(C, GetExprType(E));
  5436. // Right shift by a constant can narrow its left argument.
  5437. case BO_Shr:
  5438. case BO_ShrAssign: {
  5439. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  5440. // If the shift amount is a positive constant, drop the width by
  5441. // that much.
  5442. llvm::APSInt shift;
  5443. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  5444. shift.isNonNegative()) {
  5445. unsigned zext = shift.getZExtValue();
  5446. if (zext >= L.Width)
  5447. L.Width = (L.NonNegative ? 0 : 1);
  5448. else
  5449. L.Width -= zext;
  5450. }
  5451. return L;
  5452. }
  5453. // Comma acts as its right operand.
  5454. case BO_Comma:
  5455. return GetExprRange(C, BO->getRHS(), MaxWidth);
  5456. // Black-list pointer subtractions.
  5457. case BO_Sub:
  5458. if (BO->getLHS()->getType()->isPointerType())
  5459. return IntRange::forValueOfType(C, GetExprType(E));
  5460. break;
  5461. // The width of a division result is mostly determined by the size
  5462. // of the LHS.
  5463. case BO_Div: {
  5464. // Don't 'pre-truncate' the operands.
  5465. unsigned opWidth = C.getIntWidth(GetExprType(E));
  5466. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  5467. // If the divisor is constant, use that.
  5468. llvm::APSInt divisor;
  5469. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  5470. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  5471. if (log2 >= L.Width)
  5472. L.Width = (L.NonNegative ? 0 : 1);
  5473. else
  5474. L.Width = std::min(L.Width - log2, MaxWidth);
  5475. return L;
  5476. }
  5477. // Otherwise, just use the LHS's width.
  5478. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  5479. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  5480. }
  5481. // The result of a remainder can't be larger than the result of
  5482. // either side.
  5483. case BO_Rem: {
  5484. // Don't 'pre-truncate' the operands.
  5485. unsigned opWidth = C.getIntWidth(GetExprType(E));
  5486. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  5487. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  5488. IntRange meet = IntRange::meet(L, R);
  5489. meet.Width = std::min(meet.Width, MaxWidth);
  5490. return meet;
  5491. }
  5492. // The default behavior is okay for these.
  5493. case BO_Mul:
  5494. case BO_Add:
  5495. case BO_Xor:
  5496. case BO_Or:
  5497. break;
  5498. }
  5499. // The default case is to treat the operation as if it were closed
  5500. // on the narrowest type that encompasses both operands.
  5501. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  5502. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  5503. return IntRange::join(L, R);
  5504. }
  5505. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  5506. switch (UO->getOpcode()) {
  5507. // Boolean-valued operations are white-listed.
  5508. case UO_LNot:
  5509. return IntRange::forBoolType();
  5510. // Operations with opaque sources are black-listed.
  5511. case UO_Deref:
  5512. case UO_AddrOf: // should be impossible
  5513. return IntRange::forValueOfType(C, GetExprType(E));
  5514. default:
  5515. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  5516. }
  5517. }
  5518. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
  5519. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
  5520. if (FieldDecl *BitField = E->getSourceBitField())
  5521. return IntRange(BitField->getBitWidthValue(C),
  5522. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  5523. return IntRange::forValueOfType(C, GetExprType(E));
  5524. }
  5525. static IntRange GetExprRange(ASTContext &C, Expr *E) {
  5526. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
  5527. }
  5528. /// Checks whether the given value, which currently has the given
  5529. /// source semantics, has the same value when coerced through the
  5530. /// target semantics.
  5531. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  5532. const llvm::fltSemantics &Src,
  5533. const llvm::fltSemantics &Tgt) {
  5534. llvm::APFloat truncated = value;
  5535. bool ignored;
  5536. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  5537. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  5538. return truncated.bitwiseIsEqual(value);
  5539. }
  5540. /// Checks whether the given value, which currently has the given
  5541. /// source semantics, has the same value when coerced through the
  5542. /// target semantics.
  5543. ///
  5544. /// The value might be a vector of floats (or a complex number).
  5545. static bool IsSameFloatAfterCast(const APValue &value,
  5546. const llvm::fltSemantics &Src,
  5547. const llvm::fltSemantics &Tgt) {
  5548. if (value.isFloat())
  5549. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  5550. if (value.isVector()) {
  5551. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  5552. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  5553. return false;
  5554. return true;
  5555. }
  5556. assert(value.isComplexFloat());
  5557. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  5558. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  5559. }
  5560. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  5561. static bool IsZero(Sema &S, Expr *E) {
  5562. // Suppress cases where we are comparing against an enum constant.
  5563. if (const DeclRefExpr *DR =
  5564. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  5565. if (isa<EnumConstantDecl>(DR->getDecl()))
  5566. return false;
  5567. // Suppress cases where the '0' value is expanded from a macro.
  5568. if (E->getLocStart().isMacroID())
  5569. return false;
  5570. llvm::APSInt Value;
  5571. return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
  5572. }
  5573. static bool HasEnumType(Expr *E) {
  5574. // Strip off implicit integral promotions.
  5575. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  5576. if (ICE->getCastKind() != CK_IntegralCast &&
  5577. ICE->getCastKind() != CK_NoOp)
  5578. break;
  5579. E = ICE->getSubExpr();
  5580. }
  5581. return E->getType()->isEnumeralType();
  5582. }
  5583. static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
  5584. // Disable warning in template instantiations.
  5585. if (!S.ActiveTemplateInstantiations.empty())
  5586. return;
  5587. BinaryOperatorKind op = E->getOpcode();
  5588. if (E->isValueDependent())
  5589. return;
  5590. if (op == BO_LT && IsZero(S, E->getRHS())) {
  5591. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  5592. << "< 0" << "false" << HasEnumType(E->getLHS())
  5593. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  5594. } else if (op == BO_GE && IsZero(S, E->getRHS())) {
  5595. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  5596. << ">= 0" << "true" << HasEnumType(E->getLHS())
  5597. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  5598. } else if (op == BO_GT && IsZero(S, E->getLHS())) {
  5599. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  5600. << "0 >" << "false" << HasEnumType(E->getRHS())
  5601. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  5602. } else if (op == BO_LE && IsZero(S, E->getLHS())) {
  5603. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  5604. << "0 <=" << "true" << HasEnumType(E->getRHS())
  5605. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  5606. }
  5607. }
  5608. static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
  5609. Expr *Constant, Expr *Other,
  5610. llvm::APSInt Value,
  5611. bool RhsConstant) {
  5612. // Disable warning in template instantiations.
  5613. if (!S.ActiveTemplateInstantiations.empty())
  5614. return;
  5615. // TODO: Investigate using GetExprRange() to get tighter bounds
  5616. // on the bit ranges.
  5617. QualType OtherT = Other->getType();
  5618. if (const auto *AT = OtherT->getAs<AtomicType>())
  5619. OtherT = AT->getValueType();
  5620. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  5621. unsigned OtherWidth = OtherRange.Width;
  5622. bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
  5623. // 0 values are handled later by CheckTrivialUnsignedComparison().
  5624. if ((Value == 0) && (!OtherIsBooleanType))
  5625. return;
  5626. BinaryOperatorKind op = E->getOpcode();
  5627. bool IsTrue = true;
  5628. // Used for diagnostic printout.
  5629. enum {
  5630. LiteralConstant = 0,
  5631. CXXBoolLiteralTrue,
  5632. CXXBoolLiteralFalse
  5633. } LiteralOrBoolConstant = LiteralConstant;
  5634. if (!OtherIsBooleanType) {
  5635. QualType ConstantT = Constant->getType();
  5636. QualType CommonT = E->getLHS()->getType();
  5637. if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
  5638. return;
  5639. assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
  5640. "comparison with non-integer type");
  5641. bool ConstantSigned = ConstantT->isSignedIntegerType();
  5642. bool CommonSigned = CommonT->isSignedIntegerType();
  5643. bool EqualityOnly = false;
  5644. if (CommonSigned) {
  5645. // The common type is signed, therefore no signed to unsigned conversion.
  5646. if (!OtherRange.NonNegative) {
  5647. // Check that the constant is representable in type OtherT.
  5648. if (ConstantSigned) {
  5649. if (OtherWidth >= Value.getMinSignedBits())
  5650. return;
  5651. } else { // !ConstantSigned
  5652. if (OtherWidth >= Value.getActiveBits() + 1)
  5653. return;
  5654. }
  5655. } else { // !OtherSigned
  5656. // Check that the constant is representable in type OtherT.
  5657. // Negative values are out of range.
  5658. if (ConstantSigned) {
  5659. if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
  5660. return;
  5661. } else { // !ConstantSigned
  5662. if (OtherWidth >= Value.getActiveBits())
  5663. return;
  5664. }
  5665. }
  5666. } else { // !CommonSigned
  5667. if (OtherRange.NonNegative) {
  5668. if (OtherWidth >= Value.getActiveBits())
  5669. return;
  5670. } else { // OtherSigned
  5671. assert(!ConstantSigned &&
  5672. "Two signed types converted to unsigned types.");
  5673. // Check to see if the constant is representable in OtherT.
  5674. if (OtherWidth > Value.getActiveBits())
  5675. return;
  5676. // Check to see if the constant is equivalent to a negative value
  5677. // cast to CommonT.
  5678. if (S.Context.getIntWidth(ConstantT) ==
  5679. S.Context.getIntWidth(CommonT) &&
  5680. Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
  5681. return;
  5682. // The constant value rests between values that OtherT can represent
  5683. // after conversion. Relational comparison still works, but equality
  5684. // comparisons will be tautological.
  5685. EqualityOnly = true;
  5686. }
  5687. }
  5688. bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
  5689. if (op == BO_EQ || op == BO_NE) {
  5690. IsTrue = op == BO_NE;
  5691. } else if (EqualityOnly) {
  5692. return;
  5693. } else if (RhsConstant) {
  5694. if (op == BO_GT || op == BO_GE)
  5695. IsTrue = !PositiveConstant;
  5696. else // op == BO_LT || op == BO_LE
  5697. IsTrue = PositiveConstant;
  5698. } else {
  5699. if (op == BO_LT || op == BO_LE)
  5700. IsTrue = !PositiveConstant;
  5701. else // op == BO_GT || op == BO_GE
  5702. IsTrue = PositiveConstant;
  5703. }
  5704. } else {
  5705. // Other isKnownToHaveBooleanValue
  5706. enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
  5707. enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
  5708. enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
  5709. static const struct LinkedConditions {
  5710. CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
  5711. CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
  5712. CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
  5713. CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
  5714. CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
  5715. CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
  5716. } TruthTable = {
  5717. // Constant on LHS. | Constant on RHS. |
  5718. // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
  5719. { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
  5720. { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
  5721. { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
  5722. { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
  5723. { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
  5724. { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
  5725. };
  5726. bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
  5727. enum ConstantValue ConstVal = Zero;
  5728. if (Value.isUnsigned() || Value.isNonNegative()) {
  5729. if (Value == 0) {
  5730. LiteralOrBoolConstant =
  5731. ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
  5732. ConstVal = Zero;
  5733. } else if (Value == 1) {
  5734. LiteralOrBoolConstant =
  5735. ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
  5736. ConstVal = One;
  5737. } else {
  5738. LiteralOrBoolConstant = LiteralConstant;
  5739. ConstVal = GT_One;
  5740. }
  5741. } else {
  5742. ConstVal = LT_Zero;
  5743. }
  5744. CompareBoolWithConstantResult CmpRes;
  5745. switch (op) {
  5746. case BO_LT:
  5747. CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
  5748. break;
  5749. case BO_GT:
  5750. CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
  5751. break;
  5752. case BO_LE:
  5753. CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
  5754. break;
  5755. case BO_GE:
  5756. CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
  5757. break;
  5758. case BO_EQ:
  5759. CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
  5760. break;
  5761. case BO_NE:
  5762. CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
  5763. break;
  5764. default:
  5765. CmpRes = Unkwn;
  5766. break;
  5767. }
  5768. if (CmpRes == AFals) {
  5769. IsTrue = false;
  5770. } else if (CmpRes == ATrue) {
  5771. IsTrue = true;
  5772. } else {
  5773. return;
  5774. }
  5775. }
  5776. // If this is a comparison to an enum constant, include that
  5777. // constant in the diagnostic.
  5778. const EnumConstantDecl *ED = nullptr;
  5779. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  5780. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  5781. SmallString<64> PrettySourceValue;
  5782. llvm::raw_svector_ostream OS(PrettySourceValue);
  5783. if (ED)
  5784. OS << '\'' << *ED << "' (" << Value << ")";
  5785. else
  5786. OS << Value;
  5787. S.DiagRuntimeBehavior(
  5788. E->getOperatorLoc(), E,
  5789. S.PDiag(diag::warn_out_of_range_compare)
  5790. << OS.str() << LiteralOrBoolConstant
  5791. << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
  5792. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  5793. }
  5794. /// Analyze the operands of the given comparison. Implements the
  5795. /// fallback case from AnalyzeComparison.
  5796. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  5797. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  5798. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  5799. }
  5800. /// \brief Implements -Wsign-compare.
  5801. ///
  5802. /// \param E the binary operator to check for warnings
  5803. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  5804. // The type the comparison is being performed in.
  5805. QualType T = E->getLHS()->getType();
  5806. // Only analyze comparison operators where both sides have been converted to
  5807. // the same type.
  5808. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  5809. return AnalyzeImpConvsInComparison(S, E);
  5810. // Don't analyze value-dependent comparisons directly.
  5811. if (E->isValueDependent())
  5812. return AnalyzeImpConvsInComparison(S, E);
  5813. Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
  5814. Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
  5815. bool IsComparisonConstant = false;
  5816. // Check whether an integer constant comparison results in a value
  5817. // of 'true' or 'false'.
  5818. if (T->isIntegralType(S.Context)) {
  5819. llvm::APSInt RHSValue;
  5820. bool IsRHSIntegralLiteral =
  5821. RHS->isIntegerConstantExpr(RHSValue, S.Context);
  5822. llvm::APSInt LHSValue;
  5823. bool IsLHSIntegralLiteral =
  5824. LHS->isIntegerConstantExpr(LHSValue, S.Context);
  5825. if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
  5826. DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
  5827. else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  5828. DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
  5829. else
  5830. IsComparisonConstant =
  5831. (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
  5832. } else if (!T->hasUnsignedIntegerRepresentation())
  5833. IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
  5834. // We don't do anything special if this isn't an unsigned integral
  5835. // comparison: we're only interested in integral comparisons, and
  5836. // signed comparisons only happen in cases we don't care to warn about.
  5837. //
  5838. // We also don't care about value-dependent expressions or expressions
  5839. // whose result is a constant.
  5840. if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
  5841. return AnalyzeImpConvsInComparison(S, E);
  5842. // Check to see if one of the (unmodified) operands is of different
  5843. // signedness.
  5844. Expr *signedOperand, *unsignedOperand;
  5845. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  5846. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  5847. "unsigned comparison between two signed integer expressions?");
  5848. signedOperand = LHS;
  5849. unsignedOperand = RHS;
  5850. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  5851. signedOperand = RHS;
  5852. unsignedOperand = LHS;
  5853. } else {
  5854. CheckTrivialUnsignedComparison(S, E);
  5855. return AnalyzeImpConvsInComparison(S, E);
  5856. }
  5857. // Otherwise, calculate the effective range of the signed operand.
  5858. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  5859. // Go ahead and analyze implicit conversions in the operands. Note
  5860. // that we skip the implicit conversions on both sides.
  5861. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  5862. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  5863. // If the signed range is non-negative, -Wsign-compare won't fire,
  5864. // but we should still check for comparisons which are always true
  5865. // or false.
  5866. if (signedRange.NonNegative)
  5867. return CheckTrivialUnsignedComparison(S, E);
  5868. // For (in)equality comparisons, if the unsigned operand is a
  5869. // constant which cannot collide with a overflowed signed operand,
  5870. // then reinterpreting the signed operand as unsigned will not
  5871. // change the result of the comparison.
  5872. if (E->isEqualityOp()) {
  5873. unsigned comparisonWidth = S.Context.getIntWidth(T);
  5874. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  5875. // We should never be unable to prove that the unsigned operand is
  5876. // non-negative.
  5877. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  5878. if (unsignedRange.Width < comparisonWidth)
  5879. return;
  5880. }
  5881. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  5882. S.PDiag(diag::warn_mixed_sign_comparison)
  5883. << LHS->getType() << RHS->getType()
  5884. << LHS->getSourceRange() << RHS->getSourceRange());
  5885. }
  5886. /// Analyzes an attempt to assign the given value to a bitfield.
  5887. ///
  5888. /// Returns true if there was something fishy about the attempt.
  5889. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  5890. SourceLocation InitLoc) {
  5891. assert(Bitfield->isBitField());
  5892. if (Bitfield->isInvalidDecl())
  5893. return false;
  5894. // White-list bool bitfields.
  5895. if (Bitfield->getType()->isBooleanType())
  5896. return false;
  5897. // Ignore value- or type-dependent expressions.
  5898. if (Bitfield->getBitWidth()->isValueDependent() ||
  5899. Bitfield->getBitWidth()->isTypeDependent() ||
  5900. Init->isValueDependent() ||
  5901. Init->isTypeDependent())
  5902. return false;
  5903. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  5904. llvm::APSInt Value;
  5905. if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
  5906. return false;
  5907. unsigned OriginalWidth = Value.getBitWidth();
  5908. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  5909. if (OriginalWidth <= FieldWidth)
  5910. return false;
  5911. // Compute the value which the bitfield will contain.
  5912. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  5913. TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
  5914. // Check whether the stored value is equal to the original value.
  5915. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  5916. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  5917. return false;
  5918. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  5919. // therefore don't strictly fit into a signed bitfield of width 1.
  5920. if (FieldWidth == 1 && Value == 1)
  5921. return false;
  5922. std::string PrettyValue = Value.toString(10);
  5923. std::string PrettyTrunc = TruncatedValue.toString(10);
  5924. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  5925. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  5926. << Init->getSourceRange();
  5927. return true;
  5928. }
  5929. /// Analyze the given simple or compound assignment for warning-worthy
  5930. /// operations.
  5931. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  5932. // Just recurse on the LHS.
  5933. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  5934. // We want to recurse on the RHS as normal unless we're assigning to
  5935. // a bitfield.
  5936. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  5937. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  5938. E->getOperatorLoc())) {
  5939. // Recurse, ignoring any implicit conversions on the RHS.
  5940. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  5941. E->getOperatorLoc());
  5942. }
  5943. }
  5944. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  5945. }
  5946. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  5947. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  5948. SourceLocation CContext, unsigned diag,
  5949. bool pruneControlFlow = false) {
  5950. if (pruneControlFlow) {
  5951. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  5952. S.PDiag(diag)
  5953. << SourceType << T << E->getSourceRange()
  5954. << SourceRange(CContext));
  5955. return;
  5956. }
  5957. S.Diag(E->getExprLoc(), diag)
  5958. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  5959. }
  5960. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  5961. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  5962. SourceLocation CContext, unsigned diag,
  5963. bool pruneControlFlow = false) {
  5964. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  5965. }
  5966. /// Diagnose an implicit cast from a literal expression. Does not warn when the
  5967. /// cast wouldn't lose information.
  5968. void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
  5969. SourceLocation CContext) {
  5970. // Try to convert the literal exactly to an integer. If we can, don't warn.
  5971. bool isExact = false;
  5972. const llvm::APFloat &Value = FL->getValue();
  5973. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  5974. T->hasUnsignedIntegerRepresentation());
  5975. if (Value.convertToInteger(IntegerValue,
  5976. llvm::APFloat::rmTowardZero, &isExact)
  5977. == llvm::APFloat::opOK && isExact)
  5978. return;
  5979. // FIXME: Force the precision of the source value down so we don't print
  5980. // digits which are usually useless (we don't really care here if we
  5981. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  5982. // would automatically print the shortest representation, but it's a bit
  5983. // tricky to implement.
  5984. SmallString<16> PrettySourceValue;
  5985. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  5986. precision = (precision * 59 + 195) / 196;
  5987. Value.toString(PrettySourceValue, precision);
  5988. SmallString<16> PrettyTargetValue;
  5989. if (T->isSpecificBuiltinType(BuiltinType::Bool))
  5990. PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
  5991. else
  5992. IntegerValue.toString(PrettyTargetValue);
  5993. S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
  5994. << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
  5995. << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
  5996. }
  5997. std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
  5998. if (!Range.Width) return "0";
  5999. llvm::APSInt ValueInRange = Value;
  6000. ValueInRange.setIsSigned(!Range.NonNegative);
  6001. ValueInRange = ValueInRange.trunc(Range.Width);
  6002. return ValueInRange.toString(10);
  6003. }
  6004. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  6005. if (!isa<ImplicitCastExpr>(Ex))
  6006. return false;
  6007. Expr *InnerE = Ex->IgnoreParenImpCasts();
  6008. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  6009. const Type *Source =
  6010. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  6011. if (Target->isDependentType())
  6012. return false;
  6013. const BuiltinType *FloatCandidateBT =
  6014. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  6015. const Type *BoolCandidateType = ToBool ? Target : Source;
  6016. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  6017. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  6018. }
  6019. void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  6020. SourceLocation CC) {
  6021. unsigned NumArgs = TheCall->getNumArgs();
  6022. for (unsigned i = 0; i < NumArgs; ++i) {
  6023. Expr *CurrA = TheCall->getArg(i);
  6024. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  6025. continue;
  6026. bool IsSwapped = ((i > 0) &&
  6027. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  6028. IsSwapped |= ((i < (NumArgs - 1)) &&
  6029. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  6030. if (IsSwapped) {
  6031. // Warn on this floating-point to bool conversion.
  6032. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  6033. CurrA->getType(), CC,
  6034. diag::warn_impcast_floating_point_to_bool);
  6035. }
  6036. }
  6037. }
  6038. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  6039. SourceLocation CC) {
  6040. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  6041. E->getExprLoc()))
  6042. return;
  6043. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  6044. const Expr::NullPointerConstantKind NullKind =
  6045. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  6046. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  6047. return;
  6048. // Return if target type is a safe conversion.
  6049. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  6050. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  6051. return;
  6052. SourceLocation Loc = E->getSourceRange().getBegin();
  6053. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  6054. if (NullKind == Expr::NPCK_GNUNull) {
  6055. if (Loc.isMacroID())
  6056. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
  6057. }
  6058. // Only warn if the null and context location are in the same macro expansion.
  6059. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  6060. return;
  6061. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  6062. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
  6063. << FixItHint::CreateReplacement(Loc,
  6064. S.getFixItZeroLiteralForType(T, Loc));
  6065. }
  6066. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  6067. ObjCArrayLiteral *ArrayLiteral);
  6068. static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  6069. ObjCDictionaryLiteral *DictionaryLiteral);
  6070. /// Check a single element within a collection literal against the
  6071. /// target element type.
  6072. static void checkObjCCollectionLiteralElement(Sema &S,
  6073. QualType TargetElementType,
  6074. Expr *Element,
  6075. unsigned ElementKind) {
  6076. // Skip a bitcast to 'id' or qualified 'id'.
  6077. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  6078. if (ICE->getCastKind() == CK_BitCast &&
  6079. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  6080. Element = ICE->getSubExpr();
  6081. }
  6082. QualType ElementType = Element->getType();
  6083. ExprResult ElementResult(Element);
  6084. if (ElementType->getAs<ObjCObjectPointerType>() &&
  6085. S.CheckSingleAssignmentConstraints(TargetElementType,
  6086. ElementResult,
  6087. false, false)
  6088. != Sema::Compatible) {
  6089. S.Diag(Element->getLocStart(),
  6090. diag::warn_objc_collection_literal_element)
  6091. << ElementType << ElementKind << TargetElementType
  6092. << Element->getSourceRange();
  6093. }
  6094. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  6095. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  6096. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  6097. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  6098. }
  6099. /// Check an Objective-C array literal being converted to the given
  6100. /// target type.
  6101. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  6102. ObjCArrayLiteral *ArrayLiteral) {
  6103. if (!S.NSArrayDecl)
  6104. return;
  6105. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  6106. if (!TargetObjCPtr)
  6107. return;
  6108. if (TargetObjCPtr->isUnspecialized() ||
  6109. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  6110. != S.NSArrayDecl->getCanonicalDecl())
  6111. return;
  6112. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  6113. if (TypeArgs.size() != 1)
  6114. return;
  6115. QualType TargetElementType = TypeArgs[0];
  6116. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  6117. checkObjCCollectionLiteralElement(S, TargetElementType,
  6118. ArrayLiteral->getElement(I),
  6119. 0);
  6120. }
  6121. }
  6122. /// Check an Objective-C dictionary literal being converted to the given
  6123. /// target type.
  6124. static void checkObjCDictionaryLiteral(
  6125. Sema &S, QualType TargetType,
  6126. ObjCDictionaryLiteral *DictionaryLiteral) {
  6127. if (!S.NSDictionaryDecl)
  6128. return;
  6129. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  6130. if (!TargetObjCPtr)
  6131. return;
  6132. if (TargetObjCPtr->isUnspecialized() ||
  6133. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  6134. != S.NSDictionaryDecl->getCanonicalDecl())
  6135. return;
  6136. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  6137. if (TypeArgs.size() != 2)
  6138. return;
  6139. QualType TargetKeyType = TypeArgs[0];
  6140. QualType TargetObjectType = TypeArgs[1];
  6141. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  6142. auto Element = DictionaryLiteral->getKeyValueElement(I);
  6143. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  6144. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  6145. }
  6146. }
  6147. void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  6148. SourceLocation CC, bool *ICContext = nullptr) {
  6149. if (E->isTypeDependent() || E->isValueDependent()) return;
  6150. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  6151. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  6152. if (Source == Target) return;
  6153. if (Target->isDependentType()) return;
  6154. // If the conversion context location is invalid don't complain. We also
  6155. // don't want to emit a warning if the issue occurs from the expansion of
  6156. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  6157. // delay this check as long as possible. Once we detect we are in that
  6158. // scenario, we just return.
  6159. if (CC.isInvalid())
  6160. return;
  6161. // Diagnose implicit casts to bool.
  6162. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  6163. if (isa<StringLiteral>(E))
  6164. // Warn on string literal to bool. Checks for string literals in logical
  6165. // and expressions, for instance, assert(0 && "error here"), are
  6166. // prevented by a check in AnalyzeImplicitConversions().
  6167. return DiagnoseImpCast(S, E, T, CC,
  6168. diag::warn_impcast_string_literal_to_bool);
  6169. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  6170. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  6171. // This covers the literal expressions that evaluate to Objective-C
  6172. // objects.
  6173. return DiagnoseImpCast(S, E, T, CC,
  6174. diag::warn_impcast_objective_c_literal_to_bool);
  6175. }
  6176. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  6177. // Warn on pointer to bool conversion that is always true.
  6178. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  6179. SourceRange(CC));
  6180. }
  6181. }
  6182. // Check implicit casts from Objective-C collection literals to specialized
  6183. // collection types, e.g., NSArray<NSString *> *.
  6184. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  6185. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  6186. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  6187. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  6188. // Strip vector types.
  6189. if (isa<VectorType>(Source)) {
  6190. if (!isa<VectorType>(Target)) {
  6191. if (S.SourceMgr.isInSystemMacro(CC))
  6192. return;
  6193. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  6194. }
  6195. // If the vector cast is cast between two vectors of the same size, it is
  6196. // a bitcast, not a conversion.
  6197. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  6198. return;
  6199. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  6200. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  6201. }
  6202. if (auto VecTy = dyn_cast<VectorType>(Target))
  6203. Target = VecTy->getElementType().getTypePtr();
  6204. // Strip complex types.
  6205. if (isa<ComplexType>(Source)) {
  6206. if (!isa<ComplexType>(Target)) {
  6207. if (S.SourceMgr.isInSystemMacro(CC))
  6208. return;
  6209. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
  6210. }
  6211. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  6212. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  6213. }
  6214. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  6215. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  6216. // If the source is floating point...
  6217. if (SourceBT && SourceBT->isFloatingPoint()) {
  6218. // ...and the target is floating point...
  6219. if (TargetBT && TargetBT->isFloatingPoint()) {
  6220. // ...then warn if we're dropping FP rank.
  6221. // Builtin FP kinds are ordered by increasing FP rank.
  6222. if (SourceBT->getKind() > TargetBT->getKind()) {
  6223. // Don't warn about float constants that are precisely
  6224. // representable in the target type.
  6225. Expr::EvalResult result;
  6226. if (E->EvaluateAsRValue(result, S.Context)) {
  6227. // Value might be a float, a float vector, or a float complex.
  6228. if (IsSameFloatAfterCast(result.Val,
  6229. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  6230. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  6231. return;
  6232. }
  6233. if (S.SourceMgr.isInSystemMacro(CC))
  6234. return;
  6235. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  6236. }
  6237. return;
  6238. }
  6239. // If the target is integral, always warn.
  6240. if (TargetBT && TargetBT->isInteger()) {
  6241. if (S.SourceMgr.isInSystemMacro(CC))
  6242. return;
  6243. Expr *InnerE = E->IgnoreParenImpCasts();
  6244. // We also want to warn on, e.g., "int i = -1.234"
  6245. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  6246. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  6247. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  6248. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
  6249. DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
  6250. } else {
  6251. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
  6252. }
  6253. }
  6254. // If the target is bool, warn if expr is a function or method call.
  6255. if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
  6256. isa<CallExpr>(E)) {
  6257. // Check last argument of function call to see if it is an
  6258. // implicit cast from a type matching the type the result
  6259. // is being cast to.
  6260. CallExpr *CEx = cast<CallExpr>(E);
  6261. unsigned NumArgs = CEx->getNumArgs();
  6262. if (NumArgs > 0) {
  6263. Expr *LastA = CEx->getArg(NumArgs - 1);
  6264. Expr *InnerE = LastA->IgnoreParenImpCasts();
  6265. const Type *InnerType =
  6266. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  6267. if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
  6268. // Warn on this floating-point to bool conversion
  6269. DiagnoseImpCast(S, E, T, CC,
  6270. diag::warn_impcast_floating_point_to_bool);
  6271. }
  6272. }
  6273. }
  6274. return;
  6275. }
  6276. DiagnoseNullConversion(S, E, T, CC);
  6277. if (!Source->isIntegerType() || !Target->isIntegerType())
  6278. return;
  6279. // TODO: remove this early return once the false positives for constant->bool
  6280. // in templates, macros, etc, are reduced or removed.
  6281. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  6282. return;
  6283. IntRange SourceRange = GetExprRange(S.Context, E);
  6284. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  6285. if (SourceRange.Width > TargetRange.Width) {
  6286. // If the source is a constant, use a default-on diagnostic.
  6287. // TODO: this should happen for bitfield stores, too.
  6288. llvm::APSInt Value(32);
  6289. if (E->isIntegerConstantExpr(Value, S.Context)) {
  6290. if (S.SourceMgr.isInSystemMacro(CC))
  6291. return;
  6292. std::string PrettySourceValue = Value.toString(10);
  6293. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  6294. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  6295. S.PDiag(diag::warn_impcast_integer_precision_constant)
  6296. << PrettySourceValue << PrettyTargetValue
  6297. << E->getType() << T << E->getSourceRange()
  6298. << clang::SourceRange(CC));
  6299. return;
  6300. }
  6301. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  6302. if (S.SourceMgr.isInSystemMacro(CC))
  6303. return;
  6304. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  6305. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  6306. /* pruneControlFlow */ true);
  6307. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  6308. }
  6309. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  6310. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  6311. SourceRange.Width == TargetRange.Width)) {
  6312. if (S.SourceMgr.isInSystemMacro(CC))
  6313. return;
  6314. unsigned DiagID = diag::warn_impcast_integer_sign;
  6315. // Traditionally, gcc has warned about this under -Wsign-compare.
  6316. // We also want to warn about it in -Wconversion.
  6317. // So if -Wconversion is off, use a completely identical diagnostic
  6318. // in the sign-compare group.
  6319. // The conditional-checking code will
  6320. if (ICContext) {
  6321. DiagID = diag::warn_impcast_integer_sign_conditional;
  6322. *ICContext = true;
  6323. }
  6324. return DiagnoseImpCast(S, E, T, CC, DiagID);
  6325. }
  6326. // Diagnose conversions between different enumeration types.
  6327. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  6328. // type, to give us better diagnostics.
  6329. QualType SourceType = E->getType();
  6330. if (!S.getLangOpts().CPlusPlus) {
  6331. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  6332. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  6333. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  6334. SourceType = S.Context.getTypeDeclType(Enum);
  6335. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  6336. }
  6337. }
  6338. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  6339. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  6340. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  6341. TargetEnum->getDecl()->hasNameForLinkage() &&
  6342. SourceEnum != TargetEnum) {
  6343. if (S.SourceMgr.isInSystemMacro(CC))
  6344. return;
  6345. return DiagnoseImpCast(S, E, SourceType, T, CC,
  6346. diag::warn_impcast_different_enum_types);
  6347. }
  6348. return;
  6349. }
  6350. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  6351. SourceLocation CC, QualType T);
  6352. void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  6353. SourceLocation CC, bool &ICContext) {
  6354. E = E->IgnoreParenImpCasts();
  6355. if (isa<ConditionalOperator>(E))
  6356. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  6357. AnalyzeImplicitConversions(S, E, CC);
  6358. if (E->getType() != T)
  6359. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  6360. return;
  6361. }
  6362. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  6363. SourceLocation CC, QualType T) {
  6364. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  6365. bool Suspicious = false;
  6366. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  6367. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  6368. // If -Wconversion would have warned about either of the candidates
  6369. // for a signedness conversion to the context type...
  6370. if (!Suspicious) return;
  6371. // ...but it's currently ignored...
  6372. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  6373. return;
  6374. // ...then check whether it would have warned about either of the
  6375. // candidates for a signedness conversion to the condition type.
  6376. if (E->getType() == T) return;
  6377. Suspicious = false;
  6378. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  6379. E->getType(), CC, &Suspicious);
  6380. if (!Suspicious)
  6381. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  6382. E->getType(), CC, &Suspicious);
  6383. }
  6384. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  6385. /// Input argument E is a logical expression.
  6386. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  6387. if (S.getLangOpts().Bool)
  6388. return;
  6389. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  6390. }
  6391. /// AnalyzeImplicitConversions - Find and report any interesting
  6392. /// implicit conversions in the given expression. There are a couple
  6393. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  6394. void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
  6395. QualType T = OrigE->getType();
  6396. Expr *E = OrigE->IgnoreParenImpCasts();
  6397. if (E->isTypeDependent() || E->isValueDependent())
  6398. return;
  6399. // For conditional operators, we analyze the arguments as if they
  6400. // were being fed directly into the output.
  6401. if (isa<ConditionalOperator>(E)) {
  6402. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  6403. CheckConditionalOperator(S, CO, CC, T);
  6404. return;
  6405. }
  6406. // Check implicit argument conversions for function calls.
  6407. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  6408. CheckImplicitArgumentConversions(S, Call, CC);
  6409. // Go ahead and check any implicit conversions we might have skipped.
  6410. // The non-canonical typecheck is just an optimization;
  6411. // CheckImplicitConversion will filter out dead implicit conversions.
  6412. if (E->getType() != T)
  6413. CheckImplicitConversion(S, E, T, CC);
  6414. // Now continue drilling into this expression.
  6415. if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
  6416. if (POE->getResultExpr())
  6417. E = POE->getResultExpr();
  6418. }
  6419. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  6420. if (OVE->getSourceExpr())
  6421. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  6422. return;
  6423. }
  6424. // Skip past explicit casts.
  6425. if (isa<ExplicitCastExpr>(E)) {
  6426. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  6427. return AnalyzeImplicitConversions(S, E, CC);
  6428. }
  6429. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  6430. // Do a somewhat different check with comparison operators.
  6431. if (BO->isComparisonOp())
  6432. return AnalyzeComparison(S, BO);
  6433. // And with simple assignments.
  6434. if (BO->getOpcode() == BO_Assign)
  6435. return AnalyzeAssignment(S, BO);
  6436. }
  6437. // These break the otherwise-useful invariant below. Fortunately,
  6438. // we don't really need to recurse into them, because any internal
  6439. // expressions should have been analyzed already when they were
  6440. // built into statements.
  6441. if (isa<StmtExpr>(E)) return;
  6442. // Don't descend into unevaluated contexts.
  6443. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  6444. // Now just recurse over the expression's children.
  6445. CC = E->getExprLoc();
  6446. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  6447. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  6448. for (Stmt *SubStmt : E->children()) {
  6449. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  6450. if (!ChildExpr)
  6451. continue;
  6452. if (IsLogicalAndOperator &&
  6453. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  6454. // Ignore checking string literals that are in logical and operators.
  6455. // This is a common pattern for asserts.
  6456. continue;
  6457. AnalyzeImplicitConversions(S, ChildExpr, CC);
  6458. }
  6459. if (BO && BO->isLogicalOp()) {
  6460. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  6461. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  6462. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  6463. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  6464. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  6465. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  6466. }
  6467. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
  6468. if (U->getOpcode() == UO_LNot)
  6469. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  6470. }
  6471. } // end anonymous namespace
  6472. enum {
  6473. AddressOf,
  6474. FunctionPointer,
  6475. ArrayPointer
  6476. };
  6477. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  6478. // Returns true when emitting a warning about taking the address of a reference.
  6479. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  6480. PartialDiagnostic PD) {
  6481. E = E->IgnoreParenImpCasts();
  6482. const FunctionDecl *FD = nullptr;
  6483. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  6484. if (!DRE->getDecl()->getType()->isReferenceType())
  6485. return false;
  6486. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  6487. if (!M->getMemberDecl()->getType()->isReferenceType())
  6488. return false;
  6489. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  6490. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  6491. return false;
  6492. FD = Call->getDirectCallee();
  6493. } else {
  6494. return false;
  6495. }
  6496. SemaRef.Diag(E->getExprLoc(), PD);
  6497. // If possible, point to location of function.
  6498. if (FD) {
  6499. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  6500. }
  6501. return true;
  6502. }
  6503. // Returns true if the SourceLocation is expanded from any macro body.
  6504. // Returns false if the SourceLocation is invalid, is from not in a macro
  6505. // expansion, or is from expanded from a top-level macro argument.
  6506. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  6507. if (Loc.isInvalid())
  6508. return false;
  6509. while (Loc.isMacroID()) {
  6510. if (SM.isMacroBodyExpansion(Loc))
  6511. return true;
  6512. Loc = SM.getImmediateMacroCallerLoc(Loc);
  6513. }
  6514. return false;
  6515. }
  6516. /// \brief Diagnose pointers that are always non-null.
  6517. /// \param E the expression containing the pointer
  6518. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  6519. /// compared to a null pointer
  6520. /// \param IsEqual True when the comparison is equal to a null pointer
  6521. /// \param Range Extra SourceRange to highlight in the diagnostic
  6522. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  6523. Expr::NullPointerConstantKind NullKind,
  6524. bool IsEqual, SourceRange Range) {
  6525. if (!E)
  6526. return;
  6527. // Don't warn inside macros.
  6528. if (E->getExprLoc().isMacroID()) {
  6529. const SourceManager &SM = getSourceManager();
  6530. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  6531. IsInAnyMacroBody(SM, Range.getBegin()))
  6532. return;
  6533. }
  6534. E = E->IgnoreImpCasts();
  6535. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  6536. if (isa<CXXThisExpr>(E)) {
  6537. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  6538. : diag::warn_this_bool_conversion;
  6539. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  6540. return;
  6541. }
  6542. bool IsAddressOf = false;
  6543. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  6544. if (UO->getOpcode() != UO_AddrOf)
  6545. return;
  6546. IsAddressOf = true;
  6547. E = UO->getSubExpr();
  6548. }
  6549. if (IsAddressOf) {
  6550. unsigned DiagID = IsCompare
  6551. ? diag::warn_address_of_reference_null_compare
  6552. : diag::warn_address_of_reference_bool_conversion;
  6553. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  6554. << IsEqual;
  6555. if (CheckForReference(*this, E, PD)) {
  6556. return;
  6557. }
  6558. }
  6559. // Expect to find a single Decl. Skip anything more complicated.
  6560. ValueDecl *D = nullptr;
  6561. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  6562. D = R->getDecl();
  6563. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  6564. D = M->getMemberDecl();
  6565. }
  6566. // Weak Decls can be null.
  6567. if (!D || D->isWeak())
  6568. return;
  6569. // Check for parameter decl with nonnull attribute
  6570. if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
  6571. if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
  6572. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  6573. unsigned NumArgs = FD->getNumParams();
  6574. llvm::SmallBitVector AttrNonNull(NumArgs);
  6575. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  6576. if (!NonNull->args_size()) {
  6577. AttrNonNull.set(0, NumArgs);
  6578. break;
  6579. }
  6580. for (unsigned Val : NonNull->args()) {
  6581. if (Val >= NumArgs)
  6582. continue;
  6583. AttrNonNull.set(Val);
  6584. }
  6585. }
  6586. if (!AttrNonNull.empty())
  6587. for (unsigned i = 0; i < NumArgs; ++i)
  6588. if (FD->getParamDecl(i) == PV &&
  6589. (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
  6590. std::string Str;
  6591. llvm::raw_string_ostream S(Str);
  6592. E->printPretty(S, nullptr, getPrintingPolicy());
  6593. unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
  6594. : diag::warn_cast_nonnull_to_bool;
  6595. Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
  6596. << Range << IsEqual;
  6597. return;
  6598. }
  6599. }
  6600. }
  6601. QualType T = D->getType();
  6602. const bool IsArray = T->isArrayType();
  6603. const bool IsFunction = T->isFunctionType();
  6604. // Address of function is used to silence the function warning.
  6605. if (IsAddressOf && IsFunction) {
  6606. return;
  6607. }
  6608. // Found nothing.
  6609. if (!IsAddressOf && !IsFunction && !IsArray)
  6610. return;
  6611. // Pretty print the expression for the diagnostic.
  6612. std::string Str;
  6613. llvm::raw_string_ostream S(Str);
  6614. E->printPretty(S, nullptr, getPrintingPolicy());
  6615. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  6616. : diag::warn_impcast_pointer_to_bool;
  6617. unsigned DiagType;
  6618. if (IsAddressOf)
  6619. DiagType = AddressOf;
  6620. else if (IsFunction)
  6621. DiagType = FunctionPointer;
  6622. else if (IsArray)
  6623. DiagType = ArrayPointer;
  6624. else
  6625. llvm_unreachable("Could not determine diagnostic.");
  6626. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  6627. << Range << IsEqual;
  6628. if (!IsFunction)
  6629. return;
  6630. // Suggest '&' to silence the function warning.
  6631. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  6632. << FixItHint::CreateInsertion(E->getLocStart(), "&");
  6633. // Check to see if '()' fixit should be emitted.
  6634. QualType ReturnType;
  6635. UnresolvedSet<4> NonTemplateOverloads;
  6636. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  6637. if (ReturnType.isNull())
  6638. return;
  6639. if (IsCompare) {
  6640. // There are two cases here. If there is null constant, the only suggest
  6641. // for a pointer return type. If the null is 0, then suggest if the return
  6642. // type is a pointer or an integer type.
  6643. if (!ReturnType->isPointerType()) {
  6644. if (NullKind == Expr::NPCK_ZeroExpression ||
  6645. NullKind == Expr::NPCK_ZeroLiteral) {
  6646. if (!ReturnType->isIntegerType())
  6647. return;
  6648. } else {
  6649. return;
  6650. }
  6651. }
  6652. } else { // !IsCompare
  6653. // For function to bool, only suggest if the function pointer has bool
  6654. // return type.
  6655. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  6656. return;
  6657. }
  6658. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  6659. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
  6660. }
  6661. /// Diagnoses "dangerous" implicit conversions within the given
  6662. /// expression (which is a full expression). Implements -Wconversion
  6663. /// and -Wsign-compare.
  6664. ///
  6665. /// \param CC the "context" location of the implicit conversion, i.e.
  6666. /// the most location of the syntactic entity requiring the implicit
  6667. /// conversion
  6668. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  6669. // Don't diagnose in unevaluated contexts.
  6670. if (isUnevaluatedContext())
  6671. return;
  6672. // Don't diagnose for value- or type-dependent expressions.
  6673. if (E->isTypeDependent() || E->isValueDependent())
  6674. return;
  6675. // Check for array bounds violations in cases where the check isn't triggered
  6676. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  6677. // ArraySubscriptExpr is on the RHS of a variable initialization.
  6678. CheckArrayAccess(E);
  6679. // This is not the right CC for (e.g.) a variable initialization.
  6680. AnalyzeImplicitConversions(*this, E, CC);
  6681. }
  6682. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  6683. /// Input argument E is a logical expression.
  6684. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  6685. ::CheckBoolLikeConversion(*this, E, CC);
  6686. }
  6687. /// Diagnose when expression is an integer constant expression and its evaluation
  6688. /// results in integer overflow
  6689. void Sema::CheckForIntOverflow (Expr *E) {
  6690. if (isa<BinaryOperator>(E->IgnoreParenCasts()))
  6691. E->IgnoreParenCasts()->EvaluateForOverflow(Context);
  6692. }
  6693. namespace {
  6694. /// \brief Visitor for expressions which looks for unsequenced operations on the
  6695. /// same object.
  6696. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  6697. typedef EvaluatedExprVisitor<SequenceChecker> Base;
  6698. /// \brief A tree of sequenced regions within an expression. Two regions are
  6699. /// unsequenced if one is an ancestor or a descendent of the other. When we
  6700. /// finish processing an expression with sequencing, such as a comma
  6701. /// expression, we fold its tree nodes into its parent, since they are
  6702. /// unsequenced with respect to nodes we will visit later.
  6703. class SequenceTree {
  6704. struct Value {
  6705. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  6706. unsigned Parent : 31;
  6707. bool Merged : 1;
  6708. };
  6709. SmallVector<Value, 8> Values;
  6710. public:
  6711. /// \brief A region within an expression which may be sequenced with respect
  6712. /// to some other region.
  6713. class Seq {
  6714. explicit Seq(unsigned N) : Index(N) {}
  6715. unsigned Index;
  6716. friend class SequenceTree;
  6717. public:
  6718. Seq() : Index(0) {}
  6719. };
  6720. SequenceTree() { Values.push_back(Value(0)); }
  6721. Seq root() const { return Seq(0); }
  6722. /// \brief Create a new sequence of operations, which is an unsequenced
  6723. /// subset of \p Parent. This sequence of operations is sequenced with
  6724. /// respect to other children of \p Parent.
  6725. Seq allocate(Seq Parent) {
  6726. Values.push_back(Value(Parent.Index));
  6727. return Seq(Values.size() - 1);
  6728. }
  6729. /// \brief Merge a sequence of operations into its parent.
  6730. void merge(Seq S) {
  6731. Values[S.Index].Merged = true;
  6732. }
  6733. /// \brief Determine whether two operations are unsequenced. This operation
  6734. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  6735. /// should have been merged into its parent as appropriate.
  6736. bool isUnsequenced(Seq Cur, Seq Old) {
  6737. unsigned C = representative(Cur.Index);
  6738. unsigned Target = representative(Old.Index);
  6739. while (C >= Target) {
  6740. if (C == Target)
  6741. return true;
  6742. C = Values[C].Parent;
  6743. }
  6744. return false;
  6745. }
  6746. private:
  6747. /// \brief Pick a representative for a sequence.
  6748. unsigned representative(unsigned K) {
  6749. if (Values[K].Merged)
  6750. // Perform path compression as we go.
  6751. return Values[K].Parent = representative(Values[K].Parent);
  6752. return K;
  6753. }
  6754. };
  6755. /// An object for which we can track unsequenced uses.
  6756. typedef NamedDecl *Object;
  6757. /// Different flavors of object usage which we track. We only track the
  6758. /// least-sequenced usage of each kind.
  6759. enum UsageKind {
  6760. /// A read of an object. Multiple unsequenced reads are OK.
  6761. UK_Use,
  6762. /// A modification of an object which is sequenced before the value
  6763. /// computation of the expression, such as ++n in C++.
  6764. UK_ModAsValue,
  6765. /// A modification of an object which is not sequenced before the value
  6766. /// computation of the expression, such as n++.
  6767. UK_ModAsSideEffect,
  6768. UK_Count = UK_ModAsSideEffect + 1
  6769. };
  6770. struct Usage {
  6771. Usage() : Use(nullptr), Seq() {}
  6772. Expr *Use;
  6773. SequenceTree::Seq Seq;
  6774. };
  6775. struct UsageInfo {
  6776. UsageInfo() : Diagnosed(false) {}
  6777. Usage Uses[UK_Count];
  6778. /// Have we issued a diagnostic for this variable already?
  6779. bool Diagnosed;
  6780. };
  6781. typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
  6782. Sema &SemaRef;
  6783. /// Sequenced regions within the expression.
  6784. SequenceTree Tree;
  6785. /// Declaration modifications and references which we have seen.
  6786. UsageInfoMap UsageMap;
  6787. /// The region we are currently within.
  6788. SequenceTree::Seq Region;
  6789. /// Filled in with declarations which were modified as a side-effect
  6790. /// (that is, post-increment operations).
  6791. SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
  6792. /// Expressions to check later. We defer checking these to reduce
  6793. /// stack usage.
  6794. SmallVectorImpl<Expr *> &WorkList;
  6795. /// RAII object wrapping the visitation of a sequenced subexpression of an
  6796. /// expression. At the end of this process, the side-effects of the evaluation
  6797. /// become sequenced with respect to the value computation of the result, so
  6798. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  6799. /// UK_ModAsValue.
  6800. struct SequencedSubexpression {
  6801. SequencedSubexpression(SequenceChecker &Self)
  6802. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  6803. Self.ModAsSideEffect = &ModAsSideEffect;
  6804. }
  6805. ~SequencedSubexpression() {
  6806. for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
  6807. MI != ME; ++MI) {
  6808. UsageInfo &U = Self.UsageMap[MI->first];
  6809. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  6810. Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
  6811. SideEffectUsage = MI->second;
  6812. }
  6813. Self.ModAsSideEffect = OldModAsSideEffect;
  6814. }
  6815. SequenceChecker &Self;
  6816. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  6817. SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
  6818. };
  6819. /// RAII object wrapping the visitation of a subexpression which we might
  6820. /// choose to evaluate as a constant. If any subexpression is evaluated and
  6821. /// found to be non-constant, this allows us to suppress the evaluation of
  6822. /// the outer expression.
  6823. class EvaluationTracker {
  6824. public:
  6825. EvaluationTracker(SequenceChecker &Self)
  6826. : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
  6827. Self.EvalTracker = this;
  6828. }
  6829. ~EvaluationTracker() {
  6830. Self.EvalTracker = Prev;
  6831. if (Prev)
  6832. Prev->EvalOK &= EvalOK;
  6833. }
  6834. bool evaluate(const Expr *E, bool &Result) {
  6835. if (!EvalOK || E->isValueDependent())
  6836. return false;
  6837. EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
  6838. return EvalOK;
  6839. }
  6840. private:
  6841. SequenceChecker &Self;
  6842. EvaluationTracker *Prev;
  6843. bool EvalOK;
  6844. } *EvalTracker;
  6845. /// \brief Find the object which is produced by the specified expression,
  6846. /// if any.
  6847. Object getObject(Expr *E, bool Mod) const {
  6848. E = E->IgnoreParenCasts();
  6849. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  6850. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  6851. return getObject(UO->getSubExpr(), Mod);
  6852. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  6853. if (BO->getOpcode() == BO_Comma)
  6854. return getObject(BO->getRHS(), Mod);
  6855. if (Mod && BO->isAssignmentOp())
  6856. return getObject(BO->getLHS(), Mod);
  6857. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  6858. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  6859. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  6860. return ME->getMemberDecl();
  6861. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  6862. // FIXME: If this is a reference, map through to its value.
  6863. return DRE->getDecl();
  6864. return nullptr;
  6865. }
  6866. /// \brief Note that an object was modified or used by an expression.
  6867. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  6868. Usage &U = UI.Uses[UK];
  6869. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  6870. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  6871. ModAsSideEffect->push_back(std::make_pair(O, U));
  6872. U.Use = Ref;
  6873. U.Seq = Region;
  6874. }
  6875. }
  6876. /// \brief Check whether a modification or use conflicts with a prior usage.
  6877. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  6878. bool IsModMod) {
  6879. if (UI.Diagnosed)
  6880. return;
  6881. const Usage &U = UI.Uses[OtherKind];
  6882. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  6883. return;
  6884. Expr *Mod = U.Use;
  6885. Expr *ModOrUse = Ref;
  6886. if (OtherKind == UK_Use)
  6887. std::swap(Mod, ModOrUse);
  6888. SemaRef.Diag(Mod->getExprLoc(),
  6889. IsModMod ? diag::warn_unsequenced_mod_mod
  6890. : diag::warn_unsequenced_mod_use)
  6891. << O << SourceRange(ModOrUse->getExprLoc());
  6892. UI.Diagnosed = true;
  6893. }
  6894. void notePreUse(Object O, Expr *Use) {
  6895. UsageInfo &U = UsageMap[O];
  6896. // Uses conflict with other modifications.
  6897. checkUsage(O, U, Use, UK_ModAsValue, false);
  6898. }
  6899. void notePostUse(Object O, Expr *Use) {
  6900. UsageInfo &U = UsageMap[O];
  6901. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  6902. addUsage(U, O, Use, UK_Use);
  6903. }
  6904. void notePreMod(Object O, Expr *Mod) {
  6905. UsageInfo &U = UsageMap[O];
  6906. // Modifications conflict with other modifications and with uses.
  6907. checkUsage(O, U, Mod, UK_ModAsValue, true);
  6908. checkUsage(O, U, Mod, UK_Use, false);
  6909. }
  6910. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  6911. UsageInfo &U = UsageMap[O];
  6912. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  6913. addUsage(U, O, Use, UK);
  6914. }
  6915. public:
  6916. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  6917. : Base(S.Context), SemaRef(S), Region(Tree.root()),
  6918. ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
  6919. Visit(E);
  6920. }
  6921. void VisitStmt(Stmt *S) {
  6922. // Skip all statements which aren't expressions for now.
  6923. }
  6924. void VisitExpr(Expr *E) {
  6925. // By default, just recurse to evaluated subexpressions.
  6926. Base::VisitStmt(E);
  6927. }
  6928. void VisitCastExpr(CastExpr *E) {
  6929. Object O = Object();
  6930. if (E->getCastKind() == CK_LValueToRValue)
  6931. O = getObject(E->getSubExpr(), false);
  6932. if (O)
  6933. notePreUse(O, E);
  6934. VisitExpr(E);
  6935. if (O)
  6936. notePostUse(O, E);
  6937. }
  6938. void VisitBinComma(BinaryOperator *BO) {
  6939. // C++11 [expr.comma]p1:
  6940. // Every value computation and side effect associated with the left
  6941. // expression is sequenced before every value computation and side
  6942. // effect associated with the right expression.
  6943. SequenceTree::Seq LHS = Tree.allocate(Region);
  6944. SequenceTree::Seq RHS = Tree.allocate(Region);
  6945. SequenceTree::Seq OldRegion = Region;
  6946. {
  6947. SequencedSubexpression SeqLHS(*this);
  6948. Region = LHS;
  6949. Visit(BO->getLHS());
  6950. }
  6951. Region = RHS;
  6952. Visit(BO->getRHS());
  6953. Region = OldRegion;
  6954. // Forget that LHS and RHS are sequenced. They are both unsequenced
  6955. // with respect to other stuff.
  6956. Tree.merge(LHS);
  6957. Tree.merge(RHS);
  6958. }
  6959. void VisitBinAssign(BinaryOperator *BO) {
  6960. // The modification is sequenced after the value computation of the LHS
  6961. // and RHS, so check it before inspecting the operands and update the
  6962. // map afterwards.
  6963. Object O = getObject(BO->getLHS(), true);
  6964. if (!O)
  6965. return VisitExpr(BO);
  6966. notePreMod(O, BO);
  6967. // C++11 [expr.ass]p7:
  6968. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  6969. // only once.
  6970. //
  6971. // Therefore, for a compound assignment operator, O is considered used
  6972. // everywhere except within the evaluation of E1 itself.
  6973. if (isa<CompoundAssignOperator>(BO))
  6974. notePreUse(O, BO);
  6975. Visit(BO->getLHS());
  6976. if (isa<CompoundAssignOperator>(BO))
  6977. notePostUse(O, BO);
  6978. Visit(BO->getRHS());
  6979. // C++11 [expr.ass]p1:
  6980. // the assignment is sequenced [...] before the value computation of the
  6981. // assignment expression.
  6982. // C11 6.5.16/3 has no such rule.
  6983. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  6984. : UK_ModAsSideEffect);
  6985. }
  6986. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  6987. VisitBinAssign(CAO);
  6988. }
  6989. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  6990. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  6991. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  6992. Object O = getObject(UO->getSubExpr(), true);
  6993. if (!O)
  6994. return VisitExpr(UO);
  6995. notePreMod(O, UO);
  6996. Visit(UO->getSubExpr());
  6997. // C++11 [expr.pre.incr]p1:
  6998. // the expression ++x is equivalent to x+=1
  6999. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  7000. : UK_ModAsSideEffect);
  7001. }
  7002. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  7003. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  7004. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  7005. Object O = getObject(UO->getSubExpr(), true);
  7006. if (!O)
  7007. return VisitExpr(UO);
  7008. notePreMod(O, UO);
  7009. Visit(UO->getSubExpr());
  7010. notePostMod(O, UO, UK_ModAsSideEffect);
  7011. }
  7012. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  7013. void VisitBinLOr(BinaryOperator *BO) {
  7014. // The side-effects of the LHS of an '&&' are sequenced before the
  7015. // value computation of the RHS, and hence before the value computation
  7016. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  7017. // as if they were unconditionally sequenced.
  7018. EvaluationTracker Eval(*this);
  7019. {
  7020. SequencedSubexpression Sequenced(*this);
  7021. Visit(BO->getLHS());
  7022. }
  7023. bool Result;
  7024. if (Eval.evaluate(BO->getLHS(), Result)) {
  7025. if (!Result)
  7026. Visit(BO->getRHS());
  7027. } else {
  7028. // Check for unsequenced operations in the RHS, treating it as an
  7029. // entirely separate evaluation.
  7030. //
  7031. // FIXME: If there are operations in the RHS which are unsequenced
  7032. // with respect to operations outside the RHS, and those operations
  7033. // are unconditionally evaluated, diagnose them.
  7034. WorkList.push_back(BO->getRHS());
  7035. }
  7036. }
  7037. void VisitBinLAnd(BinaryOperator *BO) {
  7038. EvaluationTracker Eval(*this);
  7039. {
  7040. SequencedSubexpression Sequenced(*this);
  7041. Visit(BO->getLHS());
  7042. }
  7043. bool Result;
  7044. if (Eval.evaluate(BO->getLHS(), Result)) {
  7045. if (Result)
  7046. Visit(BO->getRHS());
  7047. } else {
  7048. WorkList.push_back(BO->getRHS());
  7049. }
  7050. }
  7051. // Only visit the condition, unless we can be sure which subexpression will
  7052. // be chosen.
  7053. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  7054. EvaluationTracker Eval(*this);
  7055. {
  7056. SequencedSubexpression Sequenced(*this);
  7057. Visit(CO->getCond());
  7058. }
  7059. bool Result;
  7060. if (Eval.evaluate(CO->getCond(), Result))
  7061. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  7062. else {
  7063. WorkList.push_back(CO->getTrueExpr());
  7064. WorkList.push_back(CO->getFalseExpr());
  7065. }
  7066. }
  7067. void VisitCallExpr(CallExpr *CE) {
  7068. // C++11 [intro.execution]p15:
  7069. // When calling a function [...], every value computation and side effect
  7070. // associated with any argument expression, or with the postfix expression
  7071. // designating the called function, is sequenced before execution of every
  7072. // expression or statement in the body of the function [and thus before
  7073. // the value computation of its result].
  7074. SequencedSubexpression Sequenced(*this);
  7075. Base::VisitCallExpr(CE);
  7076. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  7077. }
  7078. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  7079. // This is a call, so all subexpressions are sequenced before the result.
  7080. SequencedSubexpression Sequenced(*this);
  7081. if (!CCE->isListInitialization())
  7082. return VisitExpr(CCE);
  7083. // In C++11, list initializations are sequenced.
  7084. SmallVector<SequenceTree::Seq, 32> Elts;
  7085. SequenceTree::Seq Parent = Region;
  7086. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  7087. E = CCE->arg_end();
  7088. I != E; ++I) {
  7089. Region = Tree.allocate(Parent);
  7090. Elts.push_back(Region);
  7091. Visit(*I);
  7092. }
  7093. // Forget that the initializers are sequenced.
  7094. Region = Parent;
  7095. for (unsigned I = 0; I < Elts.size(); ++I)
  7096. Tree.merge(Elts[I]);
  7097. }
  7098. void VisitInitListExpr(InitListExpr *ILE) {
  7099. if (!SemaRef.getLangOpts().CPlusPlus11)
  7100. return VisitExpr(ILE);
  7101. // In C++11, list initializations are sequenced.
  7102. SmallVector<SequenceTree::Seq, 32> Elts;
  7103. SequenceTree::Seq Parent = Region;
  7104. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  7105. Expr *E = ILE->getInit(I);
  7106. if (!E) continue;
  7107. Region = Tree.allocate(Parent);
  7108. Elts.push_back(Region);
  7109. Visit(E);
  7110. }
  7111. // Forget that the initializers are sequenced.
  7112. Region = Parent;
  7113. for (unsigned I = 0; I < Elts.size(); ++I)
  7114. Tree.merge(Elts[I]);
  7115. }
  7116. };
  7117. }
  7118. void Sema::CheckUnsequencedOperations(Expr *E) {
  7119. SmallVector<Expr *, 8> WorkList;
  7120. WorkList.push_back(E);
  7121. while (!WorkList.empty()) {
  7122. Expr *Item = WorkList.pop_back_val();
  7123. SequenceChecker(*this, Item, WorkList);
  7124. }
  7125. }
  7126. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  7127. bool IsConstexpr) {
  7128. CheckImplicitConversions(E, CheckLoc);
  7129. CheckUnsequencedOperations(E);
  7130. if (!IsConstexpr && !E->isValueDependent())
  7131. CheckForIntOverflow(E);
  7132. }
  7133. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  7134. FieldDecl *BitField,
  7135. Expr *Init) {
  7136. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  7137. }
  7138. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  7139. SourceLocation Loc) {
  7140. if (!PType->isVariablyModifiedType())
  7141. return;
  7142. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  7143. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  7144. return;
  7145. }
  7146. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  7147. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  7148. return;
  7149. }
  7150. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  7151. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  7152. return;
  7153. }
  7154. const ArrayType *AT = S.Context.getAsArrayType(PType);
  7155. if (!AT)
  7156. return;
  7157. if (AT->getSizeModifier() != ArrayType::Star) {
  7158. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  7159. return;
  7160. }
  7161. S.Diag(Loc, diag::err_array_star_in_function_definition);
  7162. }
  7163. /// CheckParmsForFunctionDef - Check that the parameters of the given
  7164. /// function are appropriate for the definition of a function. This
  7165. /// takes care of any checks that cannot be performed on the
  7166. /// declaration itself, e.g., that the types of each of the function
  7167. /// parameters are complete.
  7168. bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
  7169. ParmVarDecl *const *PEnd,
  7170. bool CheckParameterNames) {
  7171. bool HasInvalidParm = false;
  7172. for (; P != PEnd; ++P) {
  7173. ParmVarDecl *Param = *P;
  7174. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  7175. // function declarator that is part of a function definition of
  7176. // that function shall not have incomplete type.
  7177. //
  7178. // This is also C++ [dcl.fct]p6.
  7179. if (!Param->isInvalidDecl() &&
  7180. RequireCompleteType(Param->getLocation(), Param->getType(),
  7181. diag::err_typecheck_decl_incomplete_type)) {
  7182. Param->setInvalidDecl();
  7183. HasInvalidParm = true;
  7184. }
  7185. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  7186. // declaration of each parameter shall include an identifier.
  7187. if (CheckParameterNames &&
  7188. Param->getIdentifier() == nullptr &&
  7189. !Param->isImplicit() &&
  7190. !getLangOpts().CPlusPlus)
  7191. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  7192. // C99 6.7.5.3p12:
  7193. // If the function declarator is not part of a definition of that
  7194. // function, parameters may have incomplete type and may use the [*]
  7195. // notation in their sequences of declarator specifiers to specify
  7196. // variable length array types.
  7197. QualType PType = Param->getOriginalType();
  7198. // FIXME: This diagnostic should point the '[*]' if source-location
  7199. // information is added for it.
  7200. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  7201. // MSVC destroys objects passed by value in the callee. Therefore a
  7202. // function definition which takes such a parameter must be able to call the
  7203. // object's destructor. However, we don't perform any direct access check
  7204. // on the dtor.
  7205. if (getLangOpts().CPlusPlus && Context.getTargetInfo()
  7206. .getCXXABI()
  7207. .areArgsDestroyedLeftToRightInCallee()) {
  7208. if (!Param->isInvalidDecl()) {
  7209. if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
  7210. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  7211. if (!ClassDecl->isInvalidDecl() &&
  7212. !ClassDecl->hasIrrelevantDestructor() &&
  7213. !ClassDecl->isDependentContext()) {
  7214. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  7215. MarkFunctionReferenced(Param->getLocation(), Destructor);
  7216. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  7217. }
  7218. }
  7219. }
  7220. }
  7221. }
  7222. return HasInvalidParm;
  7223. }
  7224. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  7225. /// pointer cast increases the alignment requirements.
  7226. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  7227. // This is actually a lot of work to potentially be doing on every
  7228. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  7229. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  7230. return;
  7231. // Ignore dependent types.
  7232. if (T->isDependentType() || Op->getType()->isDependentType())
  7233. return;
  7234. // Require that the destination be a pointer type.
  7235. const PointerType *DestPtr = T->getAs<PointerType>();
  7236. if (!DestPtr) return;
  7237. // If the destination has alignment 1, we're done.
  7238. QualType DestPointee = DestPtr->getPointeeType();
  7239. if (DestPointee->isIncompleteType()) return;
  7240. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  7241. if (DestAlign.isOne()) return;
  7242. // Require that the source be a pointer type.
  7243. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  7244. if (!SrcPtr) return;
  7245. QualType SrcPointee = SrcPtr->getPointeeType();
  7246. // Whitelist casts from cv void*. We already implicitly
  7247. // whitelisted casts to cv void*, since they have alignment 1.
  7248. // Also whitelist casts involving incomplete types, which implicitly
  7249. // includes 'void'.
  7250. if (SrcPointee->isIncompleteType()) return;
  7251. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  7252. if (SrcAlign >= DestAlign) return;
  7253. Diag(TRange.getBegin(), diag::warn_cast_align)
  7254. << Op->getType() << T
  7255. << static_cast<unsigned>(SrcAlign.getQuantity())
  7256. << static_cast<unsigned>(DestAlign.getQuantity())
  7257. << TRange << Op->getSourceRange();
  7258. }
  7259. static const Type* getElementType(const Expr *BaseExpr) {
  7260. const Type* EltType = BaseExpr->getType().getTypePtr();
  7261. if (EltType->isAnyPointerType())
  7262. return EltType->getPointeeType().getTypePtr();
  7263. else if (EltType->isArrayType())
  7264. return EltType->getBaseElementTypeUnsafe();
  7265. return EltType;
  7266. }
  7267. /// \brief Check whether this array fits the idiom of a size-one tail padded
  7268. /// array member of a struct.
  7269. ///
  7270. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  7271. /// commonly used to emulate flexible arrays in C89 code.
  7272. static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
  7273. const NamedDecl *ND) {
  7274. if (Size != 1 || !ND) return false;
  7275. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  7276. if (!FD) return false;
  7277. // Don't consider sizes resulting from macro expansions or template argument
  7278. // substitution to form C89 tail-padded arrays.
  7279. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  7280. while (TInfo) {
  7281. TypeLoc TL = TInfo->getTypeLoc();
  7282. // Look through typedefs.
  7283. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  7284. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  7285. TInfo = TDL->getTypeSourceInfo();
  7286. continue;
  7287. }
  7288. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  7289. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  7290. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  7291. return false;
  7292. }
  7293. break;
  7294. }
  7295. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  7296. if (!RD) return false;
  7297. if (RD->isUnion()) return false;
  7298. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  7299. if (!CRD->isStandardLayout()) return false;
  7300. }
  7301. // See if this is the last field decl in the record.
  7302. const Decl *D = FD;
  7303. while ((D = D->getNextDeclInContext()))
  7304. if (isa<FieldDecl>(D))
  7305. return false;
  7306. return true;
  7307. }
  7308. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  7309. const ArraySubscriptExpr *ASE,
  7310. bool AllowOnePastEnd, bool IndexNegated) {
  7311. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  7312. if (IndexExpr->isValueDependent())
  7313. return;
  7314. const Type *EffectiveType = getElementType(BaseExpr);
  7315. BaseExpr = BaseExpr->IgnoreParenCasts();
  7316. const ConstantArrayType *ArrayTy =
  7317. Context.getAsConstantArrayType(BaseExpr->getType());
  7318. if (!ArrayTy)
  7319. return;
  7320. llvm::APSInt index;
  7321. if (!IndexExpr->EvaluateAsInt(index, Context))
  7322. return;
  7323. if (IndexNegated)
  7324. index = -index;
  7325. const NamedDecl *ND = nullptr;
  7326. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  7327. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  7328. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  7329. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  7330. if (index.isUnsigned() || !index.isNegative()) {
  7331. llvm::APInt size = ArrayTy->getSize();
  7332. if (!size.isStrictlyPositive())
  7333. return;
  7334. const Type* BaseType = getElementType(BaseExpr);
  7335. if (BaseType != EffectiveType) {
  7336. // Make sure we're comparing apples to apples when comparing index to size
  7337. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  7338. uint64_t array_typesize = Context.getTypeSize(BaseType);
  7339. // Handle ptrarith_typesize being zero, such as when casting to void*
  7340. if (!ptrarith_typesize) ptrarith_typesize = 1;
  7341. if (ptrarith_typesize != array_typesize) {
  7342. // There's a cast to a different size type involved
  7343. uint64_t ratio = array_typesize / ptrarith_typesize;
  7344. // TODO: Be smarter about handling cases where array_typesize is not a
  7345. // multiple of ptrarith_typesize
  7346. if (ptrarith_typesize * ratio == array_typesize)
  7347. size *= llvm::APInt(size.getBitWidth(), ratio);
  7348. }
  7349. }
  7350. if (size.getBitWidth() > index.getBitWidth())
  7351. index = index.zext(size.getBitWidth());
  7352. else if (size.getBitWidth() < index.getBitWidth())
  7353. size = size.zext(index.getBitWidth());
  7354. // For array subscripting the index must be less than size, but for pointer
  7355. // arithmetic also allow the index (offset) to be equal to size since
  7356. // computing the next address after the end of the array is legal and
  7357. // commonly done e.g. in C++ iterators and range-based for loops.
  7358. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  7359. return;
  7360. // Also don't warn for arrays of size 1 which are members of some
  7361. // structure. These are often used to approximate flexible arrays in C89
  7362. // code.
  7363. if (IsTailPaddedMemberArray(*this, size, ND))
  7364. return;
  7365. // Suppress the warning if the subscript expression (as identified by the
  7366. // ']' location) and the index expression are both from macro expansions
  7367. // within a system header.
  7368. if (ASE) {
  7369. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  7370. ASE->getRBracketLoc());
  7371. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  7372. SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
  7373. IndexExpr->getLocStart());
  7374. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  7375. return;
  7376. }
  7377. }
  7378. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  7379. if (ASE)
  7380. DiagID = diag::warn_array_index_exceeds_bounds;
  7381. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  7382. PDiag(DiagID) << index.toString(10, true)
  7383. << size.toString(10, true)
  7384. << (unsigned)size.getLimitedValue(~0U)
  7385. << IndexExpr->getSourceRange());
  7386. } else {
  7387. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  7388. if (!ASE) {
  7389. DiagID = diag::warn_ptr_arith_precedes_bounds;
  7390. if (index.isNegative()) index = -index;
  7391. }
  7392. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  7393. PDiag(DiagID) << index.toString(10, true)
  7394. << IndexExpr->getSourceRange());
  7395. }
  7396. if (!ND) {
  7397. // Try harder to find a NamedDecl to point at in the note.
  7398. while (const ArraySubscriptExpr *ASE =
  7399. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  7400. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  7401. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  7402. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  7403. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  7404. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  7405. }
  7406. if (ND)
  7407. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  7408. PDiag(diag::note_array_index_out_of_bounds)
  7409. << ND->getDeclName());
  7410. }
  7411. void Sema::CheckArrayAccess(const Expr *expr) {
  7412. int AllowOnePastEnd = 0;
  7413. while (expr) {
  7414. expr = expr->IgnoreParenImpCasts();
  7415. switch (expr->getStmtClass()) {
  7416. case Stmt::ArraySubscriptExprClass: {
  7417. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  7418. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  7419. AllowOnePastEnd > 0);
  7420. return;
  7421. }
  7422. case Stmt::OMPArraySectionExprClass: {
  7423. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  7424. if (ASE->getLowerBound())
  7425. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  7426. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  7427. return;
  7428. }
  7429. case Stmt::UnaryOperatorClass: {
  7430. // Only unwrap the * and & unary operators
  7431. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  7432. expr = UO->getSubExpr();
  7433. switch (UO->getOpcode()) {
  7434. case UO_AddrOf:
  7435. AllowOnePastEnd++;
  7436. break;
  7437. case UO_Deref:
  7438. AllowOnePastEnd--;
  7439. break;
  7440. default:
  7441. return;
  7442. }
  7443. break;
  7444. }
  7445. case Stmt::ConditionalOperatorClass: {
  7446. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  7447. if (const Expr *lhs = cond->getLHS())
  7448. CheckArrayAccess(lhs);
  7449. if (const Expr *rhs = cond->getRHS())
  7450. CheckArrayAccess(rhs);
  7451. return;
  7452. }
  7453. default:
  7454. return;
  7455. }
  7456. }
  7457. }
  7458. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  7459. namespace {
  7460. struct RetainCycleOwner {
  7461. RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
  7462. VarDecl *Variable;
  7463. SourceRange Range;
  7464. SourceLocation Loc;
  7465. bool Indirect;
  7466. void setLocsFrom(Expr *e) {
  7467. Loc = e->getExprLoc();
  7468. Range = e->getSourceRange();
  7469. }
  7470. };
  7471. }
  7472. /// Consider whether capturing the given variable can possibly lead to
  7473. /// a retain cycle.
  7474. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  7475. // In ARC, it's captured strongly iff the variable has __strong
  7476. // lifetime. In MRR, it's captured strongly if the variable is
  7477. // __block and has an appropriate type.
  7478. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  7479. return false;
  7480. owner.Variable = var;
  7481. if (ref)
  7482. owner.setLocsFrom(ref);
  7483. return true;
  7484. }
  7485. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  7486. while (true) {
  7487. e = e->IgnoreParens();
  7488. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  7489. switch (cast->getCastKind()) {
  7490. case CK_BitCast:
  7491. case CK_LValueBitCast:
  7492. case CK_LValueToRValue:
  7493. case CK_ARCReclaimReturnedObject:
  7494. e = cast->getSubExpr();
  7495. continue;
  7496. default:
  7497. return false;
  7498. }
  7499. }
  7500. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  7501. ObjCIvarDecl *ivar = ref->getDecl();
  7502. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  7503. return false;
  7504. // Try to find a retain cycle in the base.
  7505. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  7506. return false;
  7507. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  7508. owner.Indirect = true;
  7509. return true;
  7510. }
  7511. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  7512. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  7513. if (!var) return false;
  7514. return considerVariable(var, ref, owner);
  7515. }
  7516. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  7517. if (member->isArrow()) return false;
  7518. // Don't count this as an indirect ownership.
  7519. e = member->getBase();
  7520. continue;
  7521. }
  7522. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  7523. // Only pay attention to pseudo-objects on property references.
  7524. ObjCPropertyRefExpr *pre
  7525. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  7526. ->IgnoreParens());
  7527. if (!pre) return false;
  7528. if (pre->isImplicitProperty()) return false;
  7529. ObjCPropertyDecl *property = pre->getExplicitProperty();
  7530. if (!property->isRetaining() &&
  7531. !(property->getPropertyIvarDecl() &&
  7532. property->getPropertyIvarDecl()->getType()
  7533. .getObjCLifetime() == Qualifiers::OCL_Strong))
  7534. return false;
  7535. owner.Indirect = true;
  7536. if (pre->isSuperReceiver()) {
  7537. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  7538. if (!owner.Variable)
  7539. return false;
  7540. owner.Loc = pre->getLocation();
  7541. owner.Range = pre->getSourceRange();
  7542. return true;
  7543. }
  7544. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  7545. ->getSourceExpr());
  7546. continue;
  7547. }
  7548. // Array ivars?
  7549. return false;
  7550. }
  7551. }
  7552. namespace {
  7553. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  7554. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  7555. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  7556. Context(Context), Variable(variable), Capturer(nullptr),
  7557. VarWillBeReased(false) {}
  7558. ASTContext &Context;
  7559. VarDecl *Variable;
  7560. Expr *Capturer;
  7561. bool VarWillBeReased;
  7562. void VisitDeclRefExpr(DeclRefExpr *ref) {
  7563. if (ref->getDecl() == Variable && !Capturer)
  7564. Capturer = ref;
  7565. }
  7566. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  7567. if (Capturer) return;
  7568. Visit(ref->getBase());
  7569. if (Capturer && ref->isFreeIvar())
  7570. Capturer = ref;
  7571. }
  7572. void VisitBlockExpr(BlockExpr *block) {
  7573. // Look inside nested blocks
  7574. if (block->getBlockDecl()->capturesVariable(Variable))
  7575. Visit(block->getBlockDecl()->getBody());
  7576. }
  7577. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  7578. if (Capturer) return;
  7579. if (OVE->getSourceExpr())
  7580. Visit(OVE->getSourceExpr());
  7581. }
  7582. void VisitBinaryOperator(BinaryOperator *BinOp) {
  7583. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  7584. return;
  7585. Expr *LHS = BinOp->getLHS();
  7586. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  7587. if (DRE->getDecl() != Variable)
  7588. return;
  7589. if (Expr *RHS = BinOp->getRHS()) {
  7590. RHS = RHS->IgnoreParenCasts();
  7591. llvm::APSInt Value;
  7592. VarWillBeReased =
  7593. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  7594. }
  7595. }
  7596. }
  7597. };
  7598. }
  7599. /// Check whether the given argument is a block which captures a
  7600. /// variable.
  7601. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  7602. assert(owner.Variable && owner.Loc.isValid());
  7603. e = e->IgnoreParenCasts();
  7604. // Look through [^{...} copy] and Block_copy(^{...}).
  7605. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  7606. Selector Cmd = ME->getSelector();
  7607. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  7608. e = ME->getInstanceReceiver();
  7609. if (!e)
  7610. return nullptr;
  7611. e = e->IgnoreParenCasts();
  7612. }
  7613. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  7614. if (CE->getNumArgs() == 1) {
  7615. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  7616. if (Fn) {
  7617. const IdentifierInfo *FnI = Fn->getIdentifier();
  7618. if (FnI && FnI->isStr("_Block_copy")) {
  7619. e = CE->getArg(0)->IgnoreParenCasts();
  7620. }
  7621. }
  7622. }
  7623. }
  7624. BlockExpr *block = dyn_cast<BlockExpr>(e);
  7625. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  7626. return nullptr;
  7627. FindCaptureVisitor visitor(S.Context, owner.Variable);
  7628. visitor.Visit(block->getBlockDecl()->getBody());
  7629. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  7630. }
  7631. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  7632. RetainCycleOwner &owner) {
  7633. assert(capturer);
  7634. assert(owner.Variable && owner.Loc.isValid());
  7635. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  7636. << owner.Variable << capturer->getSourceRange();
  7637. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  7638. << owner.Indirect << owner.Range;
  7639. }
  7640. /// Check for a keyword selector that starts with the word 'add' or
  7641. /// 'set'.
  7642. static bool isSetterLikeSelector(Selector sel) {
  7643. if (sel.isUnarySelector()) return false;
  7644. StringRef str = sel.getNameForSlot(0);
  7645. while (!str.empty() && str.front() == '_') str = str.substr(1);
  7646. if (str.startswith("set"))
  7647. str = str.substr(3);
  7648. else if (str.startswith("add")) {
  7649. // Specially whitelist 'addOperationWithBlock:'.
  7650. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  7651. return false;
  7652. str = str.substr(3);
  7653. }
  7654. else
  7655. return false;
  7656. if (str.empty()) return true;
  7657. return !isLowercase(str.front());
  7658. }
  7659. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  7660. ObjCMessageExpr *Message) {
  7661. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  7662. Message->getReceiverInterface(),
  7663. NSAPI::ClassId_NSMutableArray);
  7664. if (!IsMutableArray) {
  7665. return None;
  7666. }
  7667. Selector Sel = Message->getSelector();
  7668. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  7669. S.NSAPIObj->getNSArrayMethodKind(Sel);
  7670. if (!MKOpt) {
  7671. return None;
  7672. }
  7673. NSAPI::NSArrayMethodKind MK = *MKOpt;
  7674. switch (MK) {
  7675. case NSAPI::NSMutableArr_addObject:
  7676. case NSAPI::NSMutableArr_insertObjectAtIndex:
  7677. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  7678. return 0;
  7679. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  7680. return 1;
  7681. default:
  7682. return None;
  7683. }
  7684. return None;
  7685. }
  7686. static
  7687. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  7688. ObjCMessageExpr *Message) {
  7689. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  7690. Message->getReceiverInterface(),
  7691. NSAPI::ClassId_NSMutableDictionary);
  7692. if (!IsMutableDictionary) {
  7693. return None;
  7694. }
  7695. Selector Sel = Message->getSelector();
  7696. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  7697. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  7698. if (!MKOpt) {
  7699. return None;
  7700. }
  7701. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  7702. switch (MK) {
  7703. case NSAPI::NSMutableDict_setObjectForKey:
  7704. case NSAPI::NSMutableDict_setValueForKey:
  7705. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  7706. return 0;
  7707. default:
  7708. return None;
  7709. }
  7710. return None;
  7711. }
  7712. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  7713. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  7714. Message->getReceiverInterface(),
  7715. NSAPI::ClassId_NSMutableSet);
  7716. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  7717. Message->getReceiverInterface(),
  7718. NSAPI::ClassId_NSMutableOrderedSet);
  7719. if (!IsMutableSet && !IsMutableOrderedSet) {
  7720. return None;
  7721. }
  7722. Selector Sel = Message->getSelector();
  7723. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  7724. if (!MKOpt) {
  7725. return None;
  7726. }
  7727. NSAPI::NSSetMethodKind MK = *MKOpt;
  7728. switch (MK) {
  7729. case NSAPI::NSMutableSet_addObject:
  7730. case NSAPI::NSOrderedSet_setObjectAtIndex:
  7731. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  7732. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  7733. return 0;
  7734. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  7735. return 1;
  7736. }
  7737. return None;
  7738. }
  7739. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  7740. if (!Message->isInstanceMessage()) {
  7741. return;
  7742. }
  7743. Optional<int> ArgOpt;
  7744. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  7745. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  7746. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  7747. return;
  7748. }
  7749. int ArgIndex = *ArgOpt;
  7750. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  7751. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  7752. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  7753. }
  7754. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  7755. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  7756. if (ArgRE->isObjCSelfExpr()) {
  7757. Diag(Message->getSourceRange().getBegin(),
  7758. diag::warn_objc_circular_container)
  7759. << ArgRE->getDecl()->getName() << StringRef("super");
  7760. }
  7761. }
  7762. } else {
  7763. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  7764. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  7765. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  7766. }
  7767. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  7768. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  7769. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  7770. ValueDecl *Decl = ReceiverRE->getDecl();
  7771. Diag(Message->getSourceRange().getBegin(),
  7772. diag::warn_objc_circular_container)
  7773. << Decl->getName() << Decl->getName();
  7774. if (!ArgRE->isObjCSelfExpr()) {
  7775. Diag(Decl->getLocation(),
  7776. diag::note_objc_circular_container_declared_here)
  7777. << Decl->getName();
  7778. }
  7779. }
  7780. }
  7781. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  7782. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  7783. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  7784. ObjCIvarDecl *Decl = IvarRE->getDecl();
  7785. Diag(Message->getSourceRange().getBegin(),
  7786. diag::warn_objc_circular_container)
  7787. << Decl->getName() << Decl->getName();
  7788. Diag(Decl->getLocation(),
  7789. diag::note_objc_circular_container_declared_here)
  7790. << Decl->getName();
  7791. }
  7792. }
  7793. }
  7794. }
  7795. }
  7796. /// Check a message send to see if it's likely to cause a retain cycle.
  7797. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  7798. // Only check instance methods whose selector looks like a setter.
  7799. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  7800. return;
  7801. // Try to find a variable that the receiver is strongly owned by.
  7802. RetainCycleOwner owner;
  7803. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  7804. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  7805. return;
  7806. } else {
  7807. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  7808. owner.Variable = getCurMethodDecl()->getSelfDecl();
  7809. owner.Loc = msg->getSuperLoc();
  7810. owner.Range = msg->getSuperLoc();
  7811. }
  7812. // Check whether the receiver is captured by any of the arguments.
  7813. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
  7814. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
  7815. return diagnoseRetainCycle(*this, capturer, owner);
  7816. }
  7817. /// Check a property assign to see if it's likely to cause a retain cycle.
  7818. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  7819. RetainCycleOwner owner;
  7820. if (!findRetainCycleOwner(*this, receiver, owner))
  7821. return;
  7822. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  7823. diagnoseRetainCycle(*this, capturer, owner);
  7824. }
  7825. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  7826. RetainCycleOwner Owner;
  7827. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  7828. return;
  7829. // Because we don't have an expression for the variable, we have to set the
  7830. // location explicitly here.
  7831. Owner.Loc = Var->getLocation();
  7832. Owner.Range = Var->getSourceRange();
  7833. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  7834. diagnoseRetainCycle(*this, Capturer, Owner);
  7835. }
  7836. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  7837. Expr *RHS, bool isProperty) {
  7838. // Check if RHS is an Objective-C object literal, which also can get
  7839. // immediately zapped in a weak reference. Note that we explicitly
  7840. // allow ObjCStringLiterals, since those are designed to never really die.
  7841. RHS = RHS->IgnoreParenImpCasts();
  7842. // This enum needs to match with the 'select' in
  7843. // warn_objc_arc_literal_assign (off-by-1).
  7844. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  7845. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  7846. return false;
  7847. S.Diag(Loc, diag::warn_arc_literal_assign)
  7848. << (unsigned) Kind
  7849. << (isProperty ? 0 : 1)
  7850. << RHS->getSourceRange();
  7851. return true;
  7852. }
  7853. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  7854. Qualifiers::ObjCLifetime LT,
  7855. Expr *RHS, bool isProperty) {
  7856. // Strip off any implicit cast added to get to the one ARC-specific.
  7857. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  7858. if (cast->getCastKind() == CK_ARCConsumeObject) {
  7859. S.Diag(Loc, diag::warn_arc_retained_assign)
  7860. << (LT == Qualifiers::OCL_ExplicitNone)
  7861. << (isProperty ? 0 : 1)
  7862. << RHS->getSourceRange();
  7863. return true;
  7864. }
  7865. RHS = cast->getSubExpr();
  7866. }
  7867. if (LT == Qualifiers::OCL_Weak &&
  7868. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  7869. return true;
  7870. return false;
  7871. }
  7872. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  7873. QualType LHS, Expr *RHS) {
  7874. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  7875. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  7876. return false;
  7877. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  7878. return true;
  7879. return false;
  7880. }
  7881. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  7882. Expr *LHS, Expr *RHS) {
  7883. QualType LHSType;
  7884. // PropertyRef on LHS type need be directly obtained from
  7885. // its declaration as it has a PseudoType.
  7886. ObjCPropertyRefExpr *PRE
  7887. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  7888. if (PRE && !PRE->isImplicitProperty()) {
  7889. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  7890. if (PD)
  7891. LHSType = PD->getType();
  7892. }
  7893. if (LHSType.isNull())
  7894. LHSType = LHS->getType();
  7895. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  7896. if (LT == Qualifiers::OCL_Weak) {
  7897. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  7898. getCurFunction()->markSafeWeakUse(LHS);
  7899. }
  7900. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  7901. return;
  7902. // FIXME. Check for other life times.
  7903. if (LT != Qualifiers::OCL_None)
  7904. return;
  7905. if (PRE) {
  7906. if (PRE->isImplicitProperty())
  7907. return;
  7908. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  7909. if (!PD)
  7910. return;
  7911. unsigned Attributes = PD->getPropertyAttributes();
  7912. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  7913. // when 'assign' attribute was not explicitly specified
  7914. // by user, ignore it and rely on property type itself
  7915. // for lifetime info.
  7916. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  7917. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  7918. LHSType->isObjCRetainableType())
  7919. return;
  7920. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  7921. if (cast->getCastKind() == CK_ARCConsumeObject) {
  7922. Diag(Loc, diag::warn_arc_retained_property_assign)
  7923. << RHS->getSourceRange();
  7924. return;
  7925. }
  7926. RHS = cast->getSubExpr();
  7927. }
  7928. }
  7929. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  7930. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  7931. return;
  7932. }
  7933. }
  7934. }
  7935. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  7936. namespace {
  7937. bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  7938. SourceLocation StmtLoc,
  7939. const NullStmt *Body) {
  7940. // Do not warn if the body is a macro that expands to nothing, e.g:
  7941. //
  7942. // #define CALL(x)
  7943. // if (condition)
  7944. // CALL(0);
  7945. //
  7946. if (Body->hasLeadingEmptyMacro())
  7947. return false;
  7948. // Get line numbers of statement and body.
  7949. bool StmtLineInvalid;
  7950. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  7951. &StmtLineInvalid);
  7952. if (StmtLineInvalid)
  7953. return false;
  7954. bool BodyLineInvalid;
  7955. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  7956. &BodyLineInvalid);
  7957. if (BodyLineInvalid)
  7958. return false;
  7959. // Warn if null statement and body are on the same line.
  7960. if (StmtLine != BodyLine)
  7961. return false;
  7962. return true;
  7963. }
  7964. } // Unnamed namespace
  7965. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  7966. const Stmt *Body,
  7967. unsigned DiagID) {
  7968. // Since this is a syntactic check, don't emit diagnostic for template
  7969. // instantiations, this just adds noise.
  7970. if (CurrentInstantiationScope)
  7971. return;
  7972. // The body should be a null statement.
  7973. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  7974. if (!NBody)
  7975. return;
  7976. // Do the usual checks.
  7977. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  7978. return;
  7979. Diag(NBody->getSemiLoc(), DiagID);
  7980. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  7981. }
  7982. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  7983. const Stmt *PossibleBody) {
  7984. assert(!CurrentInstantiationScope); // Ensured by caller
  7985. SourceLocation StmtLoc;
  7986. const Stmt *Body;
  7987. unsigned DiagID;
  7988. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  7989. StmtLoc = FS->getRParenLoc();
  7990. Body = FS->getBody();
  7991. DiagID = diag::warn_empty_for_body;
  7992. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  7993. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  7994. Body = WS->getBody();
  7995. DiagID = diag::warn_empty_while_body;
  7996. } else
  7997. return; // Neither `for' nor `while'.
  7998. // The body should be a null statement.
  7999. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  8000. if (!NBody)
  8001. return;
  8002. // Skip expensive checks if diagnostic is disabled.
  8003. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  8004. return;
  8005. // Do the usual checks.
  8006. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  8007. return;
  8008. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  8009. // noise level low, emit diagnostics only if for/while is followed by a
  8010. // CompoundStmt, e.g.:
  8011. // for (int i = 0; i < n; i++);
  8012. // {
  8013. // a(i);
  8014. // }
  8015. // or if for/while is followed by a statement with more indentation
  8016. // than for/while itself:
  8017. // for (int i = 0; i < n; i++);
  8018. // a(i);
  8019. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  8020. if (!ProbableTypo) {
  8021. bool BodyColInvalid;
  8022. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  8023. PossibleBody->getLocStart(),
  8024. &BodyColInvalid);
  8025. if (BodyColInvalid)
  8026. return;
  8027. bool StmtColInvalid;
  8028. unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
  8029. S->getLocStart(),
  8030. &StmtColInvalid);
  8031. if (StmtColInvalid)
  8032. return;
  8033. if (BodyCol > StmtCol)
  8034. ProbableTypo = true;
  8035. }
  8036. if (ProbableTypo) {
  8037. Diag(NBody->getSemiLoc(), DiagID);
  8038. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  8039. }
  8040. }
  8041. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  8042. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  8043. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  8044. SourceLocation OpLoc) {
  8045. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  8046. return;
  8047. if (!ActiveTemplateInstantiations.empty())
  8048. return;
  8049. // Strip parens and casts away.
  8050. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  8051. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  8052. // Check for a call expression
  8053. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  8054. if (!CE || CE->getNumArgs() != 1)
  8055. return;
  8056. // Check for a call to std::move
  8057. const FunctionDecl *FD = CE->getDirectCallee();
  8058. if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
  8059. !FD->getIdentifier()->isStr("move"))
  8060. return;
  8061. // Get argument from std::move
  8062. RHSExpr = CE->getArg(0);
  8063. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  8064. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  8065. // Two DeclRefExpr's, check that the decls are the same.
  8066. if (LHSDeclRef && RHSDeclRef) {
  8067. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  8068. return;
  8069. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  8070. RHSDeclRef->getDecl()->getCanonicalDecl())
  8071. return;
  8072. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  8073. << LHSExpr->getSourceRange()
  8074. << RHSExpr->getSourceRange();
  8075. return;
  8076. }
  8077. // Member variables require a different approach to check for self moves.
  8078. // MemberExpr's are the same if every nested MemberExpr refers to the same
  8079. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  8080. // the base Expr's are CXXThisExpr's.
  8081. const Expr *LHSBase = LHSExpr;
  8082. const Expr *RHSBase = RHSExpr;
  8083. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  8084. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  8085. if (!LHSME || !RHSME)
  8086. return;
  8087. while (LHSME && RHSME) {
  8088. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  8089. RHSME->getMemberDecl()->getCanonicalDecl())
  8090. return;
  8091. LHSBase = LHSME->getBase();
  8092. RHSBase = RHSME->getBase();
  8093. LHSME = dyn_cast<MemberExpr>(LHSBase);
  8094. RHSME = dyn_cast<MemberExpr>(RHSBase);
  8095. }
  8096. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  8097. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  8098. if (LHSDeclRef && RHSDeclRef) {
  8099. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  8100. return;
  8101. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  8102. RHSDeclRef->getDecl()->getCanonicalDecl())
  8103. return;
  8104. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  8105. << LHSExpr->getSourceRange()
  8106. << RHSExpr->getSourceRange();
  8107. return;
  8108. }
  8109. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  8110. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  8111. << LHSExpr->getSourceRange()
  8112. << RHSExpr->getSourceRange();
  8113. }
  8114. //===--- Layout compatibility ----------------------------------------------//
  8115. namespace {
  8116. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  8117. /// \brief Check if two enumeration types are layout-compatible.
  8118. bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  8119. // C++11 [dcl.enum] p8:
  8120. // Two enumeration types are layout-compatible if they have the same
  8121. // underlying type.
  8122. return ED1->isComplete() && ED2->isComplete() &&
  8123. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  8124. }
  8125. /// \brief Check if two fields are layout-compatible.
  8126. bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
  8127. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  8128. return false;
  8129. if (Field1->isBitField() != Field2->isBitField())
  8130. return false;
  8131. if (Field1->isBitField()) {
  8132. // Make sure that the bit-fields are the same length.
  8133. unsigned Bits1 = Field1->getBitWidthValue(C);
  8134. unsigned Bits2 = Field2->getBitWidthValue(C);
  8135. if (Bits1 != Bits2)
  8136. return false;
  8137. }
  8138. return true;
  8139. }
  8140. /// \brief Check if two standard-layout structs are layout-compatible.
  8141. /// (C++11 [class.mem] p17)
  8142. bool isLayoutCompatibleStruct(ASTContext &C,
  8143. RecordDecl *RD1,
  8144. RecordDecl *RD2) {
  8145. // If both records are C++ classes, check that base classes match.
  8146. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  8147. // If one of records is a CXXRecordDecl we are in C++ mode,
  8148. // thus the other one is a CXXRecordDecl, too.
  8149. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  8150. // Check number of base classes.
  8151. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  8152. return false;
  8153. // Check the base classes.
  8154. for (CXXRecordDecl::base_class_const_iterator
  8155. Base1 = D1CXX->bases_begin(),
  8156. BaseEnd1 = D1CXX->bases_end(),
  8157. Base2 = D2CXX->bases_begin();
  8158. Base1 != BaseEnd1;
  8159. ++Base1, ++Base2) {
  8160. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  8161. return false;
  8162. }
  8163. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  8164. // If only RD2 is a C++ class, it should have zero base classes.
  8165. if (D2CXX->getNumBases() > 0)
  8166. return false;
  8167. }
  8168. // Check the fields.
  8169. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  8170. Field2End = RD2->field_end(),
  8171. Field1 = RD1->field_begin(),
  8172. Field1End = RD1->field_end();
  8173. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  8174. if (!isLayoutCompatible(C, *Field1, *Field2))
  8175. return false;
  8176. }
  8177. if (Field1 != Field1End || Field2 != Field2End)
  8178. return false;
  8179. return true;
  8180. }
  8181. /// \brief Check if two standard-layout unions are layout-compatible.
  8182. /// (C++11 [class.mem] p18)
  8183. bool isLayoutCompatibleUnion(ASTContext &C,
  8184. RecordDecl *RD1,
  8185. RecordDecl *RD2) {
  8186. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  8187. for (auto *Field2 : RD2->fields())
  8188. UnmatchedFields.insert(Field2);
  8189. for (auto *Field1 : RD1->fields()) {
  8190. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  8191. I = UnmatchedFields.begin(),
  8192. E = UnmatchedFields.end();
  8193. for ( ; I != E; ++I) {
  8194. if (isLayoutCompatible(C, Field1, *I)) {
  8195. bool Result = UnmatchedFields.erase(*I);
  8196. (void) Result;
  8197. assert(Result);
  8198. break;
  8199. }
  8200. }
  8201. if (I == E)
  8202. return false;
  8203. }
  8204. return UnmatchedFields.empty();
  8205. }
  8206. bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
  8207. if (RD1->isUnion() != RD2->isUnion())
  8208. return false;
  8209. if (RD1->isUnion())
  8210. return isLayoutCompatibleUnion(C, RD1, RD2);
  8211. else
  8212. return isLayoutCompatibleStruct(C, RD1, RD2);
  8213. }
  8214. /// \brief Check if two types are layout-compatible in C++11 sense.
  8215. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  8216. if (T1.isNull() || T2.isNull())
  8217. return false;
  8218. // C++11 [basic.types] p11:
  8219. // If two types T1 and T2 are the same type, then T1 and T2 are
  8220. // layout-compatible types.
  8221. if (C.hasSameType(T1, T2))
  8222. return true;
  8223. T1 = T1.getCanonicalType().getUnqualifiedType();
  8224. T2 = T2.getCanonicalType().getUnqualifiedType();
  8225. const Type::TypeClass TC1 = T1->getTypeClass();
  8226. const Type::TypeClass TC2 = T2->getTypeClass();
  8227. if (TC1 != TC2)
  8228. return false;
  8229. if (TC1 == Type::Enum) {
  8230. return isLayoutCompatible(C,
  8231. cast<EnumType>(T1)->getDecl(),
  8232. cast<EnumType>(T2)->getDecl());
  8233. } else if (TC1 == Type::Record) {
  8234. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  8235. return false;
  8236. return isLayoutCompatible(C,
  8237. cast<RecordType>(T1)->getDecl(),
  8238. cast<RecordType>(T2)->getDecl());
  8239. }
  8240. return false;
  8241. }
  8242. }
  8243. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  8244. namespace {
  8245. /// \brief Given a type tag expression find the type tag itself.
  8246. ///
  8247. /// \param TypeExpr Type tag expression, as it appears in user's code.
  8248. ///
  8249. /// \param VD Declaration of an identifier that appears in a type tag.
  8250. ///
  8251. /// \param MagicValue Type tag magic value.
  8252. bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  8253. const ValueDecl **VD, uint64_t *MagicValue) {
  8254. while(true) {
  8255. if (!TypeExpr)
  8256. return false;
  8257. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  8258. switch (TypeExpr->getStmtClass()) {
  8259. case Stmt::UnaryOperatorClass: {
  8260. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  8261. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  8262. TypeExpr = UO->getSubExpr();
  8263. continue;
  8264. }
  8265. return false;
  8266. }
  8267. case Stmt::DeclRefExprClass: {
  8268. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  8269. *VD = DRE->getDecl();
  8270. return true;
  8271. }
  8272. case Stmt::IntegerLiteralClass: {
  8273. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  8274. llvm::APInt MagicValueAPInt = IL->getValue();
  8275. if (MagicValueAPInt.getActiveBits() <= 64) {
  8276. *MagicValue = MagicValueAPInt.getZExtValue();
  8277. return true;
  8278. } else
  8279. return false;
  8280. }
  8281. case Stmt::BinaryConditionalOperatorClass:
  8282. case Stmt::ConditionalOperatorClass: {
  8283. const AbstractConditionalOperator *ACO =
  8284. cast<AbstractConditionalOperator>(TypeExpr);
  8285. bool Result;
  8286. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  8287. if (Result)
  8288. TypeExpr = ACO->getTrueExpr();
  8289. else
  8290. TypeExpr = ACO->getFalseExpr();
  8291. continue;
  8292. }
  8293. return false;
  8294. }
  8295. case Stmt::BinaryOperatorClass: {
  8296. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  8297. if (BO->getOpcode() == BO_Comma) {
  8298. TypeExpr = BO->getRHS();
  8299. continue;
  8300. }
  8301. return false;
  8302. }
  8303. default:
  8304. return false;
  8305. }
  8306. }
  8307. }
  8308. /// \brief Retrieve the C type corresponding to type tag TypeExpr.
  8309. ///
  8310. /// \param TypeExpr Expression that specifies a type tag.
  8311. ///
  8312. /// \param MagicValues Registered magic values.
  8313. ///
  8314. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  8315. /// kind.
  8316. ///
  8317. /// \param TypeInfo Information about the corresponding C type.
  8318. ///
  8319. /// \returns true if the corresponding C type was found.
  8320. bool GetMatchingCType(
  8321. const IdentifierInfo *ArgumentKind,
  8322. const Expr *TypeExpr, const ASTContext &Ctx,
  8323. const llvm::DenseMap<Sema::TypeTagMagicValue,
  8324. Sema::TypeTagData> *MagicValues,
  8325. bool &FoundWrongKind,
  8326. Sema::TypeTagData &TypeInfo) {
  8327. FoundWrongKind = false;
  8328. // Variable declaration that has type_tag_for_datatype attribute.
  8329. const ValueDecl *VD = nullptr;
  8330. uint64_t MagicValue;
  8331. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  8332. return false;
  8333. if (VD) {
  8334. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  8335. if (I->getArgumentKind() != ArgumentKind) {
  8336. FoundWrongKind = true;
  8337. return false;
  8338. }
  8339. TypeInfo.Type = I->getMatchingCType();
  8340. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  8341. TypeInfo.MustBeNull = I->getMustBeNull();
  8342. return true;
  8343. }
  8344. return false;
  8345. }
  8346. if (!MagicValues)
  8347. return false;
  8348. llvm::DenseMap<Sema::TypeTagMagicValue,
  8349. Sema::TypeTagData>::const_iterator I =
  8350. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  8351. if (I == MagicValues->end())
  8352. return false;
  8353. TypeInfo = I->second;
  8354. return true;
  8355. }
  8356. } // unnamed namespace
  8357. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  8358. uint64_t MagicValue, QualType Type,
  8359. bool LayoutCompatible,
  8360. bool MustBeNull) {
  8361. if (!TypeTagForDatatypeMagicValues)
  8362. TypeTagForDatatypeMagicValues.reset(
  8363. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  8364. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  8365. (*TypeTagForDatatypeMagicValues)[Magic] =
  8366. TypeTagData(Type, LayoutCompatible, MustBeNull);
  8367. }
  8368. namespace {
  8369. bool IsSameCharType(QualType T1, QualType T2) {
  8370. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  8371. if (!BT1)
  8372. return false;
  8373. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  8374. if (!BT2)
  8375. return false;
  8376. BuiltinType::Kind T1Kind = BT1->getKind();
  8377. BuiltinType::Kind T2Kind = BT2->getKind();
  8378. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  8379. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  8380. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  8381. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  8382. }
  8383. } // unnamed namespace
  8384. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  8385. const Expr * const *ExprArgs) {
  8386. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  8387. bool IsPointerAttr = Attr->getIsPointer();
  8388. const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
  8389. bool FoundWrongKind;
  8390. TypeTagData TypeInfo;
  8391. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  8392. TypeTagForDatatypeMagicValues.get(),
  8393. FoundWrongKind, TypeInfo)) {
  8394. if (FoundWrongKind)
  8395. Diag(TypeTagExpr->getExprLoc(),
  8396. diag::warn_type_tag_for_datatype_wrong_kind)
  8397. << TypeTagExpr->getSourceRange();
  8398. return;
  8399. }
  8400. const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
  8401. if (IsPointerAttr) {
  8402. // Skip implicit cast of pointer to `void *' (as a function argument).
  8403. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  8404. if (ICE->getType()->isVoidPointerType() &&
  8405. ICE->getCastKind() == CK_BitCast)
  8406. ArgumentExpr = ICE->getSubExpr();
  8407. }
  8408. QualType ArgumentType = ArgumentExpr->getType();
  8409. // Passing a `void*' pointer shouldn't trigger a warning.
  8410. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  8411. return;
  8412. if (TypeInfo.MustBeNull) {
  8413. // Type tag with matching void type requires a null pointer.
  8414. if (!ArgumentExpr->isNullPointerConstant(Context,
  8415. Expr::NPC_ValueDependentIsNotNull)) {
  8416. Diag(ArgumentExpr->getExprLoc(),
  8417. diag::warn_type_safety_null_pointer_required)
  8418. << ArgumentKind->getName()
  8419. << ArgumentExpr->getSourceRange()
  8420. << TypeTagExpr->getSourceRange();
  8421. }
  8422. return;
  8423. }
  8424. QualType RequiredType = TypeInfo.Type;
  8425. if (IsPointerAttr)
  8426. RequiredType = Context.getPointerType(RequiredType);
  8427. bool mismatch = false;
  8428. if (!TypeInfo.LayoutCompatible) {
  8429. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  8430. // C++11 [basic.fundamental] p1:
  8431. // Plain char, signed char, and unsigned char are three distinct types.
  8432. //
  8433. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  8434. // char' depending on the current char signedness mode.
  8435. if (mismatch)
  8436. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  8437. RequiredType->getPointeeType())) ||
  8438. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  8439. mismatch = false;
  8440. } else
  8441. if (IsPointerAttr)
  8442. mismatch = !isLayoutCompatible(Context,
  8443. ArgumentType->getPointeeType(),
  8444. RequiredType->getPointeeType());
  8445. else
  8446. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  8447. if (mismatch)
  8448. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  8449. << ArgumentType << ArgumentKind
  8450. << TypeInfo.LayoutCompatible << RequiredType
  8451. << ArgumentExpr->getSourceRange()
  8452. << TypeTagExpr->getSourceRange();
  8453. }