SemaChecking.cpp 203 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468
  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/Initialization.h"
  15. #include "clang/Sema/Sema.h"
  16. #include "clang/Sema/SemaInternal.h"
  17. #include "clang/Sema/Initialization.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "clang/Sema/ScopeInfo.h"
  20. #include "clang/Analysis/Analyses/FormatString.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/CharUnits.h"
  23. #include "clang/AST/DeclCXX.h"
  24. #include "clang/AST/DeclObjC.h"
  25. #include "clang/AST/Expr.h"
  26. #include "clang/AST/ExprCXX.h"
  27. #include "clang/AST/ExprObjC.h"
  28. #include "clang/AST/EvaluatedExprVisitor.h"
  29. #include "clang/AST/DeclObjC.h"
  30. #include "clang/AST/StmtCXX.h"
  31. #include "clang/AST/StmtObjC.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "llvm/ADT/BitVector.h"
  34. #include "llvm/ADT/SmallString.h"
  35. #include "llvm/ADT/STLExtras.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include "clang/Basic/TargetBuiltins.h"
  38. #include "clang/Basic/TargetInfo.h"
  39. #include "clang/Basic/ConvertUTF.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, PP.getSourceManager(),
  46. PP.getLangOpts(), PP.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. ExprResult
  89. Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  90. ExprResult TheCallResult(Owned(TheCall));
  91. // Find out if any arguments are required to be integer constant expressions.
  92. unsigned ICEArguments = 0;
  93. ASTContext::GetBuiltinTypeError Error;
  94. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  95. if (Error != ASTContext::GE_None)
  96. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  97. // If any arguments are required to be ICE's, check and diagnose.
  98. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  99. // Skip arguments not required to be ICE's.
  100. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  101. llvm::APSInt Result;
  102. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  103. return true;
  104. ICEArguments &= ~(1 << ArgNo);
  105. }
  106. switch (BuiltinID) {
  107. case Builtin::BI__builtin___CFStringMakeConstantString:
  108. assert(TheCall->getNumArgs() == 1 &&
  109. "Wrong # arguments to builtin CFStringMakeConstantString");
  110. if (CheckObjCString(TheCall->getArg(0)))
  111. return ExprError();
  112. break;
  113. case Builtin::BI__builtin_stdarg_start:
  114. case Builtin::BI__builtin_va_start:
  115. if (SemaBuiltinVAStart(TheCall))
  116. return ExprError();
  117. break;
  118. case Builtin::BI__builtin_isgreater:
  119. case Builtin::BI__builtin_isgreaterequal:
  120. case Builtin::BI__builtin_isless:
  121. case Builtin::BI__builtin_islessequal:
  122. case Builtin::BI__builtin_islessgreater:
  123. case Builtin::BI__builtin_isunordered:
  124. if (SemaBuiltinUnorderedCompare(TheCall))
  125. return ExprError();
  126. break;
  127. case Builtin::BI__builtin_fpclassify:
  128. if (SemaBuiltinFPClassification(TheCall, 6))
  129. return ExprError();
  130. break;
  131. case Builtin::BI__builtin_isfinite:
  132. case Builtin::BI__builtin_isinf:
  133. case Builtin::BI__builtin_isinf_sign:
  134. case Builtin::BI__builtin_isnan:
  135. case Builtin::BI__builtin_isnormal:
  136. if (SemaBuiltinFPClassification(TheCall, 1))
  137. return ExprError();
  138. break;
  139. case Builtin::BI__builtin_shufflevector:
  140. return SemaBuiltinShuffleVector(TheCall);
  141. // TheCall will be freed by the smart pointer here, but that's fine, since
  142. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  143. case Builtin::BI__builtin_prefetch:
  144. if (SemaBuiltinPrefetch(TheCall))
  145. return ExprError();
  146. break;
  147. case Builtin::BI__builtin_object_size:
  148. if (SemaBuiltinObjectSize(TheCall))
  149. return ExprError();
  150. break;
  151. case Builtin::BI__builtin_longjmp:
  152. if (SemaBuiltinLongjmp(TheCall))
  153. return ExprError();
  154. break;
  155. case Builtin::BI__builtin_classify_type:
  156. if (checkArgCount(*this, TheCall, 1)) return true;
  157. TheCall->setType(Context.IntTy);
  158. break;
  159. case Builtin::BI__builtin_constant_p:
  160. if (checkArgCount(*this, TheCall, 1)) return true;
  161. TheCall->setType(Context.IntTy);
  162. break;
  163. case Builtin::BI__sync_fetch_and_add:
  164. case Builtin::BI__sync_fetch_and_add_1:
  165. case Builtin::BI__sync_fetch_and_add_2:
  166. case Builtin::BI__sync_fetch_and_add_4:
  167. case Builtin::BI__sync_fetch_and_add_8:
  168. case Builtin::BI__sync_fetch_and_add_16:
  169. case Builtin::BI__sync_fetch_and_sub:
  170. case Builtin::BI__sync_fetch_and_sub_1:
  171. case Builtin::BI__sync_fetch_and_sub_2:
  172. case Builtin::BI__sync_fetch_and_sub_4:
  173. case Builtin::BI__sync_fetch_and_sub_8:
  174. case Builtin::BI__sync_fetch_and_sub_16:
  175. case Builtin::BI__sync_fetch_and_or:
  176. case Builtin::BI__sync_fetch_and_or_1:
  177. case Builtin::BI__sync_fetch_and_or_2:
  178. case Builtin::BI__sync_fetch_and_or_4:
  179. case Builtin::BI__sync_fetch_and_or_8:
  180. case Builtin::BI__sync_fetch_and_or_16:
  181. case Builtin::BI__sync_fetch_and_and:
  182. case Builtin::BI__sync_fetch_and_and_1:
  183. case Builtin::BI__sync_fetch_and_and_2:
  184. case Builtin::BI__sync_fetch_and_and_4:
  185. case Builtin::BI__sync_fetch_and_and_8:
  186. case Builtin::BI__sync_fetch_and_and_16:
  187. case Builtin::BI__sync_fetch_and_xor:
  188. case Builtin::BI__sync_fetch_and_xor_1:
  189. case Builtin::BI__sync_fetch_and_xor_2:
  190. case Builtin::BI__sync_fetch_and_xor_4:
  191. case Builtin::BI__sync_fetch_and_xor_8:
  192. case Builtin::BI__sync_fetch_and_xor_16:
  193. case Builtin::BI__sync_add_and_fetch:
  194. case Builtin::BI__sync_add_and_fetch_1:
  195. case Builtin::BI__sync_add_and_fetch_2:
  196. case Builtin::BI__sync_add_and_fetch_4:
  197. case Builtin::BI__sync_add_and_fetch_8:
  198. case Builtin::BI__sync_add_and_fetch_16:
  199. case Builtin::BI__sync_sub_and_fetch:
  200. case Builtin::BI__sync_sub_and_fetch_1:
  201. case Builtin::BI__sync_sub_and_fetch_2:
  202. case Builtin::BI__sync_sub_and_fetch_4:
  203. case Builtin::BI__sync_sub_and_fetch_8:
  204. case Builtin::BI__sync_sub_and_fetch_16:
  205. case Builtin::BI__sync_and_and_fetch:
  206. case Builtin::BI__sync_and_and_fetch_1:
  207. case Builtin::BI__sync_and_and_fetch_2:
  208. case Builtin::BI__sync_and_and_fetch_4:
  209. case Builtin::BI__sync_and_and_fetch_8:
  210. case Builtin::BI__sync_and_and_fetch_16:
  211. case Builtin::BI__sync_or_and_fetch:
  212. case Builtin::BI__sync_or_and_fetch_1:
  213. case Builtin::BI__sync_or_and_fetch_2:
  214. case Builtin::BI__sync_or_and_fetch_4:
  215. case Builtin::BI__sync_or_and_fetch_8:
  216. case Builtin::BI__sync_or_and_fetch_16:
  217. case Builtin::BI__sync_xor_and_fetch:
  218. case Builtin::BI__sync_xor_and_fetch_1:
  219. case Builtin::BI__sync_xor_and_fetch_2:
  220. case Builtin::BI__sync_xor_and_fetch_4:
  221. case Builtin::BI__sync_xor_and_fetch_8:
  222. case Builtin::BI__sync_xor_and_fetch_16:
  223. case Builtin::BI__sync_val_compare_and_swap:
  224. case Builtin::BI__sync_val_compare_and_swap_1:
  225. case Builtin::BI__sync_val_compare_and_swap_2:
  226. case Builtin::BI__sync_val_compare_and_swap_4:
  227. case Builtin::BI__sync_val_compare_and_swap_8:
  228. case Builtin::BI__sync_val_compare_and_swap_16:
  229. case Builtin::BI__sync_bool_compare_and_swap:
  230. case Builtin::BI__sync_bool_compare_and_swap_1:
  231. case Builtin::BI__sync_bool_compare_and_swap_2:
  232. case Builtin::BI__sync_bool_compare_and_swap_4:
  233. case Builtin::BI__sync_bool_compare_and_swap_8:
  234. case Builtin::BI__sync_bool_compare_and_swap_16:
  235. case Builtin::BI__sync_lock_test_and_set:
  236. case Builtin::BI__sync_lock_test_and_set_1:
  237. case Builtin::BI__sync_lock_test_and_set_2:
  238. case Builtin::BI__sync_lock_test_and_set_4:
  239. case Builtin::BI__sync_lock_test_and_set_8:
  240. case Builtin::BI__sync_lock_test_and_set_16:
  241. case Builtin::BI__sync_lock_release:
  242. case Builtin::BI__sync_lock_release_1:
  243. case Builtin::BI__sync_lock_release_2:
  244. case Builtin::BI__sync_lock_release_4:
  245. case Builtin::BI__sync_lock_release_8:
  246. case Builtin::BI__sync_lock_release_16:
  247. case Builtin::BI__sync_swap:
  248. case Builtin::BI__sync_swap_1:
  249. case Builtin::BI__sync_swap_2:
  250. case Builtin::BI__sync_swap_4:
  251. case Builtin::BI__sync_swap_8:
  252. case Builtin::BI__sync_swap_16:
  253. return SemaBuiltinAtomicOverloaded(move(TheCallResult));
  254. #define BUILTIN(ID, TYPE, ATTRS)
  255. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  256. case Builtin::BI##ID: \
  257. return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::AO##ID);
  258. #include "clang/Basic/Builtins.def"
  259. case Builtin::BI__builtin_annotation:
  260. if (SemaBuiltinAnnotation(*this, TheCall))
  261. return ExprError();
  262. break;
  263. }
  264. // Since the target specific builtins for each arch overlap, only check those
  265. // of the arch we are compiling for.
  266. if (BuiltinID >= Builtin::FirstTSBuiltin) {
  267. switch (Context.getTargetInfo().getTriple().getArch()) {
  268. case llvm::Triple::arm:
  269. case llvm::Triple::thumb:
  270. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  271. return ExprError();
  272. break;
  273. case llvm::Triple::mips:
  274. case llvm::Triple::mipsel:
  275. case llvm::Triple::mips64:
  276. case llvm::Triple::mips64el:
  277. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  278. return ExprError();
  279. break;
  280. default:
  281. break;
  282. }
  283. }
  284. return move(TheCallResult);
  285. }
  286. // Get the valid immediate range for the specified NEON type code.
  287. static unsigned RFT(unsigned t, bool shift = false) {
  288. NeonTypeFlags Type(t);
  289. int IsQuad = Type.isQuad();
  290. switch (Type.getEltType()) {
  291. case NeonTypeFlags::Int8:
  292. case NeonTypeFlags::Poly8:
  293. return shift ? 7 : (8 << IsQuad) - 1;
  294. case NeonTypeFlags::Int16:
  295. case NeonTypeFlags::Poly16:
  296. return shift ? 15 : (4 << IsQuad) - 1;
  297. case NeonTypeFlags::Int32:
  298. return shift ? 31 : (2 << IsQuad) - 1;
  299. case NeonTypeFlags::Int64:
  300. return shift ? 63 : (1 << IsQuad) - 1;
  301. case NeonTypeFlags::Float16:
  302. assert(!shift && "cannot shift float types!");
  303. return (4 << IsQuad) - 1;
  304. case NeonTypeFlags::Float32:
  305. assert(!shift && "cannot shift float types!");
  306. return (2 << IsQuad) - 1;
  307. }
  308. llvm_unreachable("Invalid NeonTypeFlag!");
  309. }
  310. /// getNeonEltType - Return the QualType corresponding to the elements of
  311. /// the vector type specified by the NeonTypeFlags. This is used to check
  312. /// the pointer arguments for Neon load/store intrinsics.
  313. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
  314. switch (Flags.getEltType()) {
  315. case NeonTypeFlags::Int8:
  316. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  317. case NeonTypeFlags::Int16:
  318. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  319. case NeonTypeFlags::Int32:
  320. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  321. case NeonTypeFlags::Int64:
  322. return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
  323. case NeonTypeFlags::Poly8:
  324. return Context.SignedCharTy;
  325. case NeonTypeFlags::Poly16:
  326. return Context.ShortTy;
  327. case NeonTypeFlags::Float16:
  328. return Context.UnsignedShortTy;
  329. case NeonTypeFlags::Float32:
  330. return Context.FloatTy;
  331. }
  332. llvm_unreachable("Invalid NeonTypeFlag!");
  333. }
  334. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  335. llvm::APSInt Result;
  336. unsigned mask = 0;
  337. unsigned TV = 0;
  338. int PtrArgNum = -1;
  339. bool HasConstPtr = false;
  340. switch (BuiltinID) {
  341. #define GET_NEON_OVERLOAD_CHECK
  342. #include "clang/Basic/arm_neon.inc"
  343. #undef GET_NEON_OVERLOAD_CHECK
  344. }
  345. // For NEON intrinsics which are overloaded on vector element type, validate
  346. // the immediate which specifies which variant to emit.
  347. unsigned ImmArg = TheCall->getNumArgs()-1;
  348. if (mask) {
  349. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  350. return true;
  351. TV = Result.getLimitedValue(64);
  352. if ((TV > 63) || (mask & (1 << TV)) == 0)
  353. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  354. << TheCall->getArg(ImmArg)->getSourceRange();
  355. }
  356. if (PtrArgNum >= 0) {
  357. // Check that pointer arguments have the specified type.
  358. Expr *Arg = TheCall->getArg(PtrArgNum);
  359. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  360. Arg = ICE->getSubExpr();
  361. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  362. QualType RHSTy = RHS.get()->getType();
  363. QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
  364. if (HasConstPtr)
  365. EltTy = EltTy.withConst();
  366. QualType LHSTy = Context.getPointerType(EltTy);
  367. AssignConvertType ConvTy;
  368. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  369. if (RHS.isInvalid())
  370. return true;
  371. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  372. RHS.get(), AA_Assigning))
  373. return true;
  374. }
  375. // For NEON intrinsics which take an immediate value as part of the
  376. // instruction, range check them here.
  377. unsigned i = 0, l = 0, u = 0;
  378. switch (BuiltinID) {
  379. default: return false;
  380. case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
  381. case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
  382. case ARM::BI__builtin_arm_vcvtr_f:
  383. case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
  384. #define GET_NEON_IMMEDIATE_CHECK
  385. #include "clang/Basic/arm_neon.inc"
  386. #undef GET_NEON_IMMEDIATE_CHECK
  387. };
  388. // We can't check the value of a dependent argument.
  389. if (TheCall->getArg(i)->isTypeDependent() ||
  390. TheCall->getArg(i)->isValueDependent())
  391. return false;
  392. // Check that the immediate argument is actually a constant.
  393. if (SemaBuiltinConstantArg(TheCall, i, Result))
  394. return true;
  395. // Range check against the upper/lower values for this isntruction.
  396. unsigned Val = Result.getZExtValue();
  397. if (Val < l || Val > (u + l))
  398. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  399. << l << u+l << TheCall->getArg(i)->getSourceRange();
  400. // FIXME: VFP Intrinsics should error if VFP not present.
  401. return false;
  402. }
  403. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  404. unsigned i = 0, l = 0, u = 0;
  405. switch (BuiltinID) {
  406. default: return false;
  407. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  408. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  409. };
  410. // We can't check the value of a dependent argument.
  411. if (TheCall->getArg(i)->isTypeDependent() ||
  412. TheCall->getArg(i)->isValueDependent())
  413. return false;
  414. // Check that the immediate argument is actually a constant.
  415. llvm::APSInt Result;
  416. if (SemaBuiltinConstantArg(TheCall, i, Result))
  417. return true;
  418. // Range check against the upper/lower values for this instruction.
  419. unsigned Val = Result.getZExtValue();
  420. if (Val < l || Val > u)
  421. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  422. << l << u << TheCall->getArg(i)->getSourceRange();
  423. return false;
  424. }
  425. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  426. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  427. /// Returns true when the format fits the function and the FormatStringInfo has
  428. /// been populated.
  429. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  430. FormatStringInfo *FSI) {
  431. FSI->HasVAListArg = Format->getFirstArg() == 0;
  432. FSI->FormatIdx = Format->getFormatIdx() - 1;
  433. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  434. // The way the format attribute works in GCC, the implicit this argument
  435. // of member functions is counted. However, it doesn't appear in our own
  436. // lists, so decrement format_idx in that case.
  437. if (IsCXXMember) {
  438. if(FSI->FormatIdx == 0)
  439. return false;
  440. --FSI->FormatIdx;
  441. if (FSI->FirstDataArg != 0)
  442. --FSI->FirstDataArg;
  443. }
  444. return true;
  445. }
  446. /// Handles the checks for format strings, non-POD arguments to vararg
  447. /// functions, and NULL arguments passed to non-NULL parameters.
  448. void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
  449. unsigned NumArgs,
  450. unsigned NumProtoArgs,
  451. bool IsMemberFunction,
  452. SourceLocation Loc,
  453. SourceRange Range,
  454. VariadicCallType CallType) {
  455. // FIXME: This mechanism should be abstracted to be less fragile and
  456. // more efficient. For example, just map function ids to custom
  457. // handlers.
  458. // Printf and scanf checking.
  459. bool HandledFormatString = false;
  460. for (specific_attr_iterator<FormatAttr>
  461. I = FDecl->specific_attr_begin<FormatAttr>(),
  462. E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
  463. if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType,
  464. Loc, Range))
  465. HandledFormatString = true;
  466. // Refuse POD arguments that weren't caught by the format string
  467. // checks above.
  468. if (!HandledFormatString && CallType != VariadicDoesNotApply)
  469. for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx)
  470. variadicArgumentPODCheck(Args[ArgIdx], CallType);
  471. for (specific_attr_iterator<NonNullAttr>
  472. I = FDecl->specific_attr_begin<NonNullAttr>(),
  473. E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
  474. CheckNonNullArguments(*I, Args, Loc);
  475. }
  476. /// CheckConstructorCall - Check a constructor call for correctness and safety
  477. /// properties not enforced by the C type system.
  478. void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
  479. unsigned NumArgs,
  480. const FunctionProtoType *Proto,
  481. SourceLocation Loc) {
  482. VariadicCallType CallType =
  483. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  484. checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
  485. /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
  486. }
  487. /// CheckFunctionCall - Check a direct function call for various correctness
  488. /// and safety properties not strictly enforced by the C type system.
  489. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  490. const FunctionProtoType *Proto) {
  491. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall);
  492. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  493. TheCall->getCallee());
  494. unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
  495. checkCall(FDecl, TheCall->getArgs(), TheCall->getNumArgs(), NumProtoArgs,
  496. IsMemberFunction, TheCall->getRParenLoc(),
  497. TheCall->getCallee()->getSourceRange(), CallType);
  498. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  499. // None of the checks below are needed for functions that don't have
  500. // simple names (e.g., C++ conversion functions).
  501. if (!FnInfo)
  502. return false;
  503. unsigned CMId = FDecl->getMemoryFunctionKind();
  504. if (CMId == 0)
  505. return false;
  506. // Handle memory setting and copying functions.
  507. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  508. CheckStrlcpycatArguments(TheCall, FnInfo);
  509. else if (CMId == Builtin::BIstrncat)
  510. CheckStrncatArguments(TheCall, FnInfo);
  511. else
  512. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  513. return false;
  514. }
  515. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  516. Expr **Args, unsigned NumArgs) {
  517. VariadicCallType CallType =
  518. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  519. checkCall(Method, Args, NumArgs, Method->param_size(),
  520. /*IsMemberFunction=*/false,
  521. lbrac, Method->getSourceRange(), CallType);
  522. return false;
  523. }
  524. bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
  525. const FunctionProtoType *Proto) {
  526. const VarDecl *V = dyn_cast<VarDecl>(NDecl);
  527. if (!V)
  528. return false;
  529. QualType Ty = V->getType();
  530. if (!Ty->isBlockPointerType())
  531. return false;
  532. VariadicCallType CallType =
  533. Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
  534. unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
  535. checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
  536. NumProtoArgs, /*IsMemberFunction=*/false,
  537. TheCall->getRParenLoc(),
  538. TheCall->getCallee()->getSourceRange(), CallType);
  539. return false;
  540. }
  541. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  542. AtomicExpr::AtomicOp Op) {
  543. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  544. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  545. // All these operations take one of the following forms:
  546. enum {
  547. // C __c11_atomic_init(A *, C)
  548. Init,
  549. // C __c11_atomic_load(A *, int)
  550. Load,
  551. // void __atomic_load(A *, CP, int)
  552. Copy,
  553. // C __c11_atomic_add(A *, M, int)
  554. Arithmetic,
  555. // C __atomic_exchange_n(A *, CP, int)
  556. Xchg,
  557. // void __atomic_exchange(A *, C *, CP, int)
  558. GNUXchg,
  559. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  560. C11CmpXchg,
  561. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  562. GNUCmpXchg
  563. } Form = Init;
  564. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
  565. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
  566. // where:
  567. // C is an appropriate type,
  568. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  569. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  570. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  571. // the int parameters are for orderings.
  572. assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  573. AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
  574. && "need to update code for modified C11 atomics");
  575. bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
  576. Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
  577. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  578. Op == AtomicExpr::AO__atomic_store_n ||
  579. Op == AtomicExpr::AO__atomic_exchange_n ||
  580. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  581. bool IsAddSub = false;
  582. switch (Op) {
  583. case AtomicExpr::AO__c11_atomic_init:
  584. Form = Init;
  585. break;
  586. case AtomicExpr::AO__c11_atomic_load:
  587. case AtomicExpr::AO__atomic_load_n:
  588. Form = Load;
  589. break;
  590. case AtomicExpr::AO__c11_atomic_store:
  591. case AtomicExpr::AO__atomic_load:
  592. case AtomicExpr::AO__atomic_store:
  593. case AtomicExpr::AO__atomic_store_n:
  594. Form = Copy;
  595. break;
  596. case AtomicExpr::AO__c11_atomic_fetch_add:
  597. case AtomicExpr::AO__c11_atomic_fetch_sub:
  598. case AtomicExpr::AO__atomic_fetch_add:
  599. case AtomicExpr::AO__atomic_fetch_sub:
  600. case AtomicExpr::AO__atomic_add_fetch:
  601. case AtomicExpr::AO__atomic_sub_fetch:
  602. IsAddSub = true;
  603. // Fall through.
  604. case AtomicExpr::AO__c11_atomic_fetch_and:
  605. case AtomicExpr::AO__c11_atomic_fetch_or:
  606. case AtomicExpr::AO__c11_atomic_fetch_xor:
  607. case AtomicExpr::AO__atomic_fetch_and:
  608. case AtomicExpr::AO__atomic_fetch_or:
  609. case AtomicExpr::AO__atomic_fetch_xor:
  610. case AtomicExpr::AO__atomic_fetch_nand:
  611. case AtomicExpr::AO__atomic_and_fetch:
  612. case AtomicExpr::AO__atomic_or_fetch:
  613. case AtomicExpr::AO__atomic_xor_fetch:
  614. case AtomicExpr::AO__atomic_nand_fetch:
  615. Form = Arithmetic;
  616. break;
  617. case AtomicExpr::AO__c11_atomic_exchange:
  618. case AtomicExpr::AO__atomic_exchange_n:
  619. Form = Xchg;
  620. break;
  621. case AtomicExpr::AO__atomic_exchange:
  622. Form = GNUXchg;
  623. break;
  624. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  625. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  626. Form = C11CmpXchg;
  627. break;
  628. case AtomicExpr::AO__atomic_compare_exchange:
  629. case AtomicExpr::AO__atomic_compare_exchange_n:
  630. Form = GNUCmpXchg;
  631. break;
  632. }
  633. // Check we have the right number of arguments.
  634. if (TheCall->getNumArgs() < NumArgs[Form]) {
  635. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  636. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  637. << TheCall->getCallee()->getSourceRange();
  638. return ExprError();
  639. } else if (TheCall->getNumArgs() > NumArgs[Form]) {
  640. Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
  641. diag::err_typecheck_call_too_many_args)
  642. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  643. << TheCall->getCallee()->getSourceRange();
  644. return ExprError();
  645. }
  646. // Inspect the first argument of the atomic operation.
  647. Expr *Ptr = TheCall->getArg(0);
  648. Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
  649. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  650. if (!pointerType) {
  651. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  652. << Ptr->getType() << Ptr->getSourceRange();
  653. return ExprError();
  654. }
  655. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  656. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  657. QualType ValType = AtomTy; // 'C'
  658. if (IsC11) {
  659. if (!AtomTy->isAtomicType()) {
  660. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  661. << Ptr->getType() << Ptr->getSourceRange();
  662. return ExprError();
  663. }
  664. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  665. }
  666. // For an arithmetic operation, the implied arithmetic must be well-formed.
  667. if (Form == Arithmetic) {
  668. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  669. if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
  670. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  671. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  672. return ExprError();
  673. }
  674. if (!IsAddSub && !ValType->isIntegerType()) {
  675. Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
  676. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  677. return ExprError();
  678. }
  679. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  680. // For __atomic_*_n operations, the value type must be a scalar integral or
  681. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  682. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  683. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  684. return ExprError();
  685. }
  686. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
  687. // For GNU atomics, require a trivially-copyable type. This is not part of
  688. // the GNU atomics specification, but we enforce it for sanity.
  689. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
  690. << Ptr->getType() << Ptr->getSourceRange();
  691. return ExprError();
  692. }
  693. // FIXME: For any builtin other than a load, the ValType must not be
  694. // const-qualified.
  695. switch (ValType.getObjCLifetime()) {
  696. case Qualifiers::OCL_None:
  697. case Qualifiers::OCL_ExplicitNone:
  698. // okay
  699. break;
  700. case Qualifiers::OCL_Weak:
  701. case Qualifiers::OCL_Strong:
  702. case Qualifiers::OCL_Autoreleasing:
  703. // FIXME: Can this happen? By this point, ValType should be known
  704. // to be trivially copyable.
  705. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  706. << ValType << Ptr->getSourceRange();
  707. return ExprError();
  708. }
  709. QualType ResultType = ValType;
  710. if (Form == Copy || Form == GNUXchg || Form == Init)
  711. ResultType = Context.VoidTy;
  712. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  713. ResultType = Context.BoolTy;
  714. // The type of a parameter passed 'by value'. In the GNU atomics, such
  715. // arguments are actually passed as pointers.
  716. QualType ByValType = ValType; // 'CP'
  717. if (!IsC11 && !IsN)
  718. ByValType = Ptr->getType();
  719. // The first argument --- the pointer --- has a fixed type; we
  720. // deduce the types of the rest of the arguments accordingly. Walk
  721. // the remaining arguments, converting them to the deduced value type.
  722. for (unsigned i = 1; i != NumArgs[Form]; ++i) {
  723. QualType Ty;
  724. if (i < NumVals[Form] + 1) {
  725. switch (i) {
  726. case 1:
  727. // The second argument is the non-atomic operand. For arithmetic, this
  728. // is always passed by value, and for a compare_exchange it is always
  729. // passed by address. For the rest, GNU uses by-address and C11 uses
  730. // by-value.
  731. assert(Form != Load);
  732. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  733. Ty = ValType;
  734. else if (Form == Copy || Form == Xchg)
  735. Ty = ByValType;
  736. else if (Form == Arithmetic)
  737. Ty = Context.getPointerDiffType();
  738. else
  739. Ty = Context.getPointerType(ValType.getUnqualifiedType());
  740. break;
  741. case 2:
  742. // The third argument to compare_exchange / GNU exchange is a
  743. // (pointer to a) desired value.
  744. Ty = ByValType;
  745. break;
  746. case 3:
  747. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  748. Ty = Context.BoolTy;
  749. break;
  750. }
  751. } else {
  752. // The order(s) are always converted to int.
  753. Ty = Context.IntTy;
  754. }
  755. InitializedEntity Entity =
  756. InitializedEntity::InitializeParameter(Context, Ty, false);
  757. ExprResult Arg = TheCall->getArg(i);
  758. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  759. if (Arg.isInvalid())
  760. return true;
  761. TheCall->setArg(i, Arg.get());
  762. }
  763. // Permute the arguments into a 'consistent' order.
  764. SmallVector<Expr*, 5> SubExprs;
  765. SubExprs.push_back(Ptr);
  766. switch (Form) {
  767. case Init:
  768. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  769. SubExprs.push_back(TheCall->getArg(1)); // Val1
  770. break;
  771. case Load:
  772. SubExprs.push_back(TheCall->getArg(1)); // Order
  773. break;
  774. case Copy:
  775. case Arithmetic:
  776. case Xchg:
  777. SubExprs.push_back(TheCall->getArg(2)); // Order
  778. SubExprs.push_back(TheCall->getArg(1)); // Val1
  779. break;
  780. case GNUXchg:
  781. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  782. SubExprs.push_back(TheCall->getArg(3)); // Order
  783. SubExprs.push_back(TheCall->getArg(1)); // Val1
  784. SubExprs.push_back(TheCall->getArg(2)); // Val2
  785. break;
  786. case C11CmpXchg:
  787. SubExprs.push_back(TheCall->getArg(3)); // Order
  788. SubExprs.push_back(TheCall->getArg(1)); // Val1
  789. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  790. SubExprs.push_back(TheCall->getArg(2)); // Val2
  791. break;
  792. case GNUCmpXchg:
  793. SubExprs.push_back(TheCall->getArg(4)); // Order
  794. SubExprs.push_back(TheCall->getArg(1)); // Val1
  795. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  796. SubExprs.push_back(TheCall->getArg(2)); // Val2
  797. SubExprs.push_back(TheCall->getArg(3)); // Weak
  798. break;
  799. }
  800. return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  801. SubExprs.data(), SubExprs.size(),
  802. ResultType, Op,
  803. TheCall->getRParenLoc()));
  804. }
  805. /// checkBuiltinArgument - Given a call to a builtin function, perform
  806. /// normal type-checking on the given argument, updating the call in
  807. /// place. This is useful when a builtin function requires custom
  808. /// type-checking for some of its arguments but not necessarily all of
  809. /// them.
  810. ///
  811. /// Returns true on error.
  812. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  813. FunctionDecl *Fn = E->getDirectCallee();
  814. assert(Fn && "builtin call without direct callee!");
  815. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  816. InitializedEntity Entity =
  817. InitializedEntity::InitializeParameter(S.Context, Param);
  818. ExprResult Arg = E->getArg(0);
  819. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  820. if (Arg.isInvalid())
  821. return true;
  822. E->setArg(ArgIndex, Arg.take());
  823. return false;
  824. }
  825. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  826. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  827. /// type of its first argument. The main ActOnCallExpr routines have already
  828. /// promoted the types of arguments because all of these calls are prototyped as
  829. /// void(...).
  830. ///
  831. /// This function goes through and does final semantic checking for these
  832. /// builtins,
  833. ExprResult
  834. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  835. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  836. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  837. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  838. // Ensure that we have at least one argument to do type inference from.
  839. if (TheCall->getNumArgs() < 1) {
  840. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  841. << 0 << 1 << TheCall->getNumArgs()
  842. << TheCall->getCallee()->getSourceRange();
  843. return ExprError();
  844. }
  845. // Inspect the first argument of the atomic builtin. This should always be
  846. // a pointer type, whose element is an integral scalar or pointer type.
  847. // Because it is a pointer type, we don't have to worry about any implicit
  848. // casts here.
  849. // FIXME: We don't allow floating point scalars as input.
  850. Expr *FirstArg = TheCall->getArg(0);
  851. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  852. if (FirstArgResult.isInvalid())
  853. return ExprError();
  854. FirstArg = FirstArgResult.take();
  855. TheCall->setArg(0, FirstArg);
  856. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  857. if (!pointerType) {
  858. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  859. << FirstArg->getType() << FirstArg->getSourceRange();
  860. return ExprError();
  861. }
  862. QualType ValType = pointerType->getPointeeType();
  863. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  864. !ValType->isBlockPointerType()) {
  865. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  866. << FirstArg->getType() << FirstArg->getSourceRange();
  867. return ExprError();
  868. }
  869. switch (ValType.getObjCLifetime()) {
  870. case Qualifiers::OCL_None:
  871. case Qualifiers::OCL_ExplicitNone:
  872. // okay
  873. break;
  874. case Qualifiers::OCL_Weak:
  875. case Qualifiers::OCL_Strong:
  876. case Qualifiers::OCL_Autoreleasing:
  877. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  878. << ValType << FirstArg->getSourceRange();
  879. return ExprError();
  880. }
  881. // Strip any qualifiers off ValType.
  882. ValType = ValType.getUnqualifiedType();
  883. // The majority of builtins return a value, but a few have special return
  884. // types, so allow them to override appropriately below.
  885. QualType ResultType = ValType;
  886. // We need to figure out which concrete builtin this maps onto. For example,
  887. // __sync_fetch_and_add with a 2 byte object turns into
  888. // __sync_fetch_and_add_2.
  889. #define BUILTIN_ROW(x) \
  890. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  891. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  892. static const unsigned BuiltinIndices[][5] = {
  893. BUILTIN_ROW(__sync_fetch_and_add),
  894. BUILTIN_ROW(__sync_fetch_and_sub),
  895. BUILTIN_ROW(__sync_fetch_and_or),
  896. BUILTIN_ROW(__sync_fetch_and_and),
  897. BUILTIN_ROW(__sync_fetch_and_xor),
  898. BUILTIN_ROW(__sync_add_and_fetch),
  899. BUILTIN_ROW(__sync_sub_and_fetch),
  900. BUILTIN_ROW(__sync_and_and_fetch),
  901. BUILTIN_ROW(__sync_or_and_fetch),
  902. BUILTIN_ROW(__sync_xor_and_fetch),
  903. BUILTIN_ROW(__sync_val_compare_and_swap),
  904. BUILTIN_ROW(__sync_bool_compare_and_swap),
  905. BUILTIN_ROW(__sync_lock_test_and_set),
  906. BUILTIN_ROW(__sync_lock_release),
  907. BUILTIN_ROW(__sync_swap)
  908. };
  909. #undef BUILTIN_ROW
  910. // Determine the index of the size.
  911. unsigned SizeIndex;
  912. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  913. case 1: SizeIndex = 0; break;
  914. case 2: SizeIndex = 1; break;
  915. case 4: SizeIndex = 2; break;
  916. case 8: SizeIndex = 3; break;
  917. case 16: SizeIndex = 4; break;
  918. default:
  919. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  920. << FirstArg->getType() << FirstArg->getSourceRange();
  921. return ExprError();
  922. }
  923. // Each of these builtins has one pointer argument, followed by some number of
  924. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  925. // that we ignore. Find out which row of BuiltinIndices to read from as well
  926. // as the number of fixed args.
  927. unsigned BuiltinID = FDecl->getBuiltinID();
  928. unsigned BuiltinIndex, NumFixed = 1;
  929. switch (BuiltinID) {
  930. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  931. case Builtin::BI__sync_fetch_and_add:
  932. case Builtin::BI__sync_fetch_and_add_1:
  933. case Builtin::BI__sync_fetch_and_add_2:
  934. case Builtin::BI__sync_fetch_and_add_4:
  935. case Builtin::BI__sync_fetch_and_add_8:
  936. case Builtin::BI__sync_fetch_and_add_16:
  937. BuiltinIndex = 0;
  938. break;
  939. case Builtin::BI__sync_fetch_and_sub:
  940. case Builtin::BI__sync_fetch_and_sub_1:
  941. case Builtin::BI__sync_fetch_and_sub_2:
  942. case Builtin::BI__sync_fetch_and_sub_4:
  943. case Builtin::BI__sync_fetch_and_sub_8:
  944. case Builtin::BI__sync_fetch_and_sub_16:
  945. BuiltinIndex = 1;
  946. break;
  947. case Builtin::BI__sync_fetch_and_or:
  948. case Builtin::BI__sync_fetch_and_or_1:
  949. case Builtin::BI__sync_fetch_and_or_2:
  950. case Builtin::BI__sync_fetch_and_or_4:
  951. case Builtin::BI__sync_fetch_and_or_8:
  952. case Builtin::BI__sync_fetch_and_or_16:
  953. BuiltinIndex = 2;
  954. break;
  955. case Builtin::BI__sync_fetch_and_and:
  956. case Builtin::BI__sync_fetch_and_and_1:
  957. case Builtin::BI__sync_fetch_and_and_2:
  958. case Builtin::BI__sync_fetch_and_and_4:
  959. case Builtin::BI__sync_fetch_and_and_8:
  960. case Builtin::BI__sync_fetch_and_and_16:
  961. BuiltinIndex = 3;
  962. break;
  963. case Builtin::BI__sync_fetch_and_xor:
  964. case Builtin::BI__sync_fetch_and_xor_1:
  965. case Builtin::BI__sync_fetch_and_xor_2:
  966. case Builtin::BI__sync_fetch_and_xor_4:
  967. case Builtin::BI__sync_fetch_and_xor_8:
  968. case Builtin::BI__sync_fetch_and_xor_16:
  969. BuiltinIndex = 4;
  970. break;
  971. case Builtin::BI__sync_add_and_fetch:
  972. case Builtin::BI__sync_add_and_fetch_1:
  973. case Builtin::BI__sync_add_and_fetch_2:
  974. case Builtin::BI__sync_add_and_fetch_4:
  975. case Builtin::BI__sync_add_and_fetch_8:
  976. case Builtin::BI__sync_add_and_fetch_16:
  977. BuiltinIndex = 5;
  978. break;
  979. case Builtin::BI__sync_sub_and_fetch:
  980. case Builtin::BI__sync_sub_and_fetch_1:
  981. case Builtin::BI__sync_sub_and_fetch_2:
  982. case Builtin::BI__sync_sub_and_fetch_4:
  983. case Builtin::BI__sync_sub_and_fetch_8:
  984. case Builtin::BI__sync_sub_and_fetch_16:
  985. BuiltinIndex = 6;
  986. break;
  987. case Builtin::BI__sync_and_and_fetch:
  988. case Builtin::BI__sync_and_and_fetch_1:
  989. case Builtin::BI__sync_and_and_fetch_2:
  990. case Builtin::BI__sync_and_and_fetch_4:
  991. case Builtin::BI__sync_and_and_fetch_8:
  992. case Builtin::BI__sync_and_and_fetch_16:
  993. BuiltinIndex = 7;
  994. break;
  995. case Builtin::BI__sync_or_and_fetch:
  996. case Builtin::BI__sync_or_and_fetch_1:
  997. case Builtin::BI__sync_or_and_fetch_2:
  998. case Builtin::BI__sync_or_and_fetch_4:
  999. case Builtin::BI__sync_or_and_fetch_8:
  1000. case Builtin::BI__sync_or_and_fetch_16:
  1001. BuiltinIndex = 8;
  1002. break;
  1003. case Builtin::BI__sync_xor_and_fetch:
  1004. case Builtin::BI__sync_xor_and_fetch_1:
  1005. case Builtin::BI__sync_xor_and_fetch_2:
  1006. case Builtin::BI__sync_xor_and_fetch_4:
  1007. case Builtin::BI__sync_xor_and_fetch_8:
  1008. case Builtin::BI__sync_xor_and_fetch_16:
  1009. BuiltinIndex = 9;
  1010. break;
  1011. case Builtin::BI__sync_val_compare_and_swap:
  1012. case Builtin::BI__sync_val_compare_and_swap_1:
  1013. case Builtin::BI__sync_val_compare_and_swap_2:
  1014. case Builtin::BI__sync_val_compare_and_swap_4:
  1015. case Builtin::BI__sync_val_compare_and_swap_8:
  1016. case Builtin::BI__sync_val_compare_and_swap_16:
  1017. BuiltinIndex = 10;
  1018. NumFixed = 2;
  1019. break;
  1020. case Builtin::BI__sync_bool_compare_and_swap:
  1021. case Builtin::BI__sync_bool_compare_and_swap_1:
  1022. case Builtin::BI__sync_bool_compare_and_swap_2:
  1023. case Builtin::BI__sync_bool_compare_and_swap_4:
  1024. case Builtin::BI__sync_bool_compare_and_swap_8:
  1025. case Builtin::BI__sync_bool_compare_and_swap_16:
  1026. BuiltinIndex = 11;
  1027. NumFixed = 2;
  1028. ResultType = Context.BoolTy;
  1029. break;
  1030. case Builtin::BI__sync_lock_test_and_set:
  1031. case Builtin::BI__sync_lock_test_and_set_1:
  1032. case Builtin::BI__sync_lock_test_and_set_2:
  1033. case Builtin::BI__sync_lock_test_and_set_4:
  1034. case Builtin::BI__sync_lock_test_and_set_8:
  1035. case Builtin::BI__sync_lock_test_and_set_16:
  1036. BuiltinIndex = 12;
  1037. break;
  1038. case Builtin::BI__sync_lock_release:
  1039. case Builtin::BI__sync_lock_release_1:
  1040. case Builtin::BI__sync_lock_release_2:
  1041. case Builtin::BI__sync_lock_release_4:
  1042. case Builtin::BI__sync_lock_release_8:
  1043. case Builtin::BI__sync_lock_release_16:
  1044. BuiltinIndex = 13;
  1045. NumFixed = 0;
  1046. ResultType = Context.VoidTy;
  1047. break;
  1048. case Builtin::BI__sync_swap:
  1049. case Builtin::BI__sync_swap_1:
  1050. case Builtin::BI__sync_swap_2:
  1051. case Builtin::BI__sync_swap_4:
  1052. case Builtin::BI__sync_swap_8:
  1053. case Builtin::BI__sync_swap_16:
  1054. BuiltinIndex = 14;
  1055. break;
  1056. }
  1057. // Now that we know how many fixed arguments we expect, first check that we
  1058. // have at least that many.
  1059. if (TheCall->getNumArgs() < 1+NumFixed) {
  1060. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  1061. << 0 << 1+NumFixed << TheCall->getNumArgs()
  1062. << TheCall->getCallee()->getSourceRange();
  1063. return ExprError();
  1064. }
  1065. // Get the decl for the concrete builtin from this, we can tell what the
  1066. // concrete integer type we should convert to is.
  1067. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  1068. const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
  1069. IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
  1070. FunctionDecl *NewBuiltinDecl =
  1071. cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
  1072. TUScope, false, DRE->getLocStart()));
  1073. // The first argument --- the pointer --- has a fixed type; we
  1074. // deduce the types of the rest of the arguments accordingly. Walk
  1075. // the remaining arguments, converting them to the deduced value type.
  1076. for (unsigned i = 0; i != NumFixed; ++i) {
  1077. ExprResult Arg = TheCall->getArg(i+1);
  1078. // GCC does an implicit conversion to the pointer or integer ValType. This
  1079. // can fail in some cases (1i -> int**), check for this error case now.
  1080. // Initialize the argument.
  1081. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  1082. ValType, /*consume*/ false);
  1083. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1084. if (Arg.isInvalid())
  1085. return ExprError();
  1086. // Okay, we have something that *can* be converted to the right type. Check
  1087. // to see if there is a potentially weird extension going on here. This can
  1088. // happen when you do an atomic operation on something like an char* and
  1089. // pass in 42. The 42 gets converted to char. This is even more strange
  1090. // for things like 45.123 -> char, etc.
  1091. // FIXME: Do this check.
  1092. TheCall->setArg(i+1, Arg.take());
  1093. }
  1094. ASTContext& Context = this->getASTContext();
  1095. // Create a new DeclRefExpr to refer to the new decl.
  1096. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  1097. Context,
  1098. DRE->getQualifierLoc(),
  1099. SourceLocation(),
  1100. NewBuiltinDecl,
  1101. /*enclosing*/ false,
  1102. DRE->getLocation(),
  1103. NewBuiltinDecl->getType(),
  1104. DRE->getValueKind());
  1105. // Set the callee in the CallExpr.
  1106. // FIXME: This leaks the original parens and implicit casts.
  1107. ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
  1108. if (PromotedCall.isInvalid())
  1109. return ExprError();
  1110. TheCall->setCallee(PromotedCall.take());
  1111. // Change the result type of the call to match the original value type. This
  1112. // is arbitrary, but the codegen for these builtins ins design to handle it
  1113. // gracefully.
  1114. TheCall->setType(ResultType);
  1115. return move(TheCallResult);
  1116. }
  1117. /// CheckObjCString - Checks that the argument to the builtin
  1118. /// CFString constructor is correct
  1119. /// Note: It might also make sense to do the UTF-16 conversion here (would
  1120. /// simplify the backend).
  1121. bool Sema::CheckObjCString(Expr *Arg) {
  1122. Arg = Arg->IgnoreParenCasts();
  1123. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  1124. if (!Literal || !Literal->isAscii()) {
  1125. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  1126. << Arg->getSourceRange();
  1127. return true;
  1128. }
  1129. if (Literal->containsNonAsciiOrNull()) {
  1130. StringRef String = Literal->getString();
  1131. unsigned NumBytes = String.size();
  1132. SmallVector<UTF16, 128> ToBuf(NumBytes);
  1133. const UTF8 *FromPtr = (UTF8 *)String.data();
  1134. UTF16 *ToPtr = &ToBuf[0];
  1135. ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1136. &ToPtr, ToPtr + NumBytes,
  1137. strictConversion);
  1138. // Check for conversion failure.
  1139. if (Result != conversionOK)
  1140. Diag(Arg->getLocStart(),
  1141. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  1142. }
  1143. return false;
  1144. }
  1145. /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
  1146. /// Emit an error and return true on failure, return false on success.
  1147. bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
  1148. Expr *Fn = TheCall->getCallee();
  1149. if (TheCall->getNumArgs() > 2) {
  1150. Diag(TheCall->getArg(2)->getLocStart(),
  1151. diag::err_typecheck_call_too_many_args)
  1152. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1153. << Fn->getSourceRange()
  1154. << SourceRange(TheCall->getArg(2)->getLocStart(),
  1155. (*(TheCall->arg_end()-1))->getLocEnd());
  1156. return true;
  1157. }
  1158. if (TheCall->getNumArgs() < 2) {
  1159. return Diag(TheCall->getLocEnd(),
  1160. diag::err_typecheck_call_too_few_args_at_least)
  1161. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  1162. }
  1163. // Type-check the first argument normally.
  1164. if (checkBuiltinArgument(*this, TheCall, 0))
  1165. return true;
  1166. // Determine whether the current function is variadic or not.
  1167. BlockScopeInfo *CurBlock = getCurBlock();
  1168. bool isVariadic;
  1169. if (CurBlock)
  1170. isVariadic = CurBlock->TheDecl->isVariadic();
  1171. else if (FunctionDecl *FD = getCurFunctionDecl())
  1172. isVariadic = FD->isVariadic();
  1173. else
  1174. isVariadic = getCurMethodDecl()->isVariadic();
  1175. if (!isVariadic) {
  1176. Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
  1177. return true;
  1178. }
  1179. // Verify that the second argument to the builtin is the last argument of the
  1180. // current function or method.
  1181. bool SecondArgIsLastNamedArgument = false;
  1182. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  1183. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  1184. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  1185. // FIXME: This isn't correct for methods (results in bogus warning).
  1186. // Get the last formal in the current function.
  1187. const ParmVarDecl *LastArg;
  1188. if (CurBlock)
  1189. LastArg = *(CurBlock->TheDecl->param_end()-1);
  1190. else if (FunctionDecl *FD = getCurFunctionDecl())
  1191. LastArg = *(FD->param_end()-1);
  1192. else
  1193. LastArg = *(getCurMethodDecl()->param_end()-1);
  1194. SecondArgIsLastNamedArgument = PV == LastArg;
  1195. }
  1196. }
  1197. if (!SecondArgIsLastNamedArgument)
  1198. Diag(TheCall->getArg(1)->getLocStart(),
  1199. diag::warn_second_parameter_of_va_start_not_last_named_argument);
  1200. return false;
  1201. }
  1202. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  1203. /// friends. This is declared to take (...), so we have to check everything.
  1204. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  1205. if (TheCall->getNumArgs() < 2)
  1206. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1207. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  1208. if (TheCall->getNumArgs() > 2)
  1209. return Diag(TheCall->getArg(2)->getLocStart(),
  1210. diag::err_typecheck_call_too_many_args)
  1211. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1212. << SourceRange(TheCall->getArg(2)->getLocStart(),
  1213. (*(TheCall->arg_end()-1))->getLocEnd());
  1214. ExprResult OrigArg0 = TheCall->getArg(0);
  1215. ExprResult OrigArg1 = TheCall->getArg(1);
  1216. // Do standard promotions between the two arguments, returning their common
  1217. // type.
  1218. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  1219. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  1220. return true;
  1221. // Make sure any conversions are pushed back into the call; this is
  1222. // type safe since unordered compare builtins are declared as "_Bool
  1223. // foo(...)".
  1224. TheCall->setArg(0, OrigArg0.get());
  1225. TheCall->setArg(1, OrigArg1.get());
  1226. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  1227. return false;
  1228. // If the common type isn't a real floating type, then the arguments were
  1229. // invalid for this operation.
  1230. if (Res.isNull() || !Res->isRealFloatingType())
  1231. return Diag(OrigArg0.get()->getLocStart(),
  1232. diag::err_typecheck_call_invalid_ordered_compare)
  1233. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  1234. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  1235. return false;
  1236. }
  1237. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  1238. /// __builtin_isnan and friends. This is declared to take (...), so we have
  1239. /// to check everything. We expect the last argument to be a floating point
  1240. /// value.
  1241. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  1242. if (TheCall->getNumArgs() < NumArgs)
  1243. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1244. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  1245. if (TheCall->getNumArgs() > NumArgs)
  1246. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  1247. diag::err_typecheck_call_too_many_args)
  1248. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  1249. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  1250. (*(TheCall->arg_end()-1))->getLocEnd());
  1251. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  1252. if (OrigArg->isTypeDependent())
  1253. return false;
  1254. // This operation requires a non-_Complex floating-point number.
  1255. if (!OrigArg->getType()->isRealFloatingType())
  1256. return Diag(OrigArg->getLocStart(),
  1257. diag::err_typecheck_call_invalid_unary_fp)
  1258. << OrigArg->getType() << OrigArg->getSourceRange();
  1259. // If this is an implicit conversion from float -> double, remove it.
  1260. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  1261. Expr *CastArg = Cast->getSubExpr();
  1262. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  1263. assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
  1264. "promotion from float to double is the only expected cast here");
  1265. Cast->setSubExpr(0);
  1266. TheCall->setArg(NumArgs-1, CastArg);
  1267. }
  1268. }
  1269. return false;
  1270. }
  1271. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  1272. // This is declared to take (...), so we have to check everything.
  1273. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  1274. if (TheCall->getNumArgs() < 2)
  1275. return ExprError(Diag(TheCall->getLocEnd(),
  1276. diag::err_typecheck_call_too_few_args_at_least)
  1277. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1278. << TheCall->getSourceRange());
  1279. // Determine which of the following types of shufflevector we're checking:
  1280. // 1) unary, vector mask: (lhs, mask)
  1281. // 2) binary, vector mask: (lhs, rhs, mask)
  1282. // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
  1283. QualType resType = TheCall->getArg(0)->getType();
  1284. unsigned numElements = 0;
  1285. if (!TheCall->getArg(0)->isTypeDependent() &&
  1286. !TheCall->getArg(1)->isTypeDependent()) {
  1287. QualType LHSType = TheCall->getArg(0)->getType();
  1288. QualType RHSType = TheCall->getArg(1)->getType();
  1289. if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
  1290. Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
  1291. << SourceRange(TheCall->getArg(0)->getLocStart(),
  1292. TheCall->getArg(1)->getLocEnd());
  1293. return ExprError();
  1294. }
  1295. numElements = LHSType->getAs<VectorType>()->getNumElements();
  1296. unsigned numResElements = TheCall->getNumArgs() - 2;
  1297. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  1298. // with mask. If so, verify that RHS is an integer vector type with the
  1299. // same number of elts as lhs.
  1300. if (TheCall->getNumArgs() == 2) {
  1301. if (!RHSType->hasIntegerRepresentation() ||
  1302. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  1303. Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
  1304. << SourceRange(TheCall->getArg(1)->getLocStart(),
  1305. TheCall->getArg(1)->getLocEnd());
  1306. numResElements = numElements;
  1307. }
  1308. else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  1309. Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
  1310. << SourceRange(TheCall->getArg(0)->getLocStart(),
  1311. TheCall->getArg(1)->getLocEnd());
  1312. return ExprError();
  1313. } else if (numElements != numResElements) {
  1314. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  1315. resType = Context.getVectorType(eltType, numResElements,
  1316. VectorType::GenericVector);
  1317. }
  1318. }
  1319. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  1320. if (TheCall->getArg(i)->isTypeDependent() ||
  1321. TheCall->getArg(i)->isValueDependent())
  1322. continue;
  1323. llvm::APSInt Result(32);
  1324. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  1325. return ExprError(Diag(TheCall->getLocStart(),
  1326. diag::err_shufflevector_nonconstant_argument)
  1327. << TheCall->getArg(i)->getSourceRange());
  1328. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  1329. return ExprError(Diag(TheCall->getLocStart(),
  1330. diag::err_shufflevector_argument_too_large)
  1331. << TheCall->getArg(i)->getSourceRange());
  1332. }
  1333. SmallVector<Expr*, 32> exprs;
  1334. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  1335. exprs.push_back(TheCall->getArg(i));
  1336. TheCall->setArg(i, 0);
  1337. }
  1338. return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
  1339. exprs.size(), resType,
  1340. TheCall->getCallee()->getLocStart(),
  1341. TheCall->getRParenLoc()));
  1342. }
  1343. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  1344. // This is declared to take (const void*, ...) and can take two
  1345. // optional constant int args.
  1346. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  1347. unsigned NumArgs = TheCall->getNumArgs();
  1348. if (NumArgs > 3)
  1349. return Diag(TheCall->getLocEnd(),
  1350. diag::err_typecheck_call_too_many_args_at_most)
  1351. << 0 /*function call*/ << 3 << NumArgs
  1352. << TheCall->getSourceRange();
  1353. // Argument 0 is checked for us and the remaining arguments must be
  1354. // constant integers.
  1355. for (unsigned i = 1; i != NumArgs; ++i) {
  1356. Expr *Arg = TheCall->getArg(i);
  1357. // We can't check the value of a dependent argument.
  1358. if (Arg->isTypeDependent() || Arg->isValueDependent())
  1359. continue;
  1360. llvm::APSInt Result;
  1361. if (SemaBuiltinConstantArg(TheCall, i, Result))
  1362. return true;
  1363. // FIXME: gcc issues a warning and rewrites these to 0. These
  1364. // seems especially odd for the third argument since the default
  1365. // is 3.
  1366. if (i == 1) {
  1367. if (Result.getLimitedValue() > 1)
  1368. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1369. << "0" << "1" << Arg->getSourceRange();
  1370. } else {
  1371. if (Result.getLimitedValue() > 3)
  1372. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1373. << "0" << "3" << Arg->getSourceRange();
  1374. }
  1375. }
  1376. return false;
  1377. }
  1378. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  1379. /// TheCall is a constant expression.
  1380. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  1381. llvm::APSInt &Result) {
  1382. Expr *Arg = TheCall->getArg(ArgNum);
  1383. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1384. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  1385. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  1386. if (!Arg->isIntegerConstantExpr(Result, Context))
  1387. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  1388. << FDecl->getDeclName() << Arg->getSourceRange();
  1389. return false;
  1390. }
  1391. /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
  1392. /// int type). This simply type checks that type is one of the defined
  1393. /// constants (0-3).
  1394. // For compatibility check 0-3, llvm only handles 0 and 2.
  1395. bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
  1396. llvm::APSInt Result;
  1397. // We can't check the value of a dependent argument.
  1398. if (TheCall->getArg(1)->isTypeDependent() ||
  1399. TheCall->getArg(1)->isValueDependent())
  1400. return false;
  1401. // Check constant-ness first.
  1402. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  1403. return true;
  1404. Expr *Arg = TheCall->getArg(1);
  1405. if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
  1406. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1407. << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  1408. }
  1409. return false;
  1410. }
  1411. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  1412. /// This checks that val is a constant 1.
  1413. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  1414. Expr *Arg = TheCall->getArg(1);
  1415. llvm::APSInt Result;
  1416. // TODO: This is less than ideal. Overload this to take a value.
  1417. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  1418. return true;
  1419. if (Result != 1)
  1420. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  1421. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  1422. return false;
  1423. }
  1424. // Determine if an expression is a string literal or constant string.
  1425. // If this function returns false on the arguments to a function expecting a
  1426. // format string, we will usually need to emit a warning.
  1427. // True string literals are then checked by CheckFormatString.
  1428. Sema::StringLiteralCheckType
  1429. Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
  1430. unsigned NumArgs, bool HasVAListArg,
  1431. unsigned format_idx, unsigned firstDataArg,
  1432. FormatStringType Type, VariadicCallType CallType,
  1433. bool inFunctionCall) {
  1434. tryAgain:
  1435. if (E->isTypeDependent() || E->isValueDependent())
  1436. return SLCT_NotALiteral;
  1437. E = E->IgnoreParenCasts();
  1438. if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
  1439. // Technically -Wformat-nonliteral does not warn about this case.
  1440. // The behavior of printf and friends in this case is implementation
  1441. // dependent. Ideally if the format string cannot be null then
  1442. // it should have a 'nonnull' attribute in the function prototype.
  1443. return SLCT_CheckedLiteral;
  1444. switch (E->getStmtClass()) {
  1445. case Stmt::BinaryConditionalOperatorClass:
  1446. case Stmt::ConditionalOperatorClass: {
  1447. // The expression is a literal if both sub-expressions were, and it was
  1448. // completely checked only if both sub-expressions were checked.
  1449. const AbstractConditionalOperator *C =
  1450. cast<AbstractConditionalOperator>(E);
  1451. StringLiteralCheckType Left =
  1452. checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
  1453. HasVAListArg, format_idx, firstDataArg,
  1454. Type, CallType, inFunctionCall);
  1455. if (Left == SLCT_NotALiteral)
  1456. return SLCT_NotALiteral;
  1457. StringLiteralCheckType Right =
  1458. checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
  1459. HasVAListArg, format_idx, firstDataArg,
  1460. Type, CallType, inFunctionCall);
  1461. return Left < Right ? Left : Right;
  1462. }
  1463. case Stmt::ImplicitCastExprClass: {
  1464. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  1465. goto tryAgain;
  1466. }
  1467. case Stmt::OpaqueValueExprClass:
  1468. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  1469. E = src;
  1470. goto tryAgain;
  1471. }
  1472. return SLCT_NotALiteral;
  1473. case Stmt::PredefinedExprClass:
  1474. // While __func__, etc., are technically not string literals, they
  1475. // cannot contain format specifiers and thus are not a security
  1476. // liability.
  1477. return SLCT_UncheckedLiteral;
  1478. case Stmt::DeclRefExprClass: {
  1479. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  1480. // As an exception, do not flag errors for variables binding to
  1481. // const string literals.
  1482. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1483. bool isConstant = false;
  1484. QualType T = DR->getType();
  1485. if (const ArrayType *AT = Context.getAsArrayType(T)) {
  1486. isConstant = AT->getElementType().isConstant(Context);
  1487. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  1488. isConstant = T.isConstant(Context) &&
  1489. PT->getPointeeType().isConstant(Context);
  1490. } else if (T->isObjCObjectPointerType()) {
  1491. // In ObjC, there is usually no "const ObjectPointer" type,
  1492. // so don't check if the pointee type is constant.
  1493. isConstant = T.isConstant(Context);
  1494. }
  1495. if (isConstant) {
  1496. if (const Expr *Init = VD->getAnyInitializer()) {
  1497. // Look through initializers like const char c[] = { "foo" }
  1498. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  1499. if (InitList->isStringLiteralInit())
  1500. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  1501. }
  1502. return checkFormatStringExpr(Init, Args, NumArgs,
  1503. HasVAListArg, format_idx,
  1504. firstDataArg, Type, CallType,
  1505. /*inFunctionCall*/false);
  1506. }
  1507. }
  1508. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  1509. // special check to see if the format string is a function parameter
  1510. // of the function calling the printf function. If the function
  1511. // has an attribute indicating it is a printf-like function, then we
  1512. // should suppress warnings concerning non-literals being used in a call
  1513. // to a vprintf function. For example:
  1514. //
  1515. // void
  1516. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  1517. // va_list ap;
  1518. // va_start(ap, fmt);
  1519. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  1520. // ...
  1521. //
  1522. if (HasVAListArg) {
  1523. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  1524. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  1525. int PVIndex = PV->getFunctionScopeIndex() + 1;
  1526. for (specific_attr_iterator<FormatAttr>
  1527. i = ND->specific_attr_begin<FormatAttr>(),
  1528. e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
  1529. FormatAttr *PVFormat = *i;
  1530. // adjust for implicit parameter
  1531. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  1532. if (MD->isInstance())
  1533. ++PVIndex;
  1534. // We also check if the formats are compatible.
  1535. // We can't pass a 'scanf' string to a 'printf' function.
  1536. if (PVIndex == PVFormat->getFormatIdx() &&
  1537. Type == GetFormatStringType(PVFormat))
  1538. return SLCT_UncheckedLiteral;
  1539. }
  1540. }
  1541. }
  1542. }
  1543. }
  1544. return SLCT_NotALiteral;
  1545. }
  1546. case Stmt::CallExprClass:
  1547. case Stmt::CXXMemberCallExprClass: {
  1548. const CallExpr *CE = cast<CallExpr>(E);
  1549. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  1550. if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
  1551. unsigned ArgIndex = FA->getFormatIdx();
  1552. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  1553. if (MD->isInstance())
  1554. --ArgIndex;
  1555. const Expr *Arg = CE->getArg(ArgIndex - 1);
  1556. return checkFormatStringExpr(Arg, Args, NumArgs,
  1557. HasVAListArg, format_idx, firstDataArg,
  1558. Type, CallType, inFunctionCall);
  1559. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  1560. unsigned BuiltinID = FD->getBuiltinID();
  1561. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  1562. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  1563. const Expr *Arg = CE->getArg(0);
  1564. return checkFormatStringExpr(Arg, Args, NumArgs,
  1565. HasVAListArg, format_idx,
  1566. firstDataArg, Type, CallType,
  1567. inFunctionCall);
  1568. }
  1569. }
  1570. }
  1571. return SLCT_NotALiteral;
  1572. }
  1573. case Stmt::ObjCStringLiteralClass:
  1574. case Stmt::StringLiteralClass: {
  1575. const StringLiteral *StrE = NULL;
  1576. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  1577. StrE = ObjCFExpr->getString();
  1578. else
  1579. StrE = cast<StringLiteral>(E);
  1580. if (StrE) {
  1581. CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
  1582. firstDataArg, Type, inFunctionCall, CallType);
  1583. return SLCT_CheckedLiteral;
  1584. }
  1585. return SLCT_NotALiteral;
  1586. }
  1587. default:
  1588. return SLCT_NotALiteral;
  1589. }
  1590. }
  1591. void
  1592. Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
  1593. const Expr * const *ExprArgs,
  1594. SourceLocation CallSiteLoc) {
  1595. for (NonNullAttr::args_iterator i = NonNull->args_begin(),
  1596. e = NonNull->args_end();
  1597. i != e; ++i) {
  1598. const Expr *ArgExpr = ExprArgs[*i];
  1599. if (ArgExpr->isNullPointerConstant(Context,
  1600. Expr::NPC_ValueDependentIsNotNull))
  1601. Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  1602. }
  1603. }
  1604. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  1605. return llvm::StringSwitch<FormatStringType>(Format->getType())
  1606. .Case("scanf", FST_Scanf)
  1607. .Cases("printf", "printf0", FST_Printf)
  1608. .Cases("NSString", "CFString", FST_NSString)
  1609. .Case("strftime", FST_Strftime)
  1610. .Case("strfmon", FST_Strfmon)
  1611. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  1612. .Default(FST_Unknown);
  1613. }
  1614. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  1615. /// functions) for correct use of format strings.
  1616. /// Returns true if a format string has been fully checked.
  1617. bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
  1618. unsigned NumArgs, bool IsCXXMember,
  1619. VariadicCallType CallType,
  1620. SourceLocation Loc, SourceRange Range) {
  1621. FormatStringInfo FSI;
  1622. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  1623. return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
  1624. FSI.FirstDataArg, GetFormatStringType(Format),
  1625. CallType, Loc, Range);
  1626. return false;
  1627. }
  1628. bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
  1629. bool HasVAListArg, unsigned format_idx,
  1630. unsigned firstDataArg, FormatStringType Type,
  1631. VariadicCallType CallType,
  1632. SourceLocation Loc, SourceRange Range) {
  1633. // CHECK: printf/scanf-like function is called with no format string.
  1634. if (format_idx >= NumArgs) {
  1635. Diag(Loc, diag::warn_missing_format_string) << Range;
  1636. return false;
  1637. }
  1638. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  1639. // CHECK: format string is not a string literal.
  1640. //
  1641. // Dynamically generated format strings are difficult to
  1642. // automatically vet at compile time. Requiring that format strings
  1643. // are string literals: (1) permits the checking of format strings by
  1644. // the compiler and thereby (2) can practically remove the source of
  1645. // many format string exploits.
  1646. // Format string can be either ObjC string (e.g. @"%d") or
  1647. // C string (e.g. "%d")
  1648. // ObjC string uses the same format specifiers as C string, so we can use
  1649. // the same format string checking logic for both ObjC and C strings.
  1650. StringLiteralCheckType CT =
  1651. checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
  1652. format_idx, firstDataArg, Type, CallType);
  1653. if (CT != SLCT_NotALiteral)
  1654. // Literal format string found, check done!
  1655. return CT == SLCT_CheckedLiteral;
  1656. // Strftime is particular as it always uses a single 'time' argument,
  1657. // so it is safe to pass a non-literal string.
  1658. if (Type == FST_Strftime)
  1659. return false;
  1660. // Do not emit diag when the string param is a macro expansion and the
  1661. // format is either NSString or CFString. This is a hack to prevent
  1662. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  1663. // which are usually used in place of NS and CF string literals.
  1664. if (Type == FST_NSString &&
  1665. SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
  1666. return false;
  1667. // If there are no arguments specified, warn with -Wformat-security, otherwise
  1668. // warn only with -Wformat-nonliteral.
  1669. if (NumArgs == format_idx+1)
  1670. Diag(Args[format_idx]->getLocStart(),
  1671. diag::warn_format_nonliteral_noargs)
  1672. << OrigFormatExpr->getSourceRange();
  1673. else
  1674. Diag(Args[format_idx]->getLocStart(),
  1675. diag::warn_format_nonliteral)
  1676. << OrigFormatExpr->getSourceRange();
  1677. return false;
  1678. }
  1679. namespace {
  1680. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  1681. protected:
  1682. Sema &S;
  1683. const StringLiteral *FExpr;
  1684. const Expr *OrigFormatExpr;
  1685. const unsigned FirstDataArg;
  1686. const unsigned NumDataArgs;
  1687. const char *Beg; // Start of format string.
  1688. const bool HasVAListArg;
  1689. const Expr * const *Args;
  1690. const unsigned NumArgs;
  1691. unsigned FormatIdx;
  1692. llvm::BitVector CoveredArgs;
  1693. bool usesPositionalArgs;
  1694. bool atFirstArg;
  1695. bool inFunctionCall;
  1696. Sema::VariadicCallType CallType;
  1697. public:
  1698. CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
  1699. const Expr *origFormatExpr, unsigned firstDataArg,
  1700. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  1701. Expr **args, unsigned numArgs,
  1702. unsigned formatIdx, bool inFunctionCall,
  1703. Sema::VariadicCallType callType)
  1704. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
  1705. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
  1706. Beg(beg), HasVAListArg(hasVAListArg),
  1707. Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
  1708. usesPositionalArgs(false), atFirstArg(true),
  1709. inFunctionCall(inFunctionCall), CallType(callType) {
  1710. CoveredArgs.resize(numDataArgs);
  1711. CoveredArgs.reset();
  1712. }
  1713. void DoneProcessing();
  1714. void HandleIncompleteSpecifier(const char *startSpecifier,
  1715. unsigned specifierLen);
  1716. void HandleNonStandardLengthModifier(
  1717. const analyze_format_string::LengthModifier &LM,
  1718. const char *startSpecifier, unsigned specifierLen);
  1719. void HandleNonStandardConversionSpecifier(
  1720. const analyze_format_string::ConversionSpecifier &CS,
  1721. const char *startSpecifier, unsigned specifierLen);
  1722. void HandleNonStandardConversionSpecification(
  1723. const analyze_format_string::LengthModifier &LM,
  1724. const analyze_format_string::ConversionSpecifier &CS,
  1725. const char *startSpecifier, unsigned specifierLen);
  1726. virtual void HandlePosition(const char *startPos, unsigned posLen);
  1727. virtual void HandleInvalidPosition(const char *startSpecifier,
  1728. unsigned specifierLen,
  1729. analyze_format_string::PositionContext p);
  1730. virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
  1731. void HandleNullChar(const char *nullCharacter);
  1732. template <typename Range>
  1733. static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
  1734. const Expr *ArgumentExpr,
  1735. PartialDiagnostic PDiag,
  1736. SourceLocation StringLoc,
  1737. bool IsStringLocation, Range StringRange,
  1738. FixItHint Fixit = FixItHint());
  1739. protected:
  1740. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  1741. const char *startSpec,
  1742. unsigned specifierLen,
  1743. const char *csStart, unsigned csLen);
  1744. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  1745. const char *startSpec,
  1746. unsigned specifierLen);
  1747. SourceRange getFormatStringRange();
  1748. CharSourceRange getSpecifierRange(const char *startSpecifier,
  1749. unsigned specifierLen);
  1750. SourceLocation getLocationOfByte(const char *x);
  1751. const Expr *getDataArg(unsigned i) const;
  1752. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  1753. const analyze_format_string::ConversionSpecifier &CS,
  1754. const char *startSpecifier, unsigned specifierLen,
  1755. unsigned argIndex);
  1756. template <typename Range>
  1757. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  1758. bool IsStringLocation, Range StringRange,
  1759. FixItHint Fixit = FixItHint());
  1760. void CheckPositionalAndNonpositionalArgs(
  1761. const analyze_format_string::FormatSpecifier *FS);
  1762. };
  1763. }
  1764. SourceRange CheckFormatHandler::getFormatStringRange() {
  1765. return OrigFormatExpr->getSourceRange();
  1766. }
  1767. CharSourceRange CheckFormatHandler::
  1768. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  1769. SourceLocation Start = getLocationOfByte(startSpecifier);
  1770. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  1771. // Advance the end SourceLocation by one due to half-open ranges.
  1772. End = End.getLocWithOffset(1);
  1773. return CharSourceRange::getCharRange(Start, End);
  1774. }
  1775. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  1776. return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
  1777. }
  1778. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  1779. unsigned specifierLen){
  1780. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  1781. getLocationOfByte(startSpecifier),
  1782. /*IsStringLocation*/true,
  1783. getSpecifierRange(startSpecifier, specifierLen));
  1784. }
  1785. void CheckFormatHandler::HandleNonStandardLengthModifier(
  1786. const analyze_format_string::LengthModifier &LM,
  1787. const char *startSpecifier, unsigned specifierLen) {
  1788. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
  1789. << 0,
  1790. getLocationOfByte(LM.getStart()),
  1791. /*IsStringLocation*/true,
  1792. getSpecifierRange(startSpecifier, specifierLen));
  1793. }
  1794. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  1795. const analyze_format_string::ConversionSpecifier &CS,
  1796. const char *startSpecifier, unsigned specifierLen) {
  1797. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
  1798. << 1,
  1799. getLocationOfByte(CS.getStart()),
  1800. /*IsStringLocation*/true,
  1801. getSpecifierRange(startSpecifier, specifierLen));
  1802. }
  1803. void CheckFormatHandler::HandleNonStandardConversionSpecification(
  1804. const analyze_format_string::LengthModifier &LM,
  1805. const analyze_format_string::ConversionSpecifier &CS,
  1806. const char *startSpecifier, unsigned specifierLen) {
  1807. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
  1808. << LM.toString() << CS.toString(),
  1809. getLocationOfByte(LM.getStart()),
  1810. /*IsStringLocation*/true,
  1811. getSpecifierRange(startSpecifier, specifierLen));
  1812. }
  1813. void CheckFormatHandler::HandlePosition(const char *startPos,
  1814. unsigned posLen) {
  1815. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  1816. getLocationOfByte(startPos),
  1817. /*IsStringLocation*/true,
  1818. getSpecifierRange(startPos, posLen));
  1819. }
  1820. void
  1821. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  1822. analyze_format_string::PositionContext p) {
  1823. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  1824. << (unsigned) p,
  1825. getLocationOfByte(startPos), /*IsStringLocation*/true,
  1826. getSpecifierRange(startPos, posLen));
  1827. }
  1828. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  1829. unsigned posLen) {
  1830. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  1831. getLocationOfByte(startPos),
  1832. /*IsStringLocation*/true,
  1833. getSpecifierRange(startPos, posLen));
  1834. }
  1835. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  1836. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  1837. // The presence of a null character is likely an error.
  1838. EmitFormatDiagnostic(
  1839. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  1840. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  1841. getFormatStringRange());
  1842. }
  1843. }
  1844. // Note that this may return NULL if there was an error parsing or building
  1845. // one of the argument expressions.
  1846. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  1847. return Args[FirstDataArg + i];
  1848. }
  1849. void CheckFormatHandler::DoneProcessing() {
  1850. // Does the number of data arguments exceed the number of
  1851. // format conversions in the format string?
  1852. if (!HasVAListArg) {
  1853. // Find any arguments that weren't covered.
  1854. CoveredArgs.flip();
  1855. signed notCoveredArg = CoveredArgs.find_first();
  1856. if (notCoveredArg >= 0) {
  1857. assert((unsigned)notCoveredArg < NumDataArgs);
  1858. if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
  1859. SourceLocation Loc = E->getLocStart();
  1860. if (!S.getSourceManager().isInSystemMacro(Loc)) {
  1861. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
  1862. Loc, /*IsStringLocation*/false,
  1863. getFormatStringRange());
  1864. }
  1865. }
  1866. }
  1867. }
  1868. }
  1869. bool
  1870. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  1871. SourceLocation Loc,
  1872. const char *startSpec,
  1873. unsigned specifierLen,
  1874. const char *csStart,
  1875. unsigned csLen) {
  1876. bool keepGoing = true;
  1877. if (argIndex < NumDataArgs) {
  1878. // Consider the argument coverered, even though the specifier doesn't
  1879. // make sense.
  1880. CoveredArgs.set(argIndex);
  1881. }
  1882. else {
  1883. // If argIndex exceeds the number of data arguments we
  1884. // don't issue a warning because that is just a cascade of warnings (and
  1885. // they may have intended '%%' anyway). We don't want to continue processing
  1886. // the format string after this point, however, as we will like just get
  1887. // gibberish when trying to match arguments.
  1888. keepGoing = false;
  1889. }
  1890. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
  1891. << StringRef(csStart, csLen),
  1892. Loc, /*IsStringLocation*/true,
  1893. getSpecifierRange(startSpec, specifierLen));
  1894. return keepGoing;
  1895. }
  1896. void
  1897. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  1898. const char *startSpec,
  1899. unsigned specifierLen) {
  1900. EmitFormatDiagnostic(
  1901. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  1902. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  1903. }
  1904. bool
  1905. CheckFormatHandler::CheckNumArgs(
  1906. const analyze_format_string::FormatSpecifier &FS,
  1907. const analyze_format_string::ConversionSpecifier &CS,
  1908. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  1909. if (argIndex >= NumDataArgs) {
  1910. PartialDiagnostic PDiag = FS.usesPositionalArg()
  1911. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  1912. << (argIndex+1) << NumDataArgs)
  1913. : S.PDiag(diag::warn_printf_insufficient_data_args);
  1914. EmitFormatDiagnostic(
  1915. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  1916. getSpecifierRange(startSpecifier, specifierLen));
  1917. return false;
  1918. }
  1919. return true;
  1920. }
  1921. template<typename Range>
  1922. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  1923. SourceLocation Loc,
  1924. bool IsStringLocation,
  1925. Range StringRange,
  1926. FixItHint FixIt) {
  1927. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  1928. Loc, IsStringLocation, StringRange, FixIt);
  1929. }
  1930. /// \brief If the format string is not within the funcion call, emit a note
  1931. /// so that the function call and string are in diagnostic messages.
  1932. ///
  1933. /// \param inFunctionCall if true, the format string is within the function
  1934. /// call and only one diagnostic message will be produced. Otherwise, an
  1935. /// extra note will be emitted pointing to location of the format string.
  1936. ///
  1937. /// \param ArgumentExpr the expression that is passed as the format string
  1938. /// argument in the function call. Used for getting locations when two
  1939. /// diagnostics are emitted.
  1940. ///
  1941. /// \param PDiag the callee should already have provided any strings for the
  1942. /// diagnostic message. This function only adds locations and fixits
  1943. /// to diagnostics.
  1944. ///
  1945. /// \param Loc primary location for diagnostic. If two diagnostics are
  1946. /// required, one will be at Loc and a new SourceLocation will be created for
  1947. /// the other one.
  1948. ///
  1949. /// \param IsStringLocation if true, Loc points to the format string should be
  1950. /// used for the note. Otherwise, Loc points to the argument list and will
  1951. /// be used with PDiag.
  1952. ///
  1953. /// \param StringRange some or all of the string to highlight. This is
  1954. /// templated so it can accept either a CharSourceRange or a SourceRange.
  1955. ///
  1956. /// \param Fixit optional fix it hint for the format string.
  1957. template<typename Range>
  1958. void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
  1959. const Expr *ArgumentExpr,
  1960. PartialDiagnostic PDiag,
  1961. SourceLocation Loc,
  1962. bool IsStringLocation,
  1963. Range StringRange,
  1964. FixItHint FixIt) {
  1965. if (InFunctionCall)
  1966. S.Diag(Loc, PDiag) << StringRange << FixIt;
  1967. else {
  1968. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  1969. << ArgumentExpr->getSourceRange();
  1970. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  1971. diag::note_format_string_defined)
  1972. << StringRange << FixIt;
  1973. }
  1974. }
  1975. //===--- CHECK: Printf format string checking ------------------------------===//
  1976. namespace {
  1977. class CheckPrintfHandler : public CheckFormatHandler {
  1978. bool ObjCContext;
  1979. public:
  1980. CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
  1981. const Expr *origFormatExpr, unsigned firstDataArg,
  1982. unsigned numDataArgs, bool isObjC,
  1983. const char *beg, bool hasVAListArg,
  1984. Expr **Args, unsigned NumArgs,
  1985. unsigned formatIdx, bool inFunctionCall,
  1986. Sema::VariadicCallType CallType)
  1987. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  1988. numDataArgs, beg, hasVAListArg, Args, NumArgs,
  1989. formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
  1990. {}
  1991. bool HandleInvalidPrintfConversionSpecifier(
  1992. const analyze_printf::PrintfSpecifier &FS,
  1993. const char *startSpecifier,
  1994. unsigned specifierLen);
  1995. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  1996. const char *startSpecifier,
  1997. unsigned specifierLen);
  1998. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  1999. const char *StartSpecifier,
  2000. unsigned SpecifierLen,
  2001. const Expr *E);
  2002. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  2003. const char *startSpecifier, unsigned specifierLen);
  2004. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  2005. const analyze_printf::OptionalAmount &Amt,
  2006. unsigned type,
  2007. const char *startSpecifier, unsigned specifierLen);
  2008. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  2009. const analyze_printf::OptionalFlag &flag,
  2010. const char *startSpecifier, unsigned specifierLen);
  2011. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  2012. const analyze_printf::OptionalFlag &ignoredFlag,
  2013. const analyze_printf::OptionalFlag &flag,
  2014. const char *startSpecifier, unsigned specifierLen);
  2015. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  2016. const Expr *E, const CharSourceRange &CSR);
  2017. };
  2018. }
  2019. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  2020. const analyze_printf::PrintfSpecifier &FS,
  2021. const char *startSpecifier,
  2022. unsigned specifierLen) {
  2023. const analyze_printf::PrintfConversionSpecifier &CS =
  2024. FS.getConversionSpecifier();
  2025. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  2026. getLocationOfByte(CS.getStart()),
  2027. startSpecifier, specifierLen,
  2028. CS.getStart(), CS.getLength());
  2029. }
  2030. bool CheckPrintfHandler::HandleAmount(
  2031. const analyze_format_string::OptionalAmount &Amt,
  2032. unsigned k, const char *startSpecifier,
  2033. unsigned specifierLen) {
  2034. if (Amt.hasDataArgument()) {
  2035. if (!HasVAListArg) {
  2036. unsigned argIndex = Amt.getArgIndex();
  2037. if (argIndex >= NumDataArgs) {
  2038. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  2039. << k,
  2040. getLocationOfByte(Amt.getStart()),
  2041. /*IsStringLocation*/true,
  2042. getSpecifierRange(startSpecifier, specifierLen));
  2043. // Don't do any more checking. We will just emit
  2044. // spurious errors.
  2045. return false;
  2046. }
  2047. // Type check the data argument. It should be an 'int'.
  2048. // Although not in conformance with C99, we also allow the argument to be
  2049. // an 'unsigned int' as that is a reasonably safe case. GCC also
  2050. // doesn't emit a warning for that case.
  2051. CoveredArgs.set(argIndex);
  2052. const Expr *Arg = getDataArg(argIndex);
  2053. if (!Arg)
  2054. return false;
  2055. QualType T = Arg->getType();
  2056. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  2057. assert(AT.isValid());
  2058. if (!AT.matchesType(S.Context, T)) {
  2059. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  2060. << k << AT.getRepresentativeTypeName(S.Context)
  2061. << T << Arg->getSourceRange(),
  2062. getLocationOfByte(Amt.getStart()),
  2063. /*IsStringLocation*/true,
  2064. getSpecifierRange(startSpecifier, specifierLen));
  2065. // Don't do any more checking. We will just emit
  2066. // spurious errors.
  2067. return false;
  2068. }
  2069. }
  2070. }
  2071. return true;
  2072. }
  2073. void CheckPrintfHandler::HandleInvalidAmount(
  2074. const analyze_printf::PrintfSpecifier &FS,
  2075. const analyze_printf::OptionalAmount &Amt,
  2076. unsigned type,
  2077. const char *startSpecifier,
  2078. unsigned specifierLen) {
  2079. const analyze_printf::PrintfConversionSpecifier &CS =
  2080. FS.getConversionSpecifier();
  2081. FixItHint fixit =
  2082. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  2083. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  2084. Amt.getConstantLength()))
  2085. : FixItHint();
  2086. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  2087. << type << CS.toString(),
  2088. getLocationOfByte(Amt.getStart()),
  2089. /*IsStringLocation*/true,
  2090. getSpecifierRange(startSpecifier, specifierLen),
  2091. fixit);
  2092. }
  2093. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  2094. const analyze_printf::OptionalFlag &flag,
  2095. const char *startSpecifier,
  2096. unsigned specifierLen) {
  2097. // Warn about pointless flag with a fixit removal.
  2098. const analyze_printf::PrintfConversionSpecifier &CS =
  2099. FS.getConversionSpecifier();
  2100. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  2101. << flag.toString() << CS.toString(),
  2102. getLocationOfByte(flag.getPosition()),
  2103. /*IsStringLocation*/true,
  2104. getSpecifierRange(startSpecifier, specifierLen),
  2105. FixItHint::CreateRemoval(
  2106. getSpecifierRange(flag.getPosition(), 1)));
  2107. }
  2108. void CheckPrintfHandler::HandleIgnoredFlag(
  2109. const analyze_printf::PrintfSpecifier &FS,
  2110. const analyze_printf::OptionalFlag &ignoredFlag,
  2111. const analyze_printf::OptionalFlag &flag,
  2112. const char *startSpecifier,
  2113. unsigned specifierLen) {
  2114. // Warn about ignored flag with a fixit removal.
  2115. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  2116. << ignoredFlag.toString() << flag.toString(),
  2117. getLocationOfByte(ignoredFlag.getPosition()),
  2118. /*IsStringLocation*/true,
  2119. getSpecifierRange(startSpecifier, specifierLen),
  2120. FixItHint::CreateRemoval(
  2121. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  2122. }
  2123. // Determines if the specified is a C++ class or struct containing
  2124. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  2125. // "c_str()").
  2126. template<typename MemberKind>
  2127. static llvm::SmallPtrSet<MemberKind*, 1>
  2128. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  2129. const RecordType *RT = Ty->getAs<RecordType>();
  2130. llvm::SmallPtrSet<MemberKind*, 1> Results;
  2131. if (!RT)
  2132. return Results;
  2133. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  2134. if (!RD)
  2135. return Results;
  2136. LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
  2137. Sema::LookupMemberName);
  2138. // We just need to include all members of the right kind turned up by the
  2139. // filter, at this point.
  2140. if (S.LookupQualifiedName(R, RT->getDecl()))
  2141. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2142. NamedDecl *decl = (*I)->getUnderlyingDecl();
  2143. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  2144. Results.insert(FK);
  2145. }
  2146. return Results;
  2147. }
  2148. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  2149. // better diagnostic if so. AT is assumed to be valid.
  2150. // Returns true when a c_str() conversion method is found.
  2151. bool CheckPrintfHandler::checkForCStrMembers(
  2152. const analyze_printf::ArgType &AT, const Expr *E,
  2153. const CharSourceRange &CSR) {
  2154. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  2155. MethodSet Results =
  2156. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  2157. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  2158. MI != ME; ++MI) {
  2159. const CXXMethodDecl *Method = *MI;
  2160. if (Method->getNumParams() == 0 &&
  2161. AT.matchesType(S.Context, Method->getResultType())) {
  2162. // FIXME: Suggest parens if the expression needs them.
  2163. SourceLocation EndLoc =
  2164. S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
  2165. S.Diag(E->getLocStart(), diag::note_printf_c_str)
  2166. << "c_str()"
  2167. << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  2168. return true;
  2169. }
  2170. }
  2171. return false;
  2172. }
  2173. bool
  2174. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  2175. &FS,
  2176. const char *startSpecifier,
  2177. unsigned specifierLen) {
  2178. using namespace analyze_format_string;
  2179. using namespace analyze_printf;
  2180. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  2181. if (FS.consumesDataArgument()) {
  2182. if (atFirstArg) {
  2183. atFirstArg = false;
  2184. usesPositionalArgs = FS.usesPositionalArg();
  2185. }
  2186. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  2187. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  2188. startSpecifier, specifierLen);
  2189. return false;
  2190. }
  2191. }
  2192. // First check if the field width, precision, and conversion specifier
  2193. // have matching data arguments.
  2194. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  2195. startSpecifier, specifierLen)) {
  2196. return false;
  2197. }
  2198. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  2199. startSpecifier, specifierLen)) {
  2200. return false;
  2201. }
  2202. if (!CS.consumesDataArgument()) {
  2203. // FIXME: Technically specifying a precision or field width here
  2204. // makes no sense. Worth issuing a warning at some point.
  2205. return true;
  2206. }
  2207. // Consume the argument.
  2208. unsigned argIndex = FS.getArgIndex();
  2209. if (argIndex < NumDataArgs) {
  2210. // The check to see if the argIndex is valid will come later.
  2211. // We set the bit here because we may exit early from this
  2212. // function if we encounter some other error.
  2213. CoveredArgs.set(argIndex);
  2214. }
  2215. // Check for using an Objective-C specific conversion specifier
  2216. // in a non-ObjC literal.
  2217. if (!ObjCContext && CS.isObjCArg()) {
  2218. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  2219. specifierLen);
  2220. }
  2221. // Check for invalid use of field width
  2222. if (!FS.hasValidFieldWidth()) {
  2223. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  2224. startSpecifier, specifierLen);
  2225. }
  2226. // Check for invalid use of precision
  2227. if (!FS.hasValidPrecision()) {
  2228. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  2229. startSpecifier, specifierLen);
  2230. }
  2231. // Check each flag does not conflict with any other component.
  2232. if (!FS.hasValidThousandsGroupingPrefix())
  2233. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  2234. if (!FS.hasValidLeadingZeros())
  2235. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  2236. if (!FS.hasValidPlusPrefix())
  2237. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  2238. if (!FS.hasValidSpacePrefix())
  2239. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  2240. if (!FS.hasValidAlternativeForm())
  2241. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  2242. if (!FS.hasValidLeftJustified())
  2243. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  2244. // Check that flags are not ignored by another flag
  2245. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  2246. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  2247. startSpecifier, specifierLen);
  2248. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  2249. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  2250. startSpecifier, specifierLen);
  2251. // Check the length modifier is valid with the given conversion specifier.
  2252. const LengthModifier &LM = FS.getLengthModifier();
  2253. if (!FS.hasValidLengthModifier())
  2254. EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
  2255. << LM.toString() << CS.toString(),
  2256. getLocationOfByte(LM.getStart()),
  2257. /*IsStringLocation*/true,
  2258. getSpecifierRange(startSpecifier, specifierLen),
  2259. FixItHint::CreateRemoval(
  2260. getSpecifierRange(LM.getStart(),
  2261. LM.getLength())));
  2262. if (!FS.hasStandardLengthModifier())
  2263. HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
  2264. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  2265. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  2266. if (!FS.hasStandardLengthConversionCombination())
  2267. HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
  2268. specifierLen);
  2269. // The remaining checks depend on the data arguments.
  2270. if (HasVAListArg)
  2271. return true;
  2272. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  2273. return false;
  2274. const Expr *Arg = getDataArg(argIndex);
  2275. if (!Arg)
  2276. return true;
  2277. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  2278. }
  2279. bool
  2280. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  2281. const char *StartSpecifier,
  2282. unsigned SpecifierLen,
  2283. const Expr *E) {
  2284. using namespace analyze_format_string;
  2285. using namespace analyze_printf;
  2286. // Now type check the data expression that matches the
  2287. // format specifier.
  2288. const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
  2289. ObjCContext);
  2290. if (AT.isValid() && !AT.matchesType(S.Context, E->getType())) {
  2291. // Look through argument promotions for our error message's reported type.
  2292. // This includes the integral and floating promotions, but excludes array
  2293. // and function pointer decay; seeing that an argument intended to be a
  2294. // string has type 'char [6]' is probably more confusing than 'char *'.
  2295. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  2296. if (ICE->getCastKind() == CK_IntegralCast ||
  2297. ICE->getCastKind() == CK_FloatingCast) {
  2298. E = ICE->getSubExpr();
  2299. // Check if we didn't match because of an implicit cast from a 'char'
  2300. // or 'short' to an 'int'. This is done because printf is a varargs
  2301. // function.
  2302. if (ICE->getType() == S.Context.IntTy ||
  2303. ICE->getType() == S.Context.UnsignedIntTy) {
  2304. // All further checking is done on the subexpression.
  2305. if (AT.matchesType(S.Context, E->getType()))
  2306. return true;
  2307. }
  2308. }
  2309. }
  2310. // We may be able to offer a FixItHint if it is a supported type.
  2311. PrintfSpecifier fixedFS = FS;
  2312. bool success = fixedFS.fixType(E->getType(), S.getLangOpts(),
  2313. S.Context, ObjCContext);
  2314. if (success) {
  2315. // Get the fix string from the fixed format specifier
  2316. SmallString<16> buf;
  2317. llvm::raw_svector_ostream os(buf);
  2318. fixedFS.toString(os);
  2319. EmitFormatDiagnostic(
  2320. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2321. << AT.getRepresentativeTypeName(S.Context) << E->getType()
  2322. << E->getSourceRange(),
  2323. E->getLocStart(),
  2324. /*IsStringLocation*/false,
  2325. getSpecifierRange(StartSpecifier, SpecifierLen),
  2326. FixItHint::CreateReplacement(
  2327. getSpecifierRange(StartSpecifier, SpecifierLen),
  2328. os.str()));
  2329. } else {
  2330. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  2331. SpecifierLen);
  2332. // Since the warning for passing non-POD types to variadic functions
  2333. // was deferred until now, we emit a warning for non-POD
  2334. // arguments here.
  2335. if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
  2336. unsigned DiagKind;
  2337. if (E->getType()->isObjCObjectType())
  2338. DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
  2339. else
  2340. DiagKind = diag::warn_non_pod_vararg_with_format_string;
  2341. EmitFormatDiagnostic(
  2342. S.PDiag(DiagKind)
  2343. << S.getLangOpts().CPlusPlus0x
  2344. << E->getType()
  2345. << CallType
  2346. << AT.getRepresentativeTypeName(S.Context)
  2347. << CSR
  2348. << E->getSourceRange(),
  2349. E->getLocStart(), /*IsStringLocation*/false, CSR);
  2350. checkForCStrMembers(AT, E, CSR);
  2351. } else
  2352. EmitFormatDiagnostic(
  2353. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2354. << AT.getRepresentativeTypeName(S.Context) << E->getType()
  2355. << CSR
  2356. << E->getSourceRange(),
  2357. E->getLocStart(), /*IsStringLocation*/false, CSR);
  2358. }
  2359. }
  2360. return true;
  2361. }
  2362. //===--- CHECK: Scanf format string checking ------------------------------===//
  2363. namespace {
  2364. class CheckScanfHandler : public CheckFormatHandler {
  2365. public:
  2366. CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
  2367. const Expr *origFormatExpr, unsigned firstDataArg,
  2368. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  2369. Expr **Args, unsigned NumArgs,
  2370. unsigned formatIdx, bool inFunctionCall,
  2371. Sema::VariadicCallType CallType)
  2372. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  2373. numDataArgs, beg, hasVAListArg,
  2374. Args, NumArgs, formatIdx, inFunctionCall, CallType)
  2375. {}
  2376. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  2377. const char *startSpecifier,
  2378. unsigned specifierLen);
  2379. bool HandleInvalidScanfConversionSpecifier(
  2380. const analyze_scanf::ScanfSpecifier &FS,
  2381. const char *startSpecifier,
  2382. unsigned specifierLen);
  2383. void HandleIncompleteScanList(const char *start, const char *end);
  2384. };
  2385. }
  2386. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  2387. const char *end) {
  2388. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  2389. getLocationOfByte(end), /*IsStringLocation*/true,
  2390. getSpecifierRange(start, end - start));
  2391. }
  2392. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  2393. const analyze_scanf::ScanfSpecifier &FS,
  2394. const char *startSpecifier,
  2395. unsigned specifierLen) {
  2396. const analyze_scanf::ScanfConversionSpecifier &CS =
  2397. FS.getConversionSpecifier();
  2398. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  2399. getLocationOfByte(CS.getStart()),
  2400. startSpecifier, specifierLen,
  2401. CS.getStart(), CS.getLength());
  2402. }
  2403. bool CheckScanfHandler::HandleScanfSpecifier(
  2404. const analyze_scanf::ScanfSpecifier &FS,
  2405. const char *startSpecifier,
  2406. unsigned specifierLen) {
  2407. using namespace analyze_scanf;
  2408. using namespace analyze_format_string;
  2409. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  2410. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  2411. // be used to decide if we are using positional arguments consistently.
  2412. if (FS.consumesDataArgument()) {
  2413. if (atFirstArg) {
  2414. atFirstArg = false;
  2415. usesPositionalArgs = FS.usesPositionalArg();
  2416. }
  2417. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  2418. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  2419. startSpecifier, specifierLen);
  2420. return false;
  2421. }
  2422. }
  2423. // Check if the field with is non-zero.
  2424. const OptionalAmount &Amt = FS.getFieldWidth();
  2425. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  2426. if (Amt.getConstantAmount() == 0) {
  2427. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  2428. Amt.getConstantLength());
  2429. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  2430. getLocationOfByte(Amt.getStart()),
  2431. /*IsStringLocation*/true, R,
  2432. FixItHint::CreateRemoval(R));
  2433. }
  2434. }
  2435. if (!FS.consumesDataArgument()) {
  2436. // FIXME: Technically specifying a precision or field width here
  2437. // makes no sense. Worth issuing a warning at some point.
  2438. return true;
  2439. }
  2440. // Consume the argument.
  2441. unsigned argIndex = FS.getArgIndex();
  2442. if (argIndex < NumDataArgs) {
  2443. // The check to see if the argIndex is valid will come later.
  2444. // We set the bit here because we may exit early from this
  2445. // function if we encounter some other error.
  2446. CoveredArgs.set(argIndex);
  2447. }
  2448. // Check the length modifier is valid with the given conversion specifier.
  2449. const LengthModifier &LM = FS.getLengthModifier();
  2450. if (!FS.hasValidLengthModifier()) {
  2451. const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
  2452. EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
  2453. << LM.toString() << CS.toString()
  2454. << getSpecifierRange(startSpecifier, specifierLen),
  2455. getLocationOfByte(LM.getStart()),
  2456. /*IsStringLocation*/true, R,
  2457. FixItHint::CreateRemoval(R));
  2458. }
  2459. if (!FS.hasStandardLengthModifier())
  2460. HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
  2461. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  2462. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  2463. if (!FS.hasStandardLengthConversionCombination())
  2464. HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
  2465. specifierLen);
  2466. // The remaining checks depend on the data arguments.
  2467. if (HasVAListArg)
  2468. return true;
  2469. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  2470. return false;
  2471. // Check that the argument type matches the format specifier.
  2472. const Expr *Ex = getDataArg(argIndex);
  2473. if (!Ex)
  2474. return true;
  2475. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  2476. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
  2477. ScanfSpecifier fixedFS = FS;
  2478. bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
  2479. S.Context);
  2480. if (success) {
  2481. // Get the fix string from the fixed format specifier.
  2482. SmallString<128> buf;
  2483. llvm::raw_svector_ostream os(buf);
  2484. fixedFS.toString(os);
  2485. EmitFormatDiagnostic(
  2486. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2487. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  2488. << Ex->getSourceRange(),
  2489. Ex->getLocStart(),
  2490. /*IsStringLocation*/false,
  2491. getSpecifierRange(startSpecifier, specifierLen),
  2492. FixItHint::CreateReplacement(
  2493. getSpecifierRange(startSpecifier, specifierLen),
  2494. os.str()));
  2495. } else {
  2496. EmitFormatDiagnostic(
  2497. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2498. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  2499. << Ex->getSourceRange(),
  2500. Ex->getLocStart(),
  2501. /*IsStringLocation*/false,
  2502. getSpecifierRange(startSpecifier, specifierLen));
  2503. }
  2504. }
  2505. return true;
  2506. }
  2507. void Sema::CheckFormatString(const StringLiteral *FExpr,
  2508. const Expr *OrigFormatExpr,
  2509. Expr **Args, unsigned NumArgs,
  2510. bool HasVAListArg, unsigned format_idx,
  2511. unsigned firstDataArg, FormatStringType Type,
  2512. bool inFunctionCall, VariadicCallType CallType) {
  2513. // CHECK: is the format string a wide literal?
  2514. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  2515. CheckFormatHandler::EmitFormatDiagnostic(
  2516. *this, inFunctionCall, Args[format_idx],
  2517. PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  2518. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  2519. return;
  2520. }
  2521. // Str - The format string. NOTE: this is NOT null-terminated!
  2522. StringRef StrRef = FExpr->getString();
  2523. const char *Str = StrRef.data();
  2524. unsigned StrLen = StrRef.size();
  2525. const unsigned numDataArgs = NumArgs - firstDataArg;
  2526. // CHECK: empty format string?
  2527. if (StrLen == 0 && numDataArgs > 0) {
  2528. CheckFormatHandler::EmitFormatDiagnostic(
  2529. *this, inFunctionCall, Args[format_idx],
  2530. PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  2531. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  2532. return;
  2533. }
  2534. if (Type == FST_Printf || Type == FST_NSString) {
  2535. CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
  2536. numDataArgs, (Type == FST_NSString),
  2537. Str, HasVAListArg, Args, NumArgs, format_idx,
  2538. inFunctionCall, CallType);
  2539. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  2540. getLangOpts()))
  2541. H.DoneProcessing();
  2542. } else if (Type == FST_Scanf) {
  2543. CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
  2544. Str, HasVAListArg, Args, NumArgs, format_idx,
  2545. inFunctionCall, CallType);
  2546. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  2547. getLangOpts()))
  2548. H.DoneProcessing();
  2549. } // TODO: handle other formats
  2550. }
  2551. //===--- CHECK: Standard memory functions ---------------------------------===//
  2552. /// \brief Determine whether the given type is a dynamic class type (e.g.,
  2553. /// whether it has a vtable).
  2554. static bool isDynamicClassType(QualType T) {
  2555. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
  2556. if (CXXRecordDecl *Definition = Record->getDefinition())
  2557. if (Definition->isDynamicClass())
  2558. return true;
  2559. return false;
  2560. }
  2561. /// \brief If E is a sizeof expression, returns its argument expression,
  2562. /// otherwise returns NULL.
  2563. static const Expr *getSizeOfExprArg(const Expr* E) {
  2564. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  2565. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  2566. if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
  2567. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  2568. return 0;
  2569. }
  2570. /// \brief If E is a sizeof expression, returns its argument type.
  2571. static QualType getSizeOfArgType(const Expr* E) {
  2572. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  2573. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  2574. if (SizeOf->getKind() == clang::UETT_SizeOf)
  2575. return SizeOf->getTypeOfArgument();
  2576. return QualType();
  2577. }
  2578. /// \brief Check for dangerous or invalid arguments to memset().
  2579. ///
  2580. /// This issues warnings on known problematic, dangerous or unspecified
  2581. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  2582. /// function calls.
  2583. ///
  2584. /// \param Call The call expression to diagnose.
  2585. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  2586. unsigned BId,
  2587. IdentifierInfo *FnName) {
  2588. assert(BId != 0);
  2589. // It is possible to have a non-standard definition of memset. Validate
  2590. // we have enough arguments, and if not, abort further checking.
  2591. unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
  2592. if (Call->getNumArgs() < ExpectedNumArgs)
  2593. return;
  2594. unsigned LastArg = (BId == Builtin::BImemset ||
  2595. BId == Builtin::BIstrndup ? 1 : 2);
  2596. unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
  2597. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  2598. // We have special checking when the length is a sizeof expression.
  2599. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  2600. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  2601. llvm::FoldingSetNodeID SizeOfArgID;
  2602. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  2603. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  2604. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  2605. QualType DestTy = Dest->getType();
  2606. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  2607. QualType PointeeTy = DestPtrTy->getPointeeType();
  2608. // Never warn about void type pointers. This can be used to suppress
  2609. // false positives.
  2610. if (PointeeTy->isVoidType())
  2611. continue;
  2612. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  2613. // actually comparing the expressions for equality. Because computing the
  2614. // expression IDs can be expensive, we only do this if the diagnostic is
  2615. // enabled.
  2616. if (SizeOfArg &&
  2617. Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
  2618. SizeOfArg->getExprLoc())) {
  2619. // We only compute IDs for expressions if the warning is enabled, and
  2620. // cache the sizeof arg's ID.
  2621. if (SizeOfArgID == llvm::FoldingSetNodeID())
  2622. SizeOfArg->Profile(SizeOfArgID, Context, true);
  2623. llvm::FoldingSetNodeID DestID;
  2624. Dest->Profile(DestID, Context, true);
  2625. if (DestID == SizeOfArgID) {
  2626. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  2627. // over sizeof(src) as well.
  2628. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  2629. StringRef ReadableName = FnName->getName();
  2630. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  2631. if (UnaryOp->getOpcode() == UO_AddrOf)
  2632. ActionIdx = 1; // If its an address-of operator, just remove it.
  2633. if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
  2634. ActionIdx = 2; // If the pointee's size is sizeof(char),
  2635. // suggest an explicit length.
  2636. // If the function is defined as a builtin macro, do not show macro
  2637. // expansion.
  2638. SourceLocation SL = SizeOfArg->getExprLoc();
  2639. SourceRange DSR = Dest->getSourceRange();
  2640. SourceRange SSR = SizeOfArg->getSourceRange();
  2641. SourceManager &SM = PP.getSourceManager();
  2642. if (SM.isMacroArgExpansion(SL)) {
  2643. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  2644. SL = SM.getSpellingLoc(SL);
  2645. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  2646. SM.getSpellingLoc(DSR.getEnd()));
  2647. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  2648. SM.getSpellingLoc(SSR.getEnd()));
  2649. }
  2650. DiagRuntimeBehavior(SL, SizeOfArg,
  2651. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  2652. << ReadableName
  2653. << PointeeTy
  2654. << DestTy
  2655. << DSR
  2656. << SSR);
  2657. DiagRuntimeBehavior(SL, SizeOfArg,
  2658. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  2659. << ActionIdx
  2660. << SSR);
  2661. break;
  2662. }
  2663. }
  2664. // Also check for cases where the sizeof argument is the exact same
  2665. // type as the memory argument, and where it points to a user-defined
  2666. // record type.
  2667. if (SizeOfArgTy != QualType()) {
  2668. if (PointeeTy->isRecordType() &&
  2669. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  2670. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  2671. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  2672. << FnName << SizeOfArgTy << ArgIdx
  2673. << PointeeTy << Dest->getSourceRange()
  2674. << LenExpr->getSourceRange());
  2675. break;
  2676. }
  2677. }
  2678. // Always complain about dynamic classes.
  2679. if (isDynamicClassType(PointeeTy)) {
  2680. unsigned OperationType = 0;
  2681. // "overwritten" if we're warning about the destination for any call
  2682. // but memcmp; otherwise a verb appropriate to the call.
  2683. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  2684. if (BId == Builtin::BImemcpy)
  2685. OperationType = 1;
  2686. else if(BId == Builtin::BImemmove)
  2687. OperationType = 2;
  2688. else if (BId == Builtin::BImemcmp)
  2689. OperationType = 3;
  2690. }
  2691. DiagRuntimeBehavior(
  2692. Dest->getExprLoc(), Dest,
  2693. PDiag(diag::warn_dyn_class_memaccess)
  2694. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  2695. << FnName << PointeeTy
  2696. << OperationType
  2697. << Call->getCallee()->getSourceRange());
  2698. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  2699. BId != Builtin::BImemset)
  2700. DiagRuntimeBehavior(
  2701. Dest->getExprLoc(), Dest,
  2702. PDiag(diag::warn_arc_object_memaccess)
  2703. << ArgIdx << FnName << PointeeTy
  2704. << Call->getCallee()->getSourceRange());
  2705. else
  2706. continue;
  2707. DiagRuntimeBehavior(
  2708. Dest->getExprLoc(), Dest,
  2709. PDiag(diag::note_bad_memaccess_silence)
  2710. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  2711. break;
  2712. }
  2713. }
  2714. }
  2715. // A little helper routine: ignore addition and subtraction of integer literals.
  2716. // This intentionally does not ignore all integer constant expressions because
  2717. // we don't want to remove sizeof().
  2718. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  2719. Ex = Ex->IgnoreParenCasts();
  2720. for (;;) {
  2721. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  2722. if (!BO || !BO->isAdditiveOp())
  2723. break;
  2724. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  2725. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  2726. if (isa<IntegerLiteral>(RHS))
  2727. Ex = LHS;
  2728. else if (isa<IntegerLiteral>(LHS))
  2729. Ex = RHS;
  2730. else
  2731. break;
  2732. }
  2733. return Ex;
  2734. }
  2735. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  2736. // be the size of the source, instead of the destination.
  2737. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  2738. IdentifierInfo *FnName) {
  2739. // Don't crash if the user has the wrong number of arguments
  2740. if (Call->getNumArgs() != 3)
  2741. return;
  2742. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  2743. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  2744. const Expr *CompareWithSrc = NULL;
  2745. // Look for 'strlcpy(dst, x, sizeof(x))'
  2746. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  2747. CompareWithSrc = Ex;
  2748. else {
  2749. // Look for 'strlcpy(dst, x, strlen(x))'
  2750. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  2751. if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
  2752. && SizeCall->getNumArgs() == 1)
  2753. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  2754. }
  2755. }
  2756. if (!CompareWithSrc)
  2757. return;
  2758. // Determine if the argument to sizeof/strlen is equal to the source
  2759. // argument. In principle there's all kinds of things you could do
  2760. // here, for instance creating an == expression and evaluating it with
  2761. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  2762. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  2763. if (!SrcArgDRE)
  2764. return;
  2765. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  2766. if (!CompareWithSrcDRE ||
  2767. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  2768. return;
  2769. const Expr *OriginalSizeArg = Call->getArg(2);
  2770. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  2771. << OriginalSizeArg->getSourceRange() << FnName;
  2772. // Output a FIXIT hint if the destination is an array (rather than a
  2773. // pointer to an array). This could be enhanced to handle some
  2774. // pointers if we know the actual size, like if DstArg is 'array+2'
  2775. // we could say 'sizeof(array)-2'.
  2776. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  2777. QualType DstArgTy = DstArg->getType();
  2778. // Only handle constant-sized or VLAs, but not flexible members.
  2779. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
  2780. // Only issue the FIXIT for arrays of size > 1.
  2781. if (CAT->getSize().getSExtValue() <= 1)
  2782. return;
  2783. } else if (!DstArgTy->isVariableArrayType()) {
  2784. return;
  2785. }
  2786. SmallString<128> sizeString;
  2787. llvm::raw_svector_ostream OS(sizeString);
  2788. OS << "sizeof(";
  2789. DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
  2790. OS << ")";
  2791. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  2792. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  2793. OS.str());
  2794. }
  2795. /// Check if two expressions refer to the same declaration.
  2796. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  2797. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  2798. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  2799. return D1->getDecl() == D2->getDecl();
  2800. return false;
  2801. }
  2802. static const Expr *getStrlenExprArg(const Expr *E) {
  2803. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  2804. const FunctionDecl *FD = CE->getDirectCallee();
  2805. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  2806. return 0;
  2807. return CE->getArg(0)->IgnoreParenCasts();
  2808. }
  2809. return 0;
  2810. }
  2811. // Warn on anti-patterns as the 'size' argument to strncat.
  2812. // The correct size argument should look like following:
  2813. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  2814. void Sema::CheckStrncatArguments(const CallExpr *CE,
  2815. IdentifierInfo *FnName) {
  2816. // Don't crash if the user has the wrong number of arguments.
  2817. if (CE->getNumArgs() < 3)
  2818. return;
  2819. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  2820. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  2821. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  2822. // Identify common expressions, which are wrongly used as the size argument
  2823. // to strncat and may lead to buffer overflows.
  2824. unsigned PatternType = 0;
  2825. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  2826. // - sizeof(dst)
  2827. if (referToTheSameDecl(SizeOfArg, DstArg))
  2828. PatternType = 1;
  2829. // - sizeof(src)
  2830. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  2831. PatternType = 2;
  2832. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  2833. if (BE->getOpcode() == BO_Sub) {
  2834. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  2835. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  2836. // - sizeof(dst) - strlen(dst)
  2837. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  2838. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  2839. PatternType = 1;
  2840. // - sizeof(src) - (anything)
  2841. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  2842. PatternType = 2;
  2843. }
  2844. }
  2845. if (PatternType == 0)
  2846. return;
  2847. // Generate the diagnostic.
  2848. SourceLocation SL = LenArg->getLocStart();
  2849. SourceRange SR = LenArg->getSourceRange();
  2850. SourceManager &SM = PP.getSourceManager();
  2851. // If the function is defined as a builtin macro, do not show macro expansion.
  2852. if (SM.isMacroArgExpansion(SL)) {
  2853. SL = SM.getSpellingLoc(SL);
  2854. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  2855. SM.getSpellingLoc(SR.getEnd()));
  2856. }
  2857. if (PatternType == 1)
  2858. Diag(SL, diag::warn_strncat_large_size) << SR;
  2859. else
  2860. Diag(SL, diag::warn_strncat_src_size) << SR;
  2861. // Output a FIXIT hint if the destination is an array (rather than a
  2862. // pointer to an array). This could be enhanced to handle some
  2863. // pointers if we know the actual size, like if DstArg is 'array+2'
  2864. // we could say 'sizeof(array)-2'.
  2865. QualType DstArgTy = DstArg->getType();
  2866. // Only handle constant-sized or VLAs, but not flexible members.
  2867. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
  2868. // Only issue the FIXIT for arrays of size > 1.
  2869. if (CAT->getSize().getSExtValue() <= 1)
  2870. return;
  2871. } else if (!DstArgTy->isVariableArrayType()) {
  2872. return;
  2873. }
  2874. SmallString<128> sizeString;
  2875. llvm::raw_svector_ostream OS(sizeString);
  2876. OS << "sizeof(";
  2877. DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
  2878. OS << ") - ";
  2879. OS << "strlen(";
  2880. DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
  2881. OS << ") - 1";
  2882. Diag(SL, diag::note_strncat_wrong_size)
  2883. << FixItHint::CreateReplacement(SR, OS.str());
  2884. }
  2885. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  2886. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  2887. Decl *ParentDecl);
  2888. static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
  2889. Decl *ParentDecl);
  2890. /// CheckReturnStackAddr - Check if a return statement returns the address
  2891. /// of a stack variable.
  2892. void
  2893. Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
  2894. SourceLocation ReturnLoc) {
  2895. Expr *stackE = 0;
  2896. SmallVector<DeclRefExpr *, 8> refVars;
  2897. // Perform checking for returned stack addresses, local blocks,
  2898. // label addresses or references to temporaries.
  2899. if (lhsType->isPointerType() ||
  2900. (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  2901. stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
  2902. } else if (lhsType->isReferenceType()) {
  2903. stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
  2904. }
  2905. if (stackE == 0)
  2906. return; // Nothing suspicious was found.
  2907. SourceLocation diagLoc;
  2908. SourceRange diagRange;
  2909. if (refVars.empty()) {
  2910. diagLoc = stackE->getLocStart();
  2911. diagRange = stackE->getSourceRange();
  2912. } else {
  2913. // We followed through a reference variable. 'stackE' contains the
  2914. // problematic expression but we will warn at the return statement pointing
  2915. // at the reference variable. We will later display the "trail" of
  2916. // reference variables using notes.
  2917. diagLoc = refVars[0]->getLocStart();
  2918. diagRange = refVars[0]->getSourceRange();
  2919. }
  2920. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
  2921. Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
  2922. : diag::warn_ret_stack_addr)
  2923. << DR->getDecl()->getDeclName() << diagRange;
  2924. } else if (isa<BlockExpr>(stackE)) { // local block.
  2925. Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  2926. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  2927. Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  2928. } else { // local temporary.
  2929. Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
  2930. : diag::warn_ret_local_temp_addr)
  2931. << diagRange;
  2932. }
  2933. // Display the "trail" of reference variables that we followed until we
  2934. // found the problematic expression using notes.
  2935. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  2936. VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  2937. // If this var binds to another reference var, show the range of the next
  2938. // var, otherwise the var binds to the problematic expression, in which case
  2939. // show the range of the expression.
  2940. SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
  2941. : stackE->getSourceRange();
  2942. Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  2943. << VD->getDeclName() << range;
  2944. }
  2945. }
  2946. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  2947. /// check if the expression in a return statement evaluates to an address
  2948. /// to a location on the stack, a local block, an address of a label, or a
  2949. /// reference to local temporary. The recursion is used to traverse the
  2950. /// AST of the return expression, with recursion backtracking when we
  2951. /// encounter a subexpression that (1) clearly does not lead to one of the
  2952. /// above problematic expressions (2) is something we cannot determine leads to
  2953. /// a problematic expression based on such local checking.
  2954. ///
  2955. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  2956. /// the expression that they point to. Such variables are added to the
  2957. /// 'refVars' vector so that we know what the reference variable "trail" was.
  2958. ///
  2959. /// EvalAddr processes expressions that are pointers that are used as
  2960. /// references (and not L-values). EvalVal handles all other values.
  2961. /// At the base case of the recursion is a check for the above problematic
  2962. /// expressions.
  2963. ///
  2964. /// This implementation handles:
  2965. ///
  2966. /// * pointer-to-pointer casts
  2967. /// * implicit conversions from array references to pointers
  2968. /// * taking the address of fields
  2969. /// * arbitrary interplay between "&" and "*" operators
  2970. /// * pointer arithmetic from an address of a stack variable
  2971. /// * taking the address of an array element where the array is on the stack
  2972. static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  2973. Decl *ParentDecl) {
  2974. if (E->isTypeDependent())
  2975. return NULL;
  2976. // We should only be called for evaluating pointer expressions.
  2977. assert((E->getType()->isAnyPointerType() ||
  2978. E->getType()->isBlockPointerType() ||
  2979. E->getType()->isObjCQualifiedIdType()) &&
  2980. "EvalAddr only works on pointers");
  2981. E = E->IgnoreParens();
  2982. // Our "symbolic interpreter" is just a dispatch off the currently
  2983. // viewed AST node. We then recursively traverse the AST by calling
  2984. // EvalAddr and EvalVal appropriately.
  2985. switch (E->getStmtClass()) {
  2986. case Stmt::DeclRefExprClass: {
  2987. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  2988. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  2989. // If this is a reference variable, follow through to the expression that
  2990. // it points to.
  2991. if (V->hasLocalStorage() &&
  2992. V->getType()->isReferenceType() && V->hasInit()) {
  2993. // Add the reference variable to the "trail".
  2994. refVars.push_back(DR);
  2995. return EvalAddr(V->getInit(), refVars, ParentDecl);
  2996. }
  2997. return NULL;
  2998. }
  2999. case Stmt::UnaryOperatorClass: {
  3000. // The only unary operator that make sense to handle here
  3001. // is AddrOf. All others don't make sense as pointers.
  3002. UnaryOperator *U = cast<UnaryOperator>(E);
  3003. if (U->getOpcode() == UO_AddrOf)
  3004. return EvalVal(U->getSubExpr(), refVars, ParentDecl);
  3005. else
  3006. return NULL;
  3007. }
  3008. case Stmt::BinaryOperatorClass: {
  3009. // Handle pointer arithmetic. All other binary operators are not valid
  3010. // in this context.
  3011. BinaryOperator *B = cast<BinaryOperator>(E);
  3012. BinaryOperatorKind op = B->getOpcode();
  3013. if (op != BO_Add && op != BO_Sub)
  3014. return NULL;
  3015. Expr *Base = B->getLHS();
  3016. // Determine which argument is the real pointer base. It could be
  3017. // the RHS argument instead of the LHS.
  3018. if (!Base->getType()->isPointerType()) Base = B->getRHS();
  3019. assert (Base->getType()->isPointerType());
  3020. return EvalAddr(Base, refVars, ParentDecl);
  3021. }
  3022. // For conditional operators we need to see if either the LHS or RHS are
  3023. // valid DeclRefExpr*s. If one of them is valid, we return it.
  3024. case Stmt::ConditionalOperatorClass: {
  3025. ConditionalOperator *C = cast<ConditionalOperator>(E);
  3026. // Handle the GNU extension for missing LHS.
  3027. if (Expr *lhsExpr = C->getLHS()) {
  3028. // In C++, we can have a throw-expression, which has 'void' type.
  3029. if (!lhsExpr->getType()->isVoidType())
  3030. if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
  3031. return LHS;
  3032. }
  3033. // In C++, we can have a throw-expression, which has 'void' type.
  3034. if (C->getRHS()->getType()->isVoidType())
  3035. return NULL;
  3036. return EvalAddr(C->getRHS(), refVars, ParentDecl);
  3037. }
  3038. case Stmt::BlockExprClass:
  3039. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  3040. return E; // local block.
  3041. return NULL;
  3042. case Stmt::AddrLabelExprClass:
  3043. return E; // address of label.
  3044. case Stmt::ExprWithCleanupsClass:
  3045. return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  3046. ParentDecl);
  3047. // For casts, we need to handle conversions from arrays to
  3048. // pointer values, and pointer-to-pointer conversions.
  3049. case Stmt::ImplicitCastExprClass:
  3050. case Stmt::CStyleCastExprClass:
  3051. case Stmt::CXXFunctionalCastExprClass:
  3052. case Stmt::ObjCBridgedCastExprClass:
  3053. case Stmt::CXXStaticCastExprClass:
  3054. case Stmt::CXXDynamicCastExprClass:
  3055. case Stmt::CXXConstCastExprClass:
  3056. case Stmt::CXXReinterpretCastExprClass: {
  3057. Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  3058. switch (cast<CastExpr>(E)->getCastKind()) {
  3059. case CK_BitCast:
  3060. case CK_LValueToRValue:
  3061. case CK_NoOp:
  3062. case CK_BaseToDerived:
  3063. case CK_DerivedToBase:
  3064. case CK_UncheckedDerivedToBase:
  3065. case CK_Dynamic:
  3066. case CK_CPointerToObjCPointerCast:
  3067. case CK_BlockPointerToObjCPointerCast:
  3068. case CK_AnyPointerToBlockPointerCast:
  3069. return EvalAddr(SubExpr, refVars, ParentDecl);
  3070. case CK_ArrayToPointerDecay:
  3071. return EvalVal(SubExpr, refVars, ParentDecl);
  3072. default:
  3073. return 0;
  3074. }
  3075. }
  3076. case Stmt::MaterializeTemporaryExprClass:
  3077. if (Expr *Result = EvalAddr(
  3078. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  3079. refVars, ParentDecl))
  3080. return Result;
  3081. return E;
  3082. // Everything else: we simply don't reason about them.
  3083. default:
  3084. return NULL;
  3085. }
  3086. }
  3087. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  3088. /// See the comments for EvalAddr for more details.
  3089. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  3090. Decl *ParentDecl) {
  3091. do {
  3092. // We should only be called for evaluating non-pointer expressions, or
  3093. // expressions with a pointer type that are not used as references but instead
  3094. // are l-values (e.g., DeclRefExpr with a pointer type).
  3095. // Our "symbolic interpreter" is just a dispatch off the currently
  3096. // viewed AST node. We then recursively traverse the AST by calling
  3097. // EvalAddr and EvalVal appropriately.
  3098. E = E->IgnoreParens();
  3099. switch (E->getStmtClass()) {
  3100. case Stmt::ImplicitCastExprClass: {
  3101. ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  3102. if (IE->getValueKind() == VK_LValue) {
  3103. E = IE->getSubExpr();
  3104. continue;
  3105. }
  3106. return NULL;
  3107. }
  3108. case Stmt::ExprWithCleanupsClass:
  3109. return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
  3110. case Stmt::DeclRefExprClass: {
  3111. // When we hit a DeclRefExpr we are looking at code that refers to a
  3112. // variable's name. If it's not a reference variable we check if it has
  3113. // local storage within the function, and if so, return the expression.
  3114. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  3115. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
  3116. // Check if it refers to itself, e.g. "int& i = i;".
  3117. if (V == ParentDecl)
  3118. return DR;
  3119. if (V->hasLocalStorage()) {
  3120. if (!V->getType()->isReferenceType())
  3121. return DR;
  3122. // Reference variable, follow through to the expression that
  3123. // it points to.
  3124. if (V->hasInit()) {
  3125. // Add the reference variable to the "trail".
  3126. refVars.push_back(DR);
  3127. return EvalVal(V->getInit(), refVars, V);
  3128. }
  3129. }
  3130. }
  3131. return NULL;
  3132. }
  3133. case Stmt::UnaryOperatorClass: {
  3134. // The only unary operator that make sense to handle here
  3135. // is Deref. All others don't resolve to a "name." This includes
  3136. // handling all sorts of rvalues passed to a unary operator.
  3137. UnaryOperator *U = cast<UnaryOperator>(E);
  3138. if (U->getOpcode() == UO_Deref)
  3139. return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
  3140. return NULL;
  3141. }
  3142. case Stmt::ArraySubscriptExprClass: {
  3143. // Array subscripts are potential references to data on the stack. We
  3144. // retrieve the DeclRefExpr* for the array variable if it indeed
  3145. // has local storage.
  3146. return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
  3147. }
  3148. case Stmt::ConditionalOperatorClass: {
  3149. // For conditional operators we need to see if either the LHS or RHS are
  3150. // non-NULL Expr's. If one is non-NULL, we return it.
  3151. ConditionalOperator *C = cast<ConditionalOperator>(E);
  3152. // Handle the GNU extension for missing LHS.
  3153. if (Expr *lhsExpr = C->getLHS())
  3154. if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
  3155. return LHS;
  3156. return EvalVal(C->getRHS(), refVars, ParentDecl);
  3157. }
  3158. // Accesses to members are potential references to data on the stack.
  3159. case Stmt::MemberExprClass: {
  3160. MemberExpr *M = cast<MemberExpr>(E);
  3161. // Check for indirect access. We only want direct field accesses.
  3162. if (M->isArrow())
  3163. return NULL;
  3164. // Check whether the member type is itself a reference, in which case
  3165. // we're not going to refer to the member, but to what the member refers to.
  3166. if (M->getMemberDecl()->getType()->isReferenceType())
  3167. return NULL;
  3168. return EvalVal(M->getBase(), refVars, ParentDecl);
  3169. }
  3170. case Stmt::MaterializeTemporaryExprClass:
  3171. if (Expr *Result = EvalVal(
  3172. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  3173. refVars, ParentDecl))
  3174. return Result;
  3175. return E;
  3176. default:
  3177. // Check that we don't return or take the address of a reference to a
  3178. // temporary. This is only useful in C++.
  3179. if (!E->isTypeDependent() && E->isRValue())
  3180. return E;
  3181. // Everything else: we simply don't reason about them.
  3182. return NULL;
  3183. }
  3184. } while (true);
  3185. }
  3186. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  3187. /// Check for comparisons of floating point operands using != and ==.
  3188. /// Issue a warning if these are no self-comparisons, as they are not likely
  3189. /// to do what the programmer intended.
  3190. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  3191. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  3192. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  3193. // Special case: check for x == x (which is OK).
  3194. // Do not emit warnings for such cases.
  3195. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  3196. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  3197. if (DRL->getDecl() == DRR->getDecl())
  3198. return;
  3199. // Special case: check for comparisons against literals that can be exactly
  3200. // represented by APFloat. In such cases, do not emit a warning. This
  3201. // is a heuristic: often comparison against such literals are used to
  3202. // detect if a value in a variable has not changed. This clearly can
  3203. // lead to false negatives.
  3204. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  3205. if (FLL->isExact())
  3206. return;
  3207. } else
  3208. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  3209. if (FLR->isExact())
  3210. return;
  3211. // Check for comparisons with builtin types.
  3212. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  3213. if (CL->isBuiltinCall())
  3214. return;
  3215. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  3216. if (CR->isBuiltinCall())
  3217. return;
  3218. // Emit the diagnostic.
  3219. Diag(Loc, diag::warn_floatingpoint_eq)
  3220. << LHS->getSourceRange() << RHS->getSourceRange();
  3221. }
  3222. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  3223. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  3224. namespace {
  3225. /// Structure recording the 'active' range of an integer-valued
  3226. /// expression.
  3227. struct IntRange {
  3228. /// The number of bits active in the int.
  3229. unsigned Width;
  3230. /// True if the int is known not to have negative values.
  3231. bool NonNegative;
  3232. IntRange(unsigned Width, bool NonNegative)
  3233. : Width(Width), NonNegative(NonNegative)
  3234. {}
  3235. /// Returns the range of the bool type.
  3236. static IntRange forBoolType() {
  3237. return IntRange(1, true);
  3238. }
  3239. /// Returns the range of an opaque value of the given integral type.
  3240. static IntRange forValueOfType(ASTContext &C, QualType T) {
  3241. return forValueOfCanonicalType(C,
  3242. T->getCanonicalTypeInternal().getTypePtr());
  3243. }
  3244. /// Returns the range of an opaque value of a canonical integral type.
  3245. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  3246. assert(T->isCanonicalUnqualified());
  3247. if (const VectorType *VT = dyn_cast<VectorType>(T))
  3248. T = VT->getElementType().getTypePtr();
  3249. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  3250. T = CT->getElementType().getTypePtr();
  3251. // For enum types, use the known bit width of the enumerators.
  3252. if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  3253. EnumDecl *Enum = ET->getDecl();
  3254. if (!Enum->isCompleteDefinition())
  3255. return IntRange(C.getIntWidth(QualType(T, 0)), false);
  3256. unsigned NumPositive = Enum->getNumPositiveBits();
  3257. unsigned NumNegative = Enum->getNumNegativeBits();
  3258. return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
  3259. }
  3260. const BuiltinType *BT = cast<BuiltinType>(T);
  3261. assert(BT->isInteger());
  3262. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  3263. }
  3264. /// Returns the "target" range of a canonical integral type, i.e.
  3265. /// the range of values expressible in the type.
  3266. ///
  3267. /// This matches forValueOfCanonicalType except that enums have the
  3268. /// full range of their type, not the range of their enumerators.
  3269. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  3270. assert(T->isCanonicalUnqualified());
  3271. if (const VectorType *VT = dyn_cast<VectorType>(T))
  3272. T = VT->getElementType().getTypePtr();
  3273. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  3274. T = CT->getElementType().getTypePtr();
  3275. if (const EnumType *ET = dyn_cast<EnumType>(T))
  3276. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  3277. const BuiltinType *BT = cast<BuiltinType>(T);
  3278. assert(BT->isInteger());
  3279. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  3280. }
  3281. /// Returns the supremum of two ranges: i.e. their conservative merge.
  3282. static IntRange join(IntRange L, IntRange R) {
  3283. return IntRange(std::max(L.Width, R.Width),
  3284. L.NonNegative && R.NonNegative);
  3285. }
  3286. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  3287. static IntRange meet(IntRange L, IntRange R) {
  3288. return IntRange(std::min(L.Width, R.Width),
  3289. L.NonNegative || R.NonNegative);
  3290. }
  3291. };
  3292. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  3293. unsigned MaxWidth) {
  3294. if (value.isSigned() && value.isNegative())
  3295. return IntRange(value.getMinSignedBits(), false);
  3296. if (value.getBitWidth() > MaxWidth)
  3297. value = value.trunc(MaxWidth);
  3298. // isNonNegative() just checks the sign bit without considering
  3299. // signedness.
  3300. return IntRange(value.getActiveBits(), true);
  3301. }
  3302. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  3303. unsigned MaxWidth) {
  3304. if (result.isInt())
  3305. return GetValueRange(C, result.getInt(), MaxWidth);
  3306. if (result.isVector()) {
  3307. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  3308. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  3309. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  3310. R = IntRange::join(R, El);
  3311. }
  3312. return R;
  3313. }
  3314. if (result.isComplexInt()) {
  3315. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  3316. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  3317. return IntRange::join(R, I);
  3318. }
  3319. // This can happen with lossless casts to intptr_t of "based" lvalues.
  3320. // Assume it might use arbitrary bits.
  3321. // FIXME: The only reason we need to pass the type in here is to get
  3322. // the sign right on this one case. It would be nice if APValue
  3323. // preserved this.
  3324. assert(result.isLValue() || result.isAddrLabelDiff());
  3325. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  3326. }
  3327. /// Pseudo-evaluate the given integer expression, estimating the
  3328. /// range of values it might take.
  3329. ///
  3330. /// \param MaxWidth - the width to which the value will be truncated
  3331. static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
  3332. E = E->IgnoreParens();
  3333. // Try a full evaluation first.
  3334. Expr::EvalResult result;
  3335. if (E->EvaluateAsRValue(result, C))
  3336. return GetValueRange(C, result.Val, E->getType(), MaxWidth);
  3337. // I think we only want to look through implicit casts here; if the
  3338. // user has an explicit widening cast, we should treat the value as
  3339. // being of the new, wider type.
  3340. if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
  3341. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  3342. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  3343. IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
  3344. bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
  3345. // Assume that non-integer casts can span the full range of the type.
  3346. if (!isIntegerCast)
  3347. return OutputTypeRange;
  3348. IntRange SubRange
  3349. = GetExprRange(C, CE->getSubExpr(),
  3350. std::min(MaxWidth, OutputTypeRange.Width));
  3351. // Bail out if the subexpr's range is as wide as the cast type.
  3352. if (SubRange.Width >= OutputTypeRange.Width)
  3353. return OutputTypeRange;
  3354. // Otherwise, we take the smaller width, and we're non-negative if
  3355. // either the output type or the subexpr is.
  3356. return IntRange(SubRange.Width,
  3357. SubRange.NonNegative || OutputTypeRange.NonNegative);
  3358. }
  3359. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  3360. // If we can fold the condition, just take that operand.
  3361. bool CondResult;
  3362. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  3363. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  3364. : CO->getFalseExpr(),
  3365. MaxWidth);
  3366. // Otherwise, conservatively merge.
  3367. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  3368. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  3369. return IntRange::join(L, R);
  3370. }
  3371. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  3372. switch (BO->getOpcode()) {
  3373. // Boolean-valued operations are single-bit and positive.
  3374. case BO_LAnd:
  3375. case BO_LOr:
  3376. case BO_LT:
  3377. case BO_GT:
  3378. case BO_LE:
  3379. case BO_GE:
  3380. case BO_EQ:
  3381. case BO_NE:
  3382. return IntRange::forBoolType();
  3383. // The type of the assignments is the type of the LHS, so the RHS
  3384. // is not necessarily the same type.
  3385. case BO_MulAssign:
  3386. case BO_DivAssign:
  3387. case BO_RemAssign:
  3388. case BO_AddAssign:
  3389. case BO_SubAssign:
  3390. case BO_XorAssign:
  3391. case BO_OrAssign:
  3392. // TODO: bitfields?
  3393. return IntRange::forValueOfType(C, E->getType());
  3394. // Simple assignments just pass through the RHS, which will have
  3395. // been coerced to the LHS type.
  3396. case BO_Assign:
  3397. // TODO: bitfields?
  3398. return GetExprRange(C, BO->getRHS(), MaxWidth);
  3399. // Operations with opaque sources are black-listed.
  3400. case BO_PtrMemD:
  3401. case BO_PtrMemI:
  3402. return IntRange::forValueOfType(C, E->getType());
  3403. // Bitwise-and uses the *infinum* of the two source ranges.
  3404. case BO_And:
  3405. case BO_AndAssign:
  3406. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  3407. GetExprRange(C, BO->getRHS(), MaxWidth));
  3408. // Left shift gets black-listed based on a judgement call.
  3409. case BO_Shl:
  3410. // ...except that we want to treat '1 << (blah)' as logically
  3411. // positive. It's an important idiom.
  3412. if (IntegerLiteral *I
  3413. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  3414. if (I->getValue() == 1) {
  3415. IntRange R = IntRange::forValueOfType(C, E->getType());
  3416. return IntRange(R.Width, /*NonNegative*/ true);
  3417. }
  3418. }
  3419. // fallthrough
  3420. case BO_ShlAssign:
  3421. return IntRange::forValueOfType(C, E->getType());
  3422. // Right shift by a constant can narrow its left argument.
  3423. case BO_Shr:
  3424. case BO_ShrAssign: {
  3425. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  3426. // If the shift amount is a positive constant, drop the width by
  3427. // that much.
  3428. llvm::APSInt shift;
  3429. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  3430. shift.isNonNegative()) {
  3431. unsigned zext = shift.getZExtValue();
  3432. if (zext >= L.Width)
  3433. L.Width = (L.NonNegative ? 0 : 1);
  3434. else
  3435. L.Width -= zext;
  3436. }
  3437. return L;
  3438. }
  3439. // Comma acts as its right operand.
  3440. case BO_Comma:
  3441. return GetExprRange(C, BO->getRHS(), MaxWidth);
  3442. // Black-list pointer subtractions.
  3443. case BO_Sub:
  3444. if (BO->getLHS()->getType()->isPointerType())
  3445. return IntRange::forValueOfType(C, E->getType());
  3446. break;
  3447. // The width of a division result is mostly determined by the size
  3448. // of the LHS.
  3449. case BO_Div: {
  3450. // Don't 'pre-truncate' the operands.
  3451. unsigned opWidth = C.getIntWidth(E->getType());
  3452. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  3453. // If the divisor is constant, use that.
  3454. llvm::APSInt divisor;
  3455. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  3456. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  3457. if (log2 >= L.Width)
  3458. L.Width = (L.NonNegative ? 0 : 1);
  3459. else
  3460. L.Width = std::min(L.Width - log2, MaxWidth);
  3461. return L;
  3462. }
  3463. // Otherwise, just use the LHS's width.
  3464. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  3465. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  3466. }
  3467. // The result of a remainder can't be larger than the result of
  3468. // either side.
  3469. case BO_Rem: {
  3470. // Don't 'pre-truncate' the operands.
  3471. unsigned opWidth = C.getIntWidth(E->getType());
  3472. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  3473. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  3474. IntRange meet = IntRange::meet(L, R);
  3475. meet.Width = std::min(meet.Width, MaxWidth);
  3476. return meet;
  3477. }
  3478. // The default behavior is okay for these.
  3479. case BO_Mul:
  3480. case BO_Add:
  3481. case BO_Xor:
  3482. case BO_Or:
  3483. break;
  3484. }
  3485. // The default case is to treat the operation as if it were closed
  3486. // on the narrowest type that encompasses both operands.
  3487. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  3488. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  3489. return IntRange::join(L, R);
  3490. }
  3491. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  3492. switch (UO->getOpcode()) {
  3493. // Boolean-valued operations are white-listed.
  3494. case UO_LNot:
  3495. return IntRange::forBoolType();
  3496. // Operations with opaque sources are black-listed.
  3497. case UO_Deref:
  3498. case UO_AddrOf: // should be impossible
  3499. return IntRange::forValueOfType(C, E->getType());
  3500. default:
  3501. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  3502. }
  3503. }
  3504. if (dyn_cast<OffsetOfExpr>(E)) {
  3505. IntRange::forValueOfType(C, E->getType());
  3506. }
  3507. if (FieldDecl *BitField = E->getBitField())
  3508. return IntRange(BitField->getBitWidthValue(C),
  3509. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  3510. return IntRange::forValueOfType(C, E->getType());
  3511. }
  3512. static IntRange GetExprRange(ASTContext &C, Expr *E) {
  3513. return GetExprRange(C, E, C.getIntWidth(E->getType()));
  3514. }
  3515. /// Checks whether the given value, which currently has the given
  3516. /// source semantics, has the same value when coerced through the
  3517. /// target semantics.
  3518. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  3519. const llvm::fltSemantics &Src,
  3520. const llvm::fltSemantics &Tgt) {
  3521. llvm::APFloat truncated = value;
  3522. bool ignored;
  3523. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  3524. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  3525. return truncated.bitwiseIsEqual(value);
  3526. }
  3527. /// Checks whether the given value, which currently has the given
  3528. /// source semantics, has the same value when coerced through the
  3529. /// target semantics.
  3530. ///
  3531. /// The value might be a vector of floats (or a complex number).
  3532. static bool IsSameFloatAfterCast(const APValue &value,
  3533. const llvm::fltSemantics &Src,
  3534. const llvm::fltSemantics &Tgt) {
  3535. if (value.isFloat())
  3536. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  3537. if (value.isVector()) {
  3538. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  3539. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  3540. return false;
  3541. return true;
  3542. }
  3543. assert(value.isComplexFloat());
  3544. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  3545. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  3546. }
  3547. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  3548. static bool IsZero(Sema &S, Expr *E) {
  3549. // Suppress cases where we are comparing against an enum constant.
  3550. if (const DeclRefExpr *DR =
  3551. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  3552. if (isa<EnumConstantDecl>(DR->getDecl()))
  3553. return false;
  3554. // Suppress cases where the '0' value is expanded from a macro.
  3555. if (E->getLocStart().isMacroID())
  3556. return false;
  3557. llvm::APSInt Value;
  3558. return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
  3559. }
  3560. static bool HasEnumType(Expr *E) {
  3561. // Strip off implicit integral promotions.
  3562. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  3563. if (ICE->getCastKind() != CK_IntegralCast &&
  3564. ICE->getCastKind() != CK_NoOp)
  3565. break;
  3566. E = ICE->getSubExpr();
  3567. }
  3568. return E->getType()->isEnumeralType();
  3569. }
  3570. static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
  3571. BinaryOperatorKind op = E->getOpcode();
  3572. if (E->isValueDependent())
  3573. return;
  3574. if (op == BO_LT && IsZero(S, E->getRHS())) {
  3575. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  3576. << "< 0" << "false" << HasEnumType(E->getLHS())
  3577. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3578. } else if (op == BO_GE && IsZero(S, E->getRHS())) {
  3579. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  3580. << ">= 0" << "true" << HasEnumType(E->getLHS())
  3581. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3582. } else if (op == BO_GT && IsZero(S, E->getLHS())) {
  3583. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  3584. << "0 >" << "false" << HasEnumType(E->getRHS())
  3585. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3586. } else if (op == BO_LE && IsZero(S, E->getLHS())) {
  3587. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  3588. << "0 <=" << "true" << HasEnumType(E->getRHS())
  3589. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3590. }
  3591. }
  3592. /// Analyze the operands of the given comparison. Implements the
  3593. /// fallback case from AnalyzeComparison.
  3594. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  3595. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  3596. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  3597. }
  3598. /// \brief Implements -Wsign-compare.
  3599. ///
  3600. /// \param E the binary operator to check for warnings
  3601. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  3602. // The type the comparison is being performed in.
  3603. QualType T = E->getLHS()->getType();
  3604. assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
  3605. && "comparison with mismatched types");
  3606. // We don't do anything special if this isn't an unsigned integral
  3607. // comparison: we're only interested in integral comparisons, and
  3608. // signed comparisons only happen in cases we don't care to warn about.
  3609. //
  3610. // We also don't care about value-dependent expressions or expressions
  3611. // whose result is a constant.
  3612. if (!T->hasUnsignedIntegerRepresentation()
  3613. || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
  3614. return AnalyzeImpConvsInComparison(S, E);
  3615. Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
  3616. Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
  3617. // Check to see if one of the (unmodified) operands is of different
  3618. // signedness.
  3619. Expr *signedOperand, *unsignedOperand;
  3620. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  3621. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  3622. "unsigned comparison between two signed integer expressions?");
  3623. signedOperand = LHS;
  3624. unsignedOperand = RHS;
  3625. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  3626. signedOperand = RHS;
  3627. unsignedOperand = LHS;
  3628. } else {
  3629. CheckTrivialUnsignedComparison(S, E);
  3630. return AnalyzeImpConvsInComparison(S, E);
  3631. }
  3632. // Otherwise, calculate the effective range of the signed operand.
  3633. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  3634. // Go ahead and analyze implicit conversions in the operands. Note
  3635. // that we skip the implicit conversions on both sides.
  3636. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  3637. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  3638. // If the signed range is non-negative, -Wsign-compare won't fire,
  3639. // but we should still check for comparisons which are always true
  3640. // or false.
  3641. if (signedRange.NonNegative)
  3642. return CheckTrivialUnsignedComparison(S, E);
  3643. // For (in)equality comparisons, if the unsigned operand is a
  3644. // constant which cannot collide with a overflowed signed operand,
  3645. // then reinterpreting the signed operand as unsigned will not
  3646. // change the result of the comparison.
  3647. if (E->isEqualityOp()) {
  3648. unsigned comparisonWidth = S.Context.getIntWidth(T);
  3649. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  3650. // We should never be unable to prove that the unsigned operand is
  3651. // non-negative.
  3652. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  3653. if (unsignedRange.Width < comparisonWidth)
  3654. return;
  3655. }
  3656. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  3657. S.PDiag(diag::warn_mixed_sign_comparison)
  3658. << LHS->getType() << RHS->getType()
  3659. << LHS->getSourceRange() << RHS->getSourceRange());
  3660. }
  3661. /// Analyzes an attempt to assign the given value to a bitfield.
  3662. ///
  3663. /// Returns true if there was something fishy about the attempt.
  3664. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  3665. SourceLocation InitLoc) {
  3666. assert(Bitfield->isBitField());
  3667. if (Bitfield->isInvalidDecl())
  3668. return false;
  3669. // White-list bool bitfields.
  3670. if (Bitfield->getType()->isBooleanType())
  3671. return false;
  3672. // Ignore value- or type-dependent expressions.
  3673. if (Bitfield->getBitWidth()->isValueDependent() ||
  3674. Bitfield->getBitWidth()->isTypeDependent() ||
  3675. Init->isValueDependent() ||
  3676. Init->isTypeDependent())
  3677. return false;
  3678. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  3679. llvm::APSInt Value;
  3680. if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
  3681. return false;
  3682. unsigned OriginalWidth = Value.getBitWidth();
  3683. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  3684. if (OriginalWidth <= FieldWidth)
  3685. return false;
  3686. // Compute the value which the bitfield will contain.
  3687. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  3688. TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
  3689. // Check whether the stored value is equal to the original value.
  3690. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  3691. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  3692. return false;
  3693. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  3694. // therefore don't strictly fit into a signed bitfield of width 1.
  3695. if (FieldWidth == 1 && Value == 1)
  3696. return false;
  3697. std::string PrettyValue = Value.toString(10);
  3698. std::string PrettyTrunc = TruncatedValue.toString(10);
  3699. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  3700. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  3701. << Init->getSourceRange();
  3702. return true;
  3703. }
  3704. /// Analyze the given simple or compound assignment for warning-worthy
  3705. /// operations.
  3706. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  3707. // Just recurse on the LHS.
  3708. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  3709. // We want to recurse on the RHS as normal unless we're assigning to
  3710. // a bitfield.
  3711. if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
  3712. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  3713. E->getOperatorLoc())) {
  3714. // Recurse, ignoring any implicit conversions on the RHS.
  3715. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  3716. E->getOperatorLoc());
  3717. }
  3718. }
  3719. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  3720. }
  3721. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  3722. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  3723. SourceLocation CContext, unsigned diag,
  3724. bool pruneControlFlow = false) {
  3725. if (pruneControlFlow) {
  3726. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  3727. S.PDiag(diag)
  3728. << SourceType << T << E->getSourceRange()
  3729. << SourceRange(CContext));
  3730. return;
  3731. }
  3732. S.Diag(E->getExprLoc(), diag)
  3733. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  3734. }
  3735. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  3736. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  3737. SourceLocation CContext, unsigned diag,
  3738. bool pruneControlFlow = false) {
  3739. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  3740. }
  3741. /// Diagnose an implicit cast from a literal expression. Does not warn when the
  3742. /// cast wouldn't lose information.
  3743. void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
  3744. SourceLocation CContext) {
  3745. // Try to convert the literal exactly to an integer. If we can, don't warn.
  3746. bool isExact = false;
  3747. const llvm::APFloat &Value = FL->getValue();
  3748. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  3749. T->hasUnsignedIntegerRepresentation());
  3750. if (Value.convertToInteger(IntegerValue,
  3751. llvm::APFloat::rmTowardZero, &isExact)
  3752. == llvm::APFloat::opOK && isExact)
  3753. return;
  3754. SmallString<16> PrettySourceValue;
  3755. Value.toString(PrettySourceValue);
  3756. SmallString<16> PrettyTargetValue;
  3757. if (T->isSpecificBuiltinType(BuiltinType::Bool))
  3758. PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
  3759. else
  3760. IntegerValue.toString(PrettyTargetValue);
  3761. S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
  3762. << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
  3763. << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
  3764. }
  3765. std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
  3766. if (!Range.Width) return "0";
  3767. llvm::APSInt ValueInRange = Value;
  3768. ValueInRange.setIsSigned(!Range.NonNegative);
  3769. ValueInRange = ValueInRange.trunc(Range.Width);
  3770. return ValueInRange.toString(10);
  3771. }
  3772. void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  3773. SourceLocation CC, bool *ICContext = 0) {
  3774. if (E->isTypeDependent() || E->isValueDependent()) return;
  3775. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  3776. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  3777. if (Source == Target) return;
  3778. if (Target->isDependentType()) return;
  3779. // If the conversion context location is invalid don't complain. We also
  3780. // don't want to emit a warning if the issue occurs from the expansion of
  3781. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  3782. // delay this check as long as possible. Once we detect we are in that
  3783. // scenario, we just return.
  3784. if (CC.isInvalid())
  3785. return;
  3786. // Diagnose implicit casts to bool.
  3787. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  3788. if (isa<StringLiteral>(E))
  3789. // Warn on string literal to bool. Checks for string literals in logical
  3790. // expressions, for instances, assert(0 && "error here"), is prevented
  3791. // by a check in AnalyzeImplicitConversions().
  3792. return DiagnoseImpCast(S, E, T, CC,
  3793. diag::warn_impcast_string_literal_to_bool);
  3794. if (Source->isFunctionType()) {
  3795. // Warn on function to bool. Checks free functions and static member
  3796. // functions. Weakly imported functions are excluded from the check,
  3797. // since it's common to test their value to check whether the linker
  3798. // found a definition for them.
  3799. ValueDecl *D = 0;
  3800. if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
  3801. D = R->getDecl();
  3802. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  3803. D = M->getMemberDecl();
  3804. }
  3805. if (D && !D->isWeak()) {
  3806. if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
  3807. S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
  3808. << F << E->getSourceRange() << SourceRange(CC);
  3809. S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
  3810. << FixItHint::CreateInsertion(E->getExprLoc(), "&");
  3811. QualType ReturnType;
  3812. UnresolvedSet<4> NonTemplateOverloads;
  3813. S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
  3814. if (!ReturnType.isNull()
  3815. && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  3816. S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
  3817. << FixItHint::CreateInsertion(
  3818. S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
  3819. return;
  3820. }
  3821. }
  3822. }
  3823. }
  3824. // Strip vector types.
  3825. if (isa<VectorType>(Source)) {
  3826. if (!isa<VectorType>(Target)) {
  3827. if (S.SourceMgr.isInSystemMacro(CC))
  3828. return;
  3829. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  3830. }
  3831. // If the vector cast is cast between two vectors of the same size, it is
  3832. // a bitcast, not a conversion.
  3833. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  3834. return;
  3835. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  3836. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  3837. }
  3838. // Strip complex types.
  3839. if (isa<ComplexType>(Source)) {
  3840. if (!isa<ComplexType>(Target)) {
  3841. if (S.SourceMgr.isInSystemMacro(CC))
  3842. return;
  3843. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
  3844. }
  3845. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  3846. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  3847. }
  3848. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  3849. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  3850. // If the source is floating point...
  3851. if (SourceBT && SourceBT->isFloatingPoint()) {
  3852. // ...and the target is floating point...
  3853. if (TargetBT && TargetBT->isFloatingPoint()) {
  3854. // ...then warn if we're dropping FP rank.
  3855. // Builtin FP kinds are ordered by increasing FP rank.
  3856. if (SourceBT->getKind() > TargetBT->getKind()) {
  3857. // Don't warn about float constants that are precisely
  3858. // representable in the target type.
  3859. Expr::EvalResult result;
  3860. if (E->EvaluateAsRValue(result, S.Context)) {
  3861. // Value might be a float, a float vector, or a float complex.
  3862. if (IsSameFloatAfterCast(result.Val,
  3863. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  3864. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  3865. return;
  3866. }
  3867. if (S.SourceMgr.isInSystemMacro(CC))
  3868. return;
  3869. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  3870. }
  3871. return;
  3872. }
  3873. // If the target is integral, always warn.
  3874. if (TargetBT && TargetBT->isInteger()) {
  3875. if (S.SourceMgr.isInSystemMacro(CC))
  3876. return;
  3877. Expr *InnerE = E->IgnoreParenImpCasts();
  3878. // We also want to warn on, e.g., "int i = -1.234"
  3879. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  3880. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  3881. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  3882. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
  3883. DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
  3884. } else {
  3885. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
  3886. }
  3887. }
  3888. return;
  3889. }
  3890. if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
  3891. == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
  3892. && !Target->isBlockPointerType() && !Target->isMemberPointerType()) {
  3893. SourceLocation Loc = E->getSourceRange().getBegin();
  3894. if (Loc.isMacroID())
  3895. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
  3896. if (!Loc.isMacroID() || CC.isMacroID())
  3897. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  3898. << T << clang::SourceRange(CC)
  3899. << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
  3900. }
  3901. if (!Source->isIntegerType() || !Target->isIntegerType())
  3902. return;
  3903. // TODO: remove this early return once the false positives for constant->bool
  3904. // in templates, macros, etc, are reduced or removed.
  3905. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  3906. return;
  3907. IntRange SourceRange = GetExprRange(S.Context, E);
  3908. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  3909. if (SourceRange.Width > TargetRange.Width) {
  3910. // If the source is a constant, use a default-on diagnostic.
  3911. // TODO: this should happen for bitfield stores, too.
  3912. llvm::APSInt Value(32);
  3913. if (E->isIntegerConstantExpr(Value, S.Context)) {
  3914. if (S.SourceMgr.isInSystemMacro(CC))
  3915. return;
  3916. std::string PrettySourceValue = Value.toString(10);
  3917. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  3918. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  3919. S.PDiag(diag::warn_impcast_integer_precision_constant)
  3920. << PrettySourceValue << PrettyTargetValue
  3921. << E->getType() << T << E->getSourceRange()
  3922. << clang::SourceRange(CC));
  3923. return;
  3924. }
  3925. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  3926. if (S.SourceMgr.isInSystemMacro(CC))
  3927. return;
  3928. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  3929. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  3930. /* pruneControlFlow */ true);
  3931. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  3932. }
  3933. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  3934. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  3935. SourceRange.Width == TargetRange.Width)) {
  3936. if (S.SourceMgr.isInSystemMacro(CC))
  3937. return;
  3938. unsigned DiagID = diag::warn_impcast_integer_sign;
  3939. // Traditionally, gcc has warned about this under -Wsign-compare.
  3940. // We also want to warn about it in -Wconversion.
  3941. // So if -Wconversion is off, use a completely identical diagnostic
  3942. // in the sign-compare group.
  3943. // The conditional-checking code will
  3944. if (ICContext) {
  3945. DiagID = diag::warn_impcast_integer_sign_conditional;
  3946. *ICContext = true;
  3947. }
  3948. return DiagnoseImpCast(S, E, T, CC, DiagID);
  3949. }
  3950. // Diagnose conversions between different enumeration types.
  3951. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  3952. // type, to give us better diagnostics.
  3953. QualType SourceType = E->getType();
  3954. if (!S.getLangOpts().CPlusPlus) {
  3955. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  3956. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  3957. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  3958. SourceType = S.Context.getTypeDeclType(Enum);
  3959. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  3960. }
  3961. }
  3962. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  3963. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  3964. if ((SourceEnum->getDecl()->getIdentifier() ||
  3965. SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
  3966. (TargetEnum->getDecl()->getIdentifier() ||
  3967. TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
  3968. SourceEnum != TargetEnum) {
  3969. if (S.SourceMgr.isInSystemMacro(CC))
  3970. return;
  3971. return DiagnoseImpCast(S, E, SourceType, T, CC,
  3972. diag::warn_impcast_different_enum_types);
  3973. }
  3974. return;
  3975. }
  3976. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  3977. SourceLocation CC, QualType T);
  3978. void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  3979. SourceLocation CC, bool &ICContext) {
  3980. E = E->IgnoreParenImpCasts();
  3981. if (isa<ConditionalOperator>(E))
  3982. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  3983. AnalyzeImplicitConversions(S, E, CC);
  3984. if (E->getType() != T)
  3985. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  3986. return;
  3987. }
  3988. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  3989. SourceLocation CC, QualType T) {
  3990. AnalyzeImplicitConversions(S, E->getCond(), CC);
  3991. bool Suspicious = false;
  3992. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  3993. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  3994. // If -Wconversion would have warned about either of the candidates
  3995. // for a signedness conversion to the context type...
  3996. if (!Suspicious) return;
  3997. // ...but it's currently ignored...
  3998. if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
  3999. CC))
  4000. return;
  4001. // ...then check whether it would have warned about either of the
  4002. // candidates for a signedness conversion to the condition type.
  4003. if (E->getType() == T) return;
  4004. Suspicious = false;
  4005. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  4006. E->getType(), CC, &Suspicious);
  4007. if (!Suspicious)
  4008. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  4009. E->getType(), CC, &Suspicious);
  4010. }
  4011. /// AnalyzeImplicitConversions - Find and report any interesting
  4012. /// implicit conversions in the given expression. There are a couple
  4013. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  4014. void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
  4015. QualType T = OrigE->getType();
  4016. Expr *E = OrigE->IgnoreParenImpCasts();
  4017. if (E->isTypeDependent() || E->isValueDependent())
  4018. return;
  4019. // For conditional operators, we analyze the arguments as if they
  4020. // were being fed directly into the output.
  4021. if (isa<ConditionalOperator>(E)) {
  4022. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  4023. CheckConditionalOperator(S, CO, CC, T);
  4024. return;
  4025. }
  4026. // Go ahead and check any implicit conversions we might have skipped.
  4027. // The non-canonical typecheck is just an optimization;
  4028. // CheckImplicitConversion will filter out dead implicit conversions.
  4029. if (E->getType() != T)
  4030. CheckImplicitConversion(S, E, T, CC);
  4031. // Now continue drilling into this expression.
  4032. // Skip past explicit casts.
  4033. if (isa<ExplicitCastExpr>(E)) {
  4034. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  4035. return AnalyzeImplicitConversions(S, E, CC);
  4036. }
  4037. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  4038. // Do a somewhat different check with comparison operators.
  4039. if (BO->isComparisonOp())
  4040. return AnalyzeComparison(S, BO);
  4041. // And with simple assignments.
  4042. if (BO->getOpcode() == BO_Assign)
  4043. return AnalyzeAssignment(S, BO);
  4044. }
  4045. // These break the otherwise-useful invariant below. Fortunately,
  4046. // we don't really need to recurse into them, because any internal
  4047. // expressions should have been analyzed already when they were
  4048. // built into statements.
  4049. if (isa<StmtExpr>(E)) return;
  4050. // Don't descend into unevaluated contexts.
  4051. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  4052. // Now just recurse over the expression's children.
  4053. CC = E->getExprLoc();
  4054. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  4055. bool IsLogicalOperator = BO && BO->isLogicalOp();
  4056. for (Stmt::child_range I = E->children(); I; ++I) {
  4057. Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
  4058. if (!ChildExpr)
  4059. continue;
  4060. if (IsLogicalOperator &&
  4061. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  4062. // Ignore checking string literals that are in logical operators.
  4063. continue;
  4064. AnalyzeImplicitConversions(S, ChildExpr, CC);
  4065. }
  4066. }
  4067. } // end anonymous namespace
  4068. /// Diagnoses "dangerous" implicit conversions within the given
  4069. /// expression (which is a full expression). Implements -Wconversion
  4070. /// and -Wsign-compare.
  4071. ///
  4072. /// \param CC the "context" location of the implicit conversion, i.e.
  4073. /// the most location of the syntactic entity requiring the implicit
  4074. /// conversion
  4075. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  4076. // Don't diagnose in unevaluated contexts.
  4077. if (isUnevaluatedContext())
  4078. return;
  4079. // Don't diagnose for value- or type-dependent expressions.
  4080. if (E->isTypeDependent() || E->isValueDependent())
  4081. return;
  4082. // Check for array bounds violations in cases where the check isn't triggered
  4083. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  4084. // ArraySubscriptExpr is on the RHS of a variable initialization.
  4085. CheckArrayAccess(E);
  4086. // This is not the right CC for (e.g.) a variable initialization.
  4087. AnalyzeImplicitConversions(*this, E, CC);
  4088. }
  4089. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  4090. FieldDecl *BitField,
  4091. Expr *Init) {
  4092. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  4093. }
  4094. /// CheckParmsForFunctionDef - Check that the parameters of the given
  4095. /// function are appropriate for the definition of a function. This
  4096. /// takes care of any checks that cannot be performed on the
  4097. /// declaration itself, e.g., that the types of each of the function
  4098. /// parameters are complete.
  4099. bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
  4100. bool CheckParameterNames) {
  4101. bool HasInvalidParm = false;
  4102. for (; P != PEnd; ++P) {
  4103. ParmVarDecl *Param = *P;
  4104. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  4105. // function declarator that is part of a function definition of
  4106. // that function shall not have incomplete type.
  4107. //
  4108. // This is also C++ [dcl.fct]p6.
  4109. if (!Param->isInvalidDecl() &&
  4110. RequireCompleteType(Param->getLocation(), Param->getType(),
  4111. diag::err_typecheck_decl_incomplete_type)) {
  4112. Param->setInvalidDecl();
  4113. HasInvalidParm = true;
  4114. }
  4115. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  4116. // declaration of each parameter shall include an identifier.
  4117. if (CheckParameterNames &&
  4118. Param->getIdentifier() == 0 &&
  4119. !Param->isImplicit() &&
  4120. !getLangOpts().CPlusPlus)
  4121. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  4122. // C99 6.7.5.3p12:
  4123. // If the function declarator is not part of a definition of that
  4124. // function, parameters may have incomplete type and may use the [*]
  4125. // notation in their sequences of declarator specifiers to specify
  4126. // variable length array types.
  4127. QualType PType = Param->getOriginalType();
  4128. if (const ArrayType *AT = Context.getAsArrayType(PType)) {
  4129. if (AT->getSizeModifier() == ArrayType::Star) {
  4130. // FIXME: This diagnosic should point the '[*]' if source-location
  4131. // information is added for it.
  4132. Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
  4133. }
  4134. }
  4135. }
  4136. return HasInvalidParm;
  4137. }
  4138. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  4139. /// pointer cast increases the alignment requirements.
  4140. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  4141. // This is actually a lot of work to potentially be doing on every
  4142. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  4143. if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
  4144. TRange.getBegin())
  4145. == DiagnosticsEngine::Ignored)
  4146. return;
  4147. // Ignore dependent types.
  4148. if (T->isDependentType() || Op->getType()->isDependentType())
  4149. return;
  4150. // Require that the destination be a pointer type.
  4151. const PointerType *DestPtr = T->getAs<PointerType>();
  4152. if (!DestPtr) return;
  4153. // If the destination has alignment 1, we're done.
  4154. QualType DestPointee = DestPtr->getPointeeType();
  4155. if (DestPointee->isIncompleteType()) return;
  4156. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  4157. if (DestAlign.isOne()) return;
  4158. // Require that the source be a pointer type.
  4159. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  4160. if (!SrcPtr) return;
  4161. QualType SrcPointee = SrcPtr->getPointeeType();
  4162. // Whitelist casts from cv void*. We already implicitly
  4163. // whitelisted casts to cv void*, since they have alignment 1.
  4164. // Also whitelist casts involving incomplete types, which implicitly
  4165. // includes 'void'.
  4166. if (SrcPointee->isIncompleteType()) return;
  4167. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  4168. if (SrcAlign >= DestAlign) return;
  4169. Diag(TRange.getBegin(), diag::warn_cast_align)
  4170. << Op->getType() << T
  4171. << static_cast<unsigned>(SrcAlign.getQuantity())
  4172. << static_cast<unsigned>(DestAlign.getQuantity())
  4173. << TRange << Op->getSourceRange();
  4174. }
  4175. static const Type* getElementType(const Expr *BaseExpr) {
  4176. const Type* EltType = BaseExpr->getType().getTypePtr();
  4177. if (EltType->isAnyPointerType())
  4178. return EltType->getPointeeType().getTypePtr();
  4179. else if (EltType->isArrayType())
  4180. return EltType->getBaseElementTypeUnsafe();
  4181. return EltType;
  4182. }
  4183. /// \brief Check whether this array fits the idiom of a size-one tail padded
  4184. /// array member of a struct.
  4185. ///
  4186. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  4187. /// commonly used to emulate flexible arrays in C89 code.
  4188. static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
  4189. const NamedDecl *ND) {
  4190. if (Size != 1 || !ND) return false;
  4191. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  4192. if (!FD) return false;
  4193. // Don't consider sizes resulting from macro expansions or template argument
  4194. // substitution to form C89 tail-padded arrays.
  4195. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  4196. while (TInfo) {
  4197. TypeLoc TL = TInfo->getTypeLoc();
  4198. // Look through typedefs.
  4199. const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
  4200. if (TTL) {
  4201. const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
  4202. TInfo = TDL->getTypeSourceInfo();
  4203. continue;
  4204. }
  4205. ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
  4206. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  4207. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  4208. return false;
  4209. break;
  4210. }
  4211. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  4212. if (!RD) return false;
  4213. if (RD->isUnion()) return false;
  4214. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  4215. if (!CRD->isStandardLayout()) return false;
  4216. }
  4217. // See if this is the last field decl in the record.
  4218. const Decl *D = FD;
  4219. while ((D = D->getNextDeclInContext()))
  4220. if (isa<FieldDecl>(D))
  4221. return false;
  4222. return true;
  4223. }
  4224. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  4225. const ArraySubscriptExpr *ASE,
  4226. bool AllowOnePastEnd, bool IndexNegated) {
  4227. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  4228. if (IndexExpr->isValueDependent())
  4229. return;
  4230. const Type *EffectiveType = getElementType(BaseExpr);
  4231. BaseExpr = BaseExpr->IgnoreParenCasts();
  4232. const ConstantArrayType *ArrayTy =
  4233. Context.getAsConstantArrayType(BaseExpr->getType());
  4234. if (!ArrayTy)
  4235. return;
  4236. llvm::APSInt index;
  4237. if (!IndexExpr->EvaluateAsInt(index, Context))
  4238. return;
  4239. if (IndexNegated)
  4240. index = -index;
  4241. const NamedDecl *ND = NULL;
  4242. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  4243. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  4244. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  4245. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  4246. if (index.isUnsigned() || !index.isNegative()) {
  4247. llvm::APInt size = ArrayTy->getSize();
  4248. if (!size.isStrictlyPositive())
  4249. return;
  4250. const Type* BaseType = getElementType(BaseExpr);
  4251. if (BaseType != EffectiveType) {
  4252. // Make sure we're comparing apples to apples when comparing index to size
  4253. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  4254. uint64_t array_typesize = Context.getTypeSize(BaseType);
  4255. // Handle ptrarith_typesize being zero, such as when casting to void*
  4256. if (!ptrarith_typesize) ptrarith_typesize = 1;
  4257. if (ptrarith_typesize != array_typesize) {
  4258. // There's a cast to a different size type involved
  4259. uint64_t ratio = array_typesize / ptrarith_typesize;
  4260. // TODO: Be smarter about handling cases where array_typesize is not a
  4261. // multiple of ptrarith_typesize
  4262. if (ptrarith_typesize * ratio == array_typesize)
  4263. size *= llvm::APInt(size.getBitWidth(), ratio);
  4264. }
  4265. }
  4266. if (size.getBitWidth() > index.getBitWidth())
  4267. index = index.zext(size.getBitWidth());
  4268. else if (size.getBitWidth() < index.getBitWidth())
  4269. size = size.zext(index.getBitWidth());
  4270. // For array subscripting the index must be less than size, but for pointer
  4271. // arithmetic also allow the index (offset) to be equal to size since
  4272. // computing the next address after the end of the array is legal and
  4273. // commonly done e.g. in C++ iterators and range-based for loops.
  4274. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  4275. return;
  4276. // Also don't warn for arrays of size 1 which are members of some
  4277. // structure. These are often used to approximate flexible arrays in C89
  4278. // code.
  4279. if (IsTailPaddedMemberArray(*this, size, ND))
  4280. return;
  4281. // Suppress the warning if the subscript expression (as identified by the
  4282. // ']' location) and the index expression are both from macro expansions
  4283. // within a system header.
  4284. if (ASE) {
  4285. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  4286. ASE->getRBracketLoc());
  4287. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  4288. SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
  4289. IndexExpr->getLocStart());
  4290. if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
  4291. return;
  4292. }
  4293. }
  4294. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  4295. if (ASE)
  4296. DiagID = diag::warn_array_index_exceeds_bounds;
  4297. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  4298. PDiag(DiagID) << index.toString(10, true)
  4299. << size.toString(10, true)
  4300. << (unsigned)size.getLimitedValue(~0U)
  4301. << IndexExpr->getSourceRange());
  4302. } else {
  4303. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  4304. if (!ASE) {
  4305. DiagID = diag::warn_ptr_arith_precedes_bounds;
  4306. if (index.isNegative()) index = -index;
  4307. }
  4308. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  4309. PDiag(DiagID) << index.toString(10, true)
  4310. << IndexExpr->getSourceRange());
  4311. }
  4312. if (!ND) {
  4313. // Try harder to find a NamedDecl to point at in the note.
  4314. while (const ArraySubscriptExpr *ASE =
  4315. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  4316. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  4317. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  4318. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  4319. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  4320. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  4321. }
  4322. if (ND)
  4323. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  4324. PDiag(diag::note_array_index_out_of_bounds)
  4325. << ND->getDeclName());
  4326. }
  4327. void Sema::CheckArrayAccess(const Expr *expr) {
  4328. int AllowOnePastEnd = 0;
  4329. while (expr) {
  4330. expr = expr->IgnoreParenImpCasts();
  4331. switch (expr->getStmtClass()) {
  4332. case Stmt::ArraySubscriptExprClass: {
  4333. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  4334. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  4335. AllowOnePastEnd > 0);
  4336. return;
  4337. }
  4338. case Stmt::UnaryOperatorClass: {
  4339. // Only unwrap the * and & unary operators
  4340. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  4341. expr = UO->getSubExpr();
  4342. switch (UO->getOpcode()) {
  4343. case UO_AddrOf:
  4344. AllowOnePastEnd++;
  4345. break;
  4346. case UO_Deref:
  4347. AllowOnePastEnd--;
  4348. break;
  4349. default:
  4350. return;
  4351. }
  4352. break;
  4353. }
  4354. case Stmt::ConditionalOperatorClass: {
  4355. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  4356. if (const Expr *lhs = cond->getLHS())
  4357. CheckArrayAccess(lhs);
  4358. if (const Expr *rhs = cond->getRHS())
  4359. CheckArrayAccess(rhs);
  4360. return;
  4361. }
  4362. default:
  4363. return;
  4364. }
  4365. }
  4366. }
  4367. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  4368. namespace {
  4369. struct RetainCycleOwner {
  4370. RetainCycleOwner() : Variable(0), Indirect(false) {}
  4371. VarDecl *Variable;
  4372. SourceRange Range;
  4373. SourceLocation Loc;
  4374. bool Indirect;
  4375. void setLocsFrom(Expr *e) {
  4376. Loc = e->getExprLoc();
  4377. Range = e->getSourceRange();
  4378. }
  4379. };
  4380. }
  4381. /// Consider whether capturing the given variable can possibly lead to
  4382. /// a retain cycle.
  4383. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  4384. // In ARC, it's captured strongly iff the variable has __strong
  4385. // lifetime. In MRR, it's captured strongly if the variable is
  4386. // __block and has an appropriate type.
  4387. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  4388. return false;
  4389. owner.Variable = var;
  4390. owner.setLocsFrom(ref);
  4391. return true;
  4392. }
  4393. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  4394. while (true) {
  4395. e = e->IgnoreParens();
  4396. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  4397. switch (cast->getCastKind()) {
  4398. case CK_BitCast:
  4399. case CK_LValueBitCast:
  4400. case CK_LValueToRValue:
  4401. case CK_ARCReclaimReturnedObject:
  4402. e = cast->getSubExpr();
  4403. continue;
  4404. default:
  4405. return false;
  4406. }
  4407. }
  4408. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  4409. ObjCIvarDecl *ivar = ref->getDecl();
  4410. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  4411. return false;
  4412. // Try to find a retain cycle in the base.
  4413. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  4414. return false;
  4415. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  4416. owner.Indirect = true;
  4417. return true;
  4418. }
  4419. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  4420. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  4421. if (!var) return false;
  4422. return considerVariable(var, ref, owner);
  4423. }
  4424. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  4425. if (member->isArrow()) return false;
  4426. // Don't count this as an indirect ownership.
  4427. e = member->getBase();
  4428. continue;
  4429. }
  4430. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  4431. // Only pay attention to pseudo-objects on property references.
  4432. ObjCPropertyRefExpr *pre
  4433. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  4434. ->IgnoreParens());
  4435. if (!pre) return false;
  4436. if (pre->isImplicitProperty()) return false;
  4437. ObjCPropertyDecl *property = pre->getExplicitProperty();
  4438. if (!property->isRetaining() &&
  4439. !(property->getPropertyIvarDecl() &&
  4440. property->getPropertyIvarDecl()->getType()
  4441. .getObjCLifetime() == Qualifiers::OCL_Strong))
  4442. return false;
  4443. owner.Indirect = true;
  4444. if (pre->isSuperReceiver()) {
  4445. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  4446. if (!owner.Variable)
  4447. return false;
  4448. owner.Loc = pre->getLocation();
  4449. owner.Range = pre->getSourceRange();
  4450. return true;
  4451. }
  4452. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  4453. ->getSourceExpr());
  4454. continue;
  4455. }
  4456. // Array ivars?
  4457. return false;
  4458. }
  4459. }
  4460. namespace {
  4461. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  4462. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  4463. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  4464. Variable(variable), Capturer(0) {}
  4465. VarDecl *Variable;
  4466. Expr *Capturer;
  4467. void VisitDeclRefExpr(DeclRefExpr *ref) {
  4468. if (ref->getDecl() == Variable && !Capturer)
  4469. Capturer = ref;
  4470. }
  4471. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  4472. if (Capturer) return;
  4473. Visit(ref->getBase());
  4474. if (Capturer && ref->isFreeIvar())
  4475. Capturer = ref;
  4476. }
  4477. void VisitBlockExpr(BlockExpr *block) {
  4478. // Look inside nested blocks
  4479. if (block->getBlockDecl()->capturesVariable(Variable))
  4480. Visit(block->getBlockDecl()->getBody());
  4481. }
  4482. };
  4483. }
  4484. /// Check whether the given argument is a block which captures a
  4485. /// variable.
  4486. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  4487. assert(owner.Variable && owner.Loc.isValid());
  4488. e = e->IgnoreParenCasts();
  4489. BlockExpr *block = dyn_cast<BlockExpr>(e);
  4490. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  4491. return 0;
  4492. FindCaptureVisitor visitor(S.Context, owner.Variable);
  4493. visitor.Visit(block->getBlockDecl()->getBody());
  4494. return visitor.Capturer;
  4495. }
  4496. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  4497. RetainCycleOwner &owner) {
  4498. assert(capturer);
  4499. assert(owner.Variable && owner.Loc.isValid());
  4500. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  4501. << owner.Variable << capturer->getSourceRange();
  4502. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  4503. << owner.Indirect << owner.Range;
  4504. }
  4505. /// Check for a keyword selector that starts with the word 'add' or
  4506. /// 'set'.
  4507. static bool isSetterLikeSelector(Selector sel) {
  4508. if (sel.isUnarySelector()) return false;
  4509. StringRef str = sel.getNameForSlot(0);
  4510. while (!str.empty() && str.front() == '_') str = str.substr(1);
  4511. if (str.startswith("set"))
  4512. str = str.substr(3);
  4513. else if (str.startswith("add")) {
  4514. // Specially whitelist 'addOperationWithBlock:'.
  4515. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  4516. return false;
  4517. str = str.substr(3);
  4518. }
  4519. else
  4520. return false;
  4521. if (str.empty()) return true;
  4522. return !islower(str.front());
  4523. }
  4524. /// Check a message send to see if it's likely to cause a retain cycle.
  4525. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  4526. // Only check instance methods whose selector looks like a setter.
  4527. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  4528. return;
  4529. // Try to find a variable that the receiver is strongly owned by.
  4530. RetainCycleOwner owner;
  4531. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  4532. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  4533. return;
  4534. } else {
  4535. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  4536. owner.Variable = getCurMethodDecl()->getSelfDecl();
  4537. owner.Loc = msg->getSuperLoc();
  4538. owner.Range = msg->getSuperLoc();
  4539. }
  4540. // Check whether the receiver is captured by any of the arguments.
  4541. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
  4542. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
  4543. return diagnoseRetainCycle(*this, capturer, owner);
  4544. }
  4545. /// Check a property assign to see if it's likely to cause a retain cycle.
  4546. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  4547. RetainCycleOwner owner;
  4548. if (!findRetainCycleOwner(*this, receiver, owner))
  4549. return;
  4550. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  4551. diagnoseRetainCycle(*this, capturer, owner);
  4552. }
  4553. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  4554. QualType LHS, Expr *RHS) {
  4555. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  4556. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  4557. return false;
  4558. // strip off any implicit cast added to get to the one arc-specific
  4559. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  4560. if (cast->getCastKind() == CK_ARCConsumeObject) {
  4561. Diag(Loc, diag::warn_arc_retained_assign)
  4562. << (LT == Qualifiers::OCL_ExplicitNone) << 1
  4563. << RHS->getSourceRange();
  4564. return true;
  4565. }
  4566. RHS = cast->getSubExpr();
  4567. }
  4568. return false;
  4569. }
  4570. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  4571. Expr *LHS, Expr *RHS) {
  4572. QualType LHSType;
  4573. // PropertyRef on LHS type need be directly obtained from
  4574. // its declaration as it has a PsuedoType.
  4575. ObjCPropertyRefExpr *PRE
  4576. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  4577. if (PRE && !PRE->isImplicitProperty()) {
  4578. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  4579. if (PD)
  4580. LHSType = PD->getType();
  4581. }
  4582. if (LHSType.isNull())
  4583. LHSType = LHS->getType();
  4584. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  4585. return;
  4586. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  4587. // FIXME. Check for other life times.
  4588. if (LT != Qualifiers::OCL_None)
  4589. return;
  4590. if (PRE) {
  4591. if (PRE->isImplicitProperty())
  4592. return;
  4593. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  4594. if (!PD)
  4595. return;
  4596. unsigned Attributes = PD->getPropertyAttributes();
  4597. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  4598. // when 'assign' attribute was not explicitly specified
  4599. // by user, ignore it and rely on property type itself
  4600. // for lifetime info.
  4601. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  4602. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  4603. LHSType->isObjCRetainableType())
  4604. return;
  4605. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  4606. if (cast->getCastKind() == CK_ARCConsumeObject) {
  4607. Diag(Loc, diag::warn_arc_retained_property_assign)
  4608. << RHS->getSourceRange();
  4609. return;
  4610. }
  4611. RHS = cast->getSubExpr();
  4612. }
  4613. }
  4614. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  4615. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  4616. if (cast->getCastKind() == CK_ARCConsumeObject) {
  4617. Diag(Loc, diag::warn_arc_retained_assign)
  4618. << 0 << 0<< RHS->getSourceRange();
  4619. return;
  4620. }
  4621. RHS = cast->getSubExpr();
  4622. }
  4623. }
  4624. }
  4625. }
  4626. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  4627. namespace {
  4628. bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  4629. SourceLocation StmtLoc,
  4630. const NullStmt *Body) {
  4631. // Do not warn if the body is a macro that expands to nothing, e.g:
  4632. //
  4633. // #define CALL(x)
  4634. // if (condition)
  4635. // CALL(0);
  4636. //
  4637. if (Body->hasLeadingEmptyMacro())
  4638. return false;
  4639. // Get line numbers of statement and body.
  4640. bool StmtLineInvalid;
  4641. unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
  4642. &StmtLineInvalid);
  4643. if (StmtLineInvalid)
  4644. return false;
  4645. bool BodyLineInvalid;
  4646. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  4647. &BodyLineInvalid);
  4648. if (BodyLineInvalid)
  4649. return false;
  4650. // Warn if null statement and body are on the same line.
  4651. if (StmtLine != BodyLine)
  4652. return false;
  4653. return true;
  4654. }
  4655. } // Unnamed namespace
  4656. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  4657. const Stmt *Body,
  4658. unsigned DiagID) {
  4659. // Since this is a syntactic check, don't emit diagnostic for template
  4660. // instantiations, this just adds noise.
  4661. if (CurrentInstantiationScope)
  4662. return;
  4663. // The body should be a null statement.
  4664. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  4665. if (!NBody)
  4666. return;
  4667. // Do the usual checks.
  4668. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  4669. return;
  4670. Diag(NBody->getSemiLoc(), DiagID);
  4671. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  4672. }
  4673. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  4674. const Stmt *PossibleBody) {
  4675. assert(!CurrentInstantiationScope); // Ensured by caller
  4676. SourceLocation StmtLoc;
  4677. const Stmt *Body;
  4678. unsigned DiagID;
  4679. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  4680. StmtLoc = FS->getRParenLoc();
  4681. Body = FS->getBody();
  4682. DiagID = diag::warn_empty_for_body;
  4683. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  4684. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  4685. Body = WS->getBody();
  4686. DiagID = diag::warn_empty_while_body;
  4687. } else
  4688. return; // Neither `for' nor `while'.
  4689. // The body should be a null statement.
  4690. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  4691. if (!NBody)
  4692. return;
  4693. // Skip expensive checks if diagnostic is disabled.
  4694. if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
  4695. DiagnosticsEngine::Ignored)
  4696. return;
  4697. // Do the usual checks.
  4698. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  4699. return;
  4700. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  4701. // noise level low, emit diagnostics only if for/while is followed by a
  4702. // CompoundStmt, e.g.:
  4703. // for (int i = 0; i < n; i++);
  4704. // {
  4705. // a(i);
  4706. // }
  4707. // or if for/while is followed by a statement with more indentation
  4708. // than for/while itself:
  4709. // for (int i = 0; i < n; i++);
  4710. // a(i);
  4711. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  4712. if (!ProbableTypo) {
  4713. bool BodyColInvalid;
  4714. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  4715. PossibleBody->getLocStart(),
  4716. &BodyColInvalid);
  4717. if (BodyColInvalid)
  4718. return;
  4719. bool StmtColInvalid;
  4720. unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
  4721. S->getLocStart(),
  4722. &StmtColInvalid);
  4723. if (StmtColInvalid)
  4724. return;
  4725. if (BodyCol > StmtCol)
  4726. ProbableTypo = true;
  4727. }
  4728. if (ProbableTypo) {
  4729. Diag(NBody->getSemiLoc(), DiagID);
  4730. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  4731. }
  4732. }