Tools.cpp 402 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060
  1. //===--- Tools.cpp - Tools Implementations ----------------------*- C++ -*-===//
  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. #include "Tools.h"
  10. #include "InputInfo.h"
  11. #include "ToolChains.h"
  12. #include "clang/Basic/CharInfo.h"
  13. #include "clang/Basic/LangOptions.h"
  14. #include "clang/Basic/ObjCRuntime.h"
  15. #include "clang/Basic/Version.h"
  16. #include "clang/Config/config.h"
  17. #include "clang/Driver/Action.h"
  18. #include "clang/Driver/Compilation.h"
  19. #include "clang/Driver/Driver.h"
  20. #include "clang/Driver/DriverDiagnostic.h"
  21. #include "clang/Driver/Job.h"
  22. #include "clang/Driver/Options.h"
  23. #include "clang/Driver/SanitizerArgs.h"
  24. #include "clang/Driver/ToolChain.h"
  25. #include "clang/Driver/Util.h"
  26. #include "llvm/ADT/STLExtras.h"
  27. #include "llvm/ADT/SmallString.h"
  28. #include "llvm/ADT/StringExtras.h"
  29. #include "llvm/ADT/StringSwitch.h"
  30. #include "llvm/ADT/Twine.h"
  31. #include "llvm/Option/Arg.h"
  32. #include "llvm/Option/ArgList.h"
  33. #include "llvm/Option/Option.h"
  34. #include "llvm/Support/CodeGen.h"
  35. #include "llvm/Support/Compression.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/FileSystem.h"
  38. #include "llvm/Support/Host.h"
  39. #include "llvm/Support/Path.h"
  40. #include "llvm/Support/Process.h"
  41. #include "llvm/Support/Program.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include "llvm/Support/TargetParser.h"
  44. #ifdef LLVM_ON_UNIX
  45. #include <unistd.h> // For getuid().
  46. #endif
  47. using namespace clang::driver;
  48. using namespace clang::driver::tools;
  49. using namespace clang;
  50. using namespace llvm::opt;
  51. static void handleTargetFeaturesGroup(const ArgList &Args,
  52. std::vector<const char *> &Features,
  53. OptSpecifier Group) {
  54. for (const Arg *A : Args.filtered(Group)) {
  55. StringRef Name = A->getOption().getName();
  56. A->claim();
  57. // Skip over "-m".
  58. assert(Name.startswith("m") && "Invalid feature name.");
  59. Name = Name.substr(1);
  60. bool IsNegative = Name.startswith("no-");
  61. if (IsNegative)
  62. Name = Name.substr(3);
  63. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  64. }
  65. }
  66. static const char *getSparcAsmModeForCPU(StringRef Name,
  67. const llvm::Triple &Triple) {
  68. if (Triple.getArch() == llvm::Triple::sparcv9) {
  69. return llvm::StringSwitch<const char *>(Name)
  70. .Case("niagara", "-Av9b")
  71. .Case("niagara2", "-Av9b")
  72. .Case("niagara3", "-Av9d")
  73. .Case("niagara4", "-Av9d")
  74. .Default("-Av9");
  75. } else {
  76. return llvm::StringSwitch<const char *>(Name)
  77. .Case("v8", "-Av8")
  78. .Case("supersparc", "-Av8")
  79. .Case("sparclite", "-Asparclite")
  80. .Case("f934", "-Asparclite")
  81. .Case("hypersparc", "-Av8")
  82. .Case("sparclite86x", "-Asparclite")
  83. .Case("sparclet", "-Asparclet")
  84. .Case("tsc701", "-Asparclet")
  85. .Case("v9", "-Av8plus")
  86. .Case("ultrasparc", "-Av8plus")
  87. .Case("ultrasparc3", "-Av8plus")
  88. .Case("niagara", "-Av8plusb")
  89. .Case("niagara2", "-Av8plusb")
  90. .Case("niagara3", "-Av8plusd")
  91. .Case("niagara4", "-Av8plusd")
  92. .Default("-Av8");
  93. }
  94. }
  95. /// CheckPreprocessingOptions - Perform some validation of preprocessing
  96. /// arguments that is shared with gcc.
  97. static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
  98. if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
  99. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
  100. !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
  101. D.Diag(diag::err_drv_argument_only_allowed_with)
  102. << A->getBaseArg().getAsString(Args)
  103. << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
  104. }
  105. }
  106. }
  107. /// CheckCodeGenerationOptions - Perform some validation of code generation
  108. /// arguments that is shared with gcc.
  109. static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
  110. // In gcc, only ARM checks this, but it seems reasonable to check universally.
  111. if (Args.hasArg(options::OPT_static))
  112. if (const Arg *A =
  113. Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
  114. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  115. << "-static";
  116. }
  117. // Add backslashes to escape spaces and other backslashes.
  118. // This is used for the space-separated argument list specified with
  119. // the -dwarf-debug-flags option.
  120. static void EscapeSpacesAndBackslashes(const char *Arg,
  121. SmallVectorImpl<char> &Res) {
  122. for (; *Arg; ++Arg) {
  123. switch (*Arg) {
  124. default:
  125. break;
  126. case ' ':
  127. case '\\':
  128. Res.push_back('\\');
  129. break;
  130. }
  131. Res.push_back(*Arg);
  132. }
  133. }
  134. // Quote target names for inclusion in GNU Make dependency files.
  135. // Only the characters '$', '#', ' ', '\t' are quoted.
  136. static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
  137. for (unsigned i = 0, e = Target.size(); i != e; ++i) {
  138. switch (Target[i]) {
  139. case ' ':
  140. case '\t':
  141. // Escape the preceding backslashes
  142. for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
  143. Res.push_back('\\');
  144. // Escape the space/tab
  145. Res.push_back('\\');
  146. break;
  147. case '$':
  148. Res.push_back('$');
  149. break;
  150. case '#':
  151. Res.push_back('\\');
  152. break;
  153. default:
  154. break;
  155. }
  156. Res.push_back(Target[i]);
  157. }
  158. }
  159. static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
  160. const char *ArgName, const char *EnvVar) {
  161. const char *DirList = ::getenv(EnvVar);
  162. bool CombinedArg = false;
  163. if (!DirList)
  164. return; // Nothing to do.
  165. StringRef Name(ArgName);
  166. if (Name.equals("-I") || Name.equals("-L"))
  167. CombinedArg = true;
  168. StringRef Dirs(DirList);
  169. if (Dirs.empty()) // Empty string should not add '.'.
  170. return;
  171. StringRef::size_type Delim;
  172. while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
  173. if (Delim == 0) { // Leading colon.
  174. if (CombinedArg) {
  175. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  176. } else {
  177. CmdArgs.push_back(ArgName);
  178. CmdArgs.push_back(".");
  179. }
  180. } else {
  181. if (CombinedArg) {
  182. CmdArgs.push_back(
  183. Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
  184. } else {
  185. CmdArgs.push_back(ArgName);
  186. CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
  187. }
  188. }
  189. Dirs = Dirs.substr(Delim + 1);
  190. }
  191. if (Dirs.empty()) { // Trailing colon.
  192. if (CombinedArg) {
  193. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  194. } else {
  195. CmdArgs.push_back(ArgName);
  196. CmdArgs.push_back(".");
  197. }
  198. } else { // Add the last path.
  199. if (CombinedArg) {
  200. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
  201. } else {
  202. CmdArgs.push_back(ArgName);
  203. CmdArgs.push_back(Args.MakeArgString(Dirs));
  204. }
  205. }
  206. }
  207. static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
  208. const ArgList &Args, ArgStringList &CmdArgs) {
  209. const Driver &D = TC.getDriver();
  210. // Add extra linker input arguments which are not treated as inputs
  211. // (constructed via -Xarch_).
  212. Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
  213. for (const auto &II : Inputs) {
  214. if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
  215. // Don't try to pass LLVM inputs unless we have native support.
  216. D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
  217. // Add filenames immediately.
  218. if (II.isFilename()) {
  219. CmdArgs.push_back(II.getFilename());
  220. continue;
  221. }
  222. // Otherwise, this is a linker input argument.
  223. const Arg &A = II.getInputArg();
  224. // Handle reserved library options.
  225. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
  226. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  227. else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
  228. TC.AddCCKextLibArgs(Args, CmdArgs);
  229. else if (A.getOption().matches(options::OPT_z)) {
  230. // Pass -z prefix for gcc linker compatibility.
  231. A.claim();
  232. A.render(Args, CmdArgs);
  233. } else {
  234. A.renderAsInput(Args, CmdArgs);
  235. }
  236. }
  237. // LIBRARY_PATH - included following the user specified library paths.
  238. // and only supported on native toolchains.
  239. if (!TC.isCrossCompiling())
  240. addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
  241. }
  242. /// \brief Determine whether Objective-C automated reference counting is
  243. /// enabled.
  244. static bool isObjCAutoRefCount(const ArgList &Args) {
  245. return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
  246. }
  247. /// \brief Determine whether we are linking the ObjC runtime.
  248. static bool isObjCRuntimeLinked(const ArgList &Args) {
  249. if (isObjCAutoRefCount(Args)) {
  250. Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
  251. return true;
  252. }
  253. return Args.hasArg(options::OPT_fobjc_link_runtime);
  254. }
  255. static bool forwardToGCC(const Option &O) {
  256. // Don't forward inputs from the original command line. They are added from
  257. // InputInfoList.
  258. return O.getKind() != Option::InputClass &&
  259. !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
  260. }
  261. void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
  262. const Driver &D, const ArgList &Args,
  263. ArgStringList &CmdArgs,
  264. const InputInfo &Output,
  265. const InputInfoList &Inputs,
  266. const ToolChain *AuxToolChain) const {
  267. Arg *A;
  268. CheckPreprocessingOptions(D, Args);
  269. Args.AddLastArg(CmdArgs, options::OPT_C);
  270. Args.AddLastArg(CmdArgs, options::OPT_CC);
  271. // Handle dependency file generation.
  272. if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
  273. (A = Args.getLastArg(options::OPT_MD)) ||
  274. (A = Args.getLastArg(options::OPT_MMD))) {
  275. // Determine the output location.
  276. const char *DepFile;
  277. if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
  278. DepFile = MF->getValue();
  279. C.addFailureResultFile(DepFile, &JA);
  280. } else if (Output.getType() == types::TY_Dependencies) {
  281. DepFile = Output.getFilename();
  282. } else if (A->getOption().matches(options::OPT_M) ||
  283. A->getOption().matches(options::OPT_MM)) {
  284. DepFile = "-";
  285. } else {
  286. DepFile = getDependencyFileName(Args, Inputs);
  287. C.addFailureResultFile(DepFile, &JA);
  288. }
  289. CmdArgs.push_back("-dependency-file");
  290. CmdArgs.push_back(DepFile);
  291. // Add a default target if one wasn't specified.
  292. if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
  293. const char *DepTarget;
  294. // If user provided -o, that is the dependency target, except
  295. // when we are only generating a dependency file.
  296. Arg *OutputOpt = Args.getLastArg(options::OPT_o);
  297. if (OutputOpt && Output.getType() != types::TY_Dependencies) {
  298. DepTarget = OutputOpt->getValue();
  299. } else {
  300. // Otherwise derive from the base input.
  301. //
  302. // FIXME: This should use the computed output file location.
  303. SmallString<128> P(Inputs[0].getBaseInput());
  304. llvm::sys::path::replace_extension(P, "o");
  305. DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
  306. }
  307. CmdArgs.push_back("-MT");
  308. SmallString<128> Quoted;
  309. QuoteTarget(DepTarget, Quoted);
  310. CmdArgs.push_back(Args.MakeArgString(Quoted));
  311. }
  312. if (A->getOption().matches(options::OPT_M) ||
  313. A->getOption().matches(options::OPT_MD))
  314. CmdArgs.push_back("-sys-header-deps");
  315. if ((isa<PrecompileJobAction>(JA) &&
  316. !Args.hasArg(options::OPT_fno_module_file_deps)) ||
  317. Args.hasArg(options::OPT_fmodule_file_deps))
  318. CmdArgs.push_back("-module-file-deps");
  319. }
  320. if (Args.hasArg(options::OPT_MG)) {
  321. if (!A || A->getOption().matches(options::OPT_MD) ||
  322. A->getOption().matches(options::OPT_MMD))
  323. D.Diag(diag::err_drv_mg_requires_m_or_mm);
  324. CmdArgs.push_back("-MG");
  325. }
  326. Args.AddLastArg(CmdArgs, options::OPT_MP);
  327. Args.AddLastArg(CmdArgs, options::OPT_MV);
  328. // Convert all -MQ <target> args to -MT <quoted target>
  329. for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
  330. A->claim();
  331. if (A->getOption().matches(options::OPT_MQ)) {
  332. CmdArgs.push_back("-MT");
  333. SmallString<128> Quoted;
  334. QuoteTarget(A->getValue(), Quoted);
  335. CmdArgs.push_back(Args.MakeArgString(Quoted));
  336. // -MT flag - no change
  337. } else {
  338. A->render(Args, CmdArgs);
  339. }
  340. }
  341. // Add -i* options, and automatically translate to
  342. // -include-pch/-include-pth for transparent PCH support. It's
  343. // wonky, but we include looking for .gch so we can support seamless
  344. // replacement into a build system already set up to be generating
  345. // .gch files.
  346. int YcIndex = -1, YuIndex = -1;
  347. {
  348. int AI = -1;
  349. const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
  350. const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
  351. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  352. // Walk the whole i_Group and skip non "-include" flags so that the index
  353. // here matches the index in the next loop below.
  354. ++AI;
  355. if (!A->getOption().matches(options::OPT_include))
  356. continue;
  357. if (YcArg && strcmp(A->getValue(), YcArg->getValue()) == 0)
  358. YcIndex = AI;
  359. if (YuArg && strcmp(A->getValue(), YuArg->getValue()) == 0)
  360. YuIndex = AI;
  361. }
  362. }
  363. if (isa<PrecompileJobAction>(JA) && YcIndex != -1) {
  364. Driver::InputList Inputs;
  365. D.BuildInputs(getToolChain(), C.getArgs(), Inputs);
  366. assert(Inputs.size() == 1 && "Need one input when building pch");
  367. CmdArgs.push_back(Args.MakeArgString(Twine("-find-pch-source=") +
  368. Inputs[0].second->getValue()));
  369. }
  370. bool RenderedImplicitInclude = false;
  371. int AI = -1;
  372. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  373. ++AI;
  374. if (getToolChain().getDriver().IsCLMode() &&
  375. A->getOption().matches(options::OPT_include)) {
  376. // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
  377. // include is compiled into foo.h, and everything after goes into
  378. // the .obj file. /Yufoo.h means that all includes prior to and including
  379. // foo.h are completely skipped and replaced with a use of the pch file
  380. // for foo.h. (Each flag can have at most one value, multiple /Yc flags
  381. // just mean that the last one wins.) If /Yc and /Yu are both present
  382. // and refer to the same file, /Yc wins.
  383. // Note that OPT__SLASH_FI gets mapped to OPT_include.
  384. // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
  385. // cl.exe seems to support both flags with different values, but that
  386. // seems strange (which flag does /Fp now refer to?), so don't implement
  387. // that until someone needs it.
  388. int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
  389. if (PchIndex != -1) {
  390. if (isa<PrecompileJobAction>(JA)) {
  391. // When building the pch, skip all includes after the pch.
  392. assert(YcIndex != -1 && PchIndex == YcIndex);
  393. if (AI >= YcIndex)
  394. continue;
  395. } else {
  396. // When using the pch, skip all includes prior to the pch.
  397. if (AI < PchIndex) {
  398. A->claim();
  399. continue;
  400. }
  401. if (AI == PchIndex) {
  402. A->claim();
  403. CmdArgs.push_back("-include-pch");
  404. CmdArgs.push_back(
  405. Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
  406. continue;
  407. }
  408. }
  409. }
  410. } else if (A->getOption().matches(options::OPT_include)) {
  411. // Handling of gcc-style gch precompiled headers.
  412. bool IsFirstImplicitInclude = !RenderedImplicitInclude;
  413. RenderedImplicitInclude = true;
  414. // Use PCH if the user requested it.
  415. bool UsePCH = D.CCCUsePCH;
  416. bool FoundPTH = false;
  417. bool FoundPCH = false;
  418. SmallString<128> P(A->getValue());
  419. // We want the files to have a name like foo.h.pch. Add a dummy extension
  420. // so that replace_extension does the right thing.
  421. P += ".dummy";
  422. if (UsePCH) {
  423. llvm::sys::path::replace_extension(P, "pch");
  424. if (llvm::sys::fs::exists(P))
  425. FoundPCH = true;
  426. }
  427. if (!FoundPCH) {
  428. llvm::sys::path::replace_extension(P, "pth");
  429. if (llvm::sys::fs::exists(P))
  430. FoundPTH = true;
  431. }
  432. if (!FoundPCH && !FoundPTH) {
  433. llvm::sys::path::replace_extension(P, "gch");
  434. if (llvm::sys::fs::exists(P)) {
  435. FoundPCH = UsePCH;
  436. FoundPTH = !UsePCH;
  437. }
  438. }
  439. if (FoundPCH || FoundPTH) {
  440. if (IsFirstImplicitInclude) {
  441. A->claim();
  442. if (UsePCH)
  443. CmdArgs.push_back("-include-pch");
  444. else
  445. CmdArgs.push_back("-include-pth");
  446. CmdArgs.push_back(Args.MakeArgString(P));
  447. continue;
  448. } else {
  449. // Ignore the PCH if not first on command line and emit warning.
  450. D.Diag(diag::warn_drv_pch_not_first_include) << P
  451. << A->getAsString(Args);
  452. }
  453. }
  454. }
  455. // Not translated, render as usual.
  456. A->claim();
  457. A->render(Args, CmdArgs);
  458. }
  459. Args.AddAllArgs(CmdArgs,
  460. {options::OPT_D, options::OPT_U, options::OPT_I_Group,
  461. options::OPT_F, options::OPT_index_header_map});
  462. // Add -Wp, and -Xpreprocessor if using the preprocessor.
  463. // FIXME: There is a very unfortunate problem here, some troubled
  464. // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
  465. // really support that we would have to parse and then translate
  466. // those options. :(
  467. Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
  468. options::OPT_Xpreprocessor);
  469. // -I- is a deprecated GCC feature, reject it.
  470. if (Arg *A = Args.getLastArg(options::OPT_I_))
  471. D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
  472. // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
  473. // -isysroot to the CC1 invocation.
  474. StringRef sysroot = C.getSysRoot();
  475. if (sysroot != "") {
  476. if (!Args.hasArg(options::OPT_isysroot)) {
  477. CmdArgs.push_back("-isysroot");
  478. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  479. }
  480. }
  481. // Parse additional include paths from environment variables.
  482. // FIXME: We should probably sink the logic for handling these from the
  483. // frontend into the driver. It will allow deleting 4 otherwise unused flags.
  484. // CPATH - included following the user specified includes (but prior to
  485. // builtin and standard includes).
  486. addDirectoryList(Args, CmdArgs, "-I", "CPATH");
  487. // C_INCLUDE_PATH - system includes enabled when compiling C.
  488. addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
  489. // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
  490. addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
  491. // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
  492. addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
  493. // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
  494. addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
  495. // Optional AuxToolChain indicates that we need to include headers
  496. // for more than one target. If that's the case, add include paths
  497. // from AuxToolChain right after include paths of the same kind for
  498. // the current target.
  499. // Add C++ include arguments, if needed.
  500. if (types::isCXX(Inputs[0].getType())) {
  501. getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  502. if (AuxToolChain)
  503. AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  504. }
  505. // Add system include arguments.
  506. getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
  507. if (AuxToolChain)
  508. AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  509. // Add CUDA include arguments, if needed.
  510. if (types::isCuda(Inputs[0].getType()))
  511. getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
  512. }
  513. // FIXME: Move to target hook.
  514. static bool isSignedCharDefault(const llvm::Triple &Triple) {
  515. switch (Triple.getArch()) {
  516. default:
  517. return true;
  518. case llvm::Triple::aarch64:
  519. case llvm::Triple::aarch64_be:
  520. case llvm::Triple::arm:
  521. case llvm::Triple::armeb:
  522. case llvm::Triple::thumb:
  523. case llvm::Triple::thumbeb:
  524. if (Triple.isOSDarwin() || Triple.isOSWindows())
  525. return true;
  526. return false;
  527. case llvm::Triple::ppc:
  528. case llvm::Triple::ppc64:
  529. if (Triple.isOSDarwin())
  530. return true;
  531. return false;
  532. case llvm::Triple::hexagon:
  533. case llvm::Triple::ppc64le:
  534. case llvm::Triple::systemz:
  535. case llvm::Triple::xcore:
  536. return false;
  537. }
  538. }
  539. static bool isNoCommonDefault(const llvm::Triple &Triple) {
  540. switch (Triple.getArch()) {
  541. default:
  542. return false;
  543. case llvm::Triple::xcore:
  544. case llvm::Triple::wasm32:
  545. case llvm::Triple::wasm64:
  546. return true;
  547. }
  548. }
  549. // ARM tools start.
  550. // Get SubArch (vN).
  551. static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
  552. llvm::StringRef Arch = Triple.getArchName();
  553. return llvm::ARM::parseArchVersion(Arch);
  554. }
  555. // True if M-profile.
  556. static bool isARMMProfile(const llvm::Triple &Triple) {
  557. llvm::StringRef Arch = Triple.getArchName();
  558. unsigned Profile = llvm::ARM::parseArchProfile(Arch);
  559. return Profile == llvm::ARM::PK_M;
  560. }
  561. // Get Arch/CPU from args.
  562. static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
  563. llvm::StringRef &CPU, bool FromAs = false) {
  564. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  565. CPU = A->getValue();
  566. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  567. Arch = A->getValue();
  568. if (!FromAs)
  569. return;
  570. for (const Arg *A :
  571. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  572. StringRef Value = A->getValue();
  573. if (Value.startswith("-mcpu="))
  574. CPU = Value.substr(6);
  575. if (Value.startswith("-march="))
  576. Arch = Value.substr(7);
  577. }
  578. }
  579. // Handle -mhwdiv=.
  580. // FIXME: Use ARMTargetParser.
  581. static void getARMHWDivFeatures(const Driver &D, const Arg *A,
  582. const ArgList &Args, StringRef HWDiv,
  583. std::vector<const char *> &Features) {
  584. unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
  585. if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
  586. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  587. }
  588. // Handle -mfpu=.
  589. static void getARMFPUFeatures(const Driver &D, const Arg *A,
  590. const ArgList &Args, StringRef FPU,
  591. std::vector<const char *> &Features) {
  592. unsigned FPUID = llvm::ARM::parseFPU(FPU);
  593. if (!llvm::ARM::getFPUFeatures(FPUID, Features))
  594. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  595. }
  596. // Decode ARM features from string like +[no]featureA+[no]featureB+...
  597. static bool DecodeARMFeatures(const Driver &D, StringRef text,
  598. std::vector<const char *> &Features) {
  599. SmallVector<StringRef, 8> Split;
  600. text.split(Split, StringRef("+"), -1, false);
  601. for (StringRef Feature : Split) {
  602. const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
  603. if (FeatureName)
  604. Features.push_back(FeatureName);
  605. else
  606. return false;
  607. }
  608. return true;
  609. }
  610. // Check if -march is valid by checking if it can be canonicalised and parsed.
  611. // getARMArch is used here instead of just checking the -march value in order
  612. // to handle -march=native correctly.
  613. static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
  614. llvm::StringRef ArchName,
  615. std::vector<const char *> &Features,
  616. const llvm::Triple &Triple) {
  617. std::pair<StringRef, StringRef> Split = ArchName.split("+");
  618. std::string MArch = arm::getARMArch(ArchName, Triple);
  619. if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
  620. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  621. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  622. }
  623. // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
  624. static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
  625. llvm::StringRef CPUName, llvm::StringRef ArchName,
  626. std::vector<const char *> &Features,
  627. const llvm::Triple &Triple) {
  628. std::pair<StringRef, StringRef> Split = CPUName.split("+");
  629. std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
  630. if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
  631. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  632. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  633. }
  634. static bool useAAPCSForMachO(const llvm::Triple &T) {
  635. // The backend is hardwired to assume AAPCS for M-class processors, ensure
  636. // the frontend matches that.
  637. return T.getEnvironment() == llvm::Triple::EABI ||
  638. T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
  639. }
  640. // Select the float ABI as determined by -msoft-float, -mhard-float, and
  641. // -mfloat-abi=.
  642. arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
  643. const Driver &D = TC.getDriver();
  644. const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
  645. auto SubArch = getARMSubArchVersionNumber(Triple);
  646. arm::FloatABI ABI = FloatABI::Invalid;
  647. if (Arg *A =
  648. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  649. options::OPT_mfloat_abi_EQ)) {
  650. if (A->getOption().matches(options::OPT_msoft_float)) {
  651. ABI = FloatABI::Soft;
  652. } else if (A->getOption().matches(options::OPT_mhard_float)) {
  653. ABI = FloatABI::Hard;
  654. } else {
  655. ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
  656. .Case("soft", FloatABI::Soft)
  657. .Case("softfp", FloatABI::SoftFP)
  658. .Case("hard", FloatABI::Hard)
  659. .Default(FloatABI::Invalid);
  660. if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  661. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  662. ABI = FloatABI::Soft;
  663. }
  664. }
  665. // It is incorrect to select hard float ABI on MachO platforms if the ABI is
  666. // "apcs-gnu".
  667. if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
  668. ABI == FloatABI::Hard) {
  669. D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
  670. << Triple.getArchName();
  671. }
  672. }
  673. // If unspecified, choose the default based on the platform.
  674. if (ABI == FloatABI::Invalid) {
  675. switch (Triple.getOS()) {
  676. case llvm::Triple::Darwin:
  677. case llvm::Triple::MacOSX:
  678. case llvm::Triple::IOS:
  679. case llvm::Triple::TvOS: {
  680. // Darwin defaults to "softfp" for v6 and v7.
  681. ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  682. ABI = Triple.isWatchABI() ? FloatABI::Hard : ABI;
  683. break;
  684. }
  685. case llvm::Triple::WatchOS:
  686. ABI = FloatABI::Hard;
  687. break;
  688. // FIXME: this is invalid for WindowsCE
  689. case llvm::Triple::Win32:
  690. ABI = FloatABI::Hard;
  691. break;
  692. case llvm::Triple::FreeBSD:
  693. switch (Triple.getEnvironment()) {
  694. case llvm::Triple::GNUEABIHF:
  695. ABI = FloatABI::Hard;
  696. break;
  697. default:
  698. // FreeBSD defaults to soft float
  699. ABI = FloatABI::Soft;
  700. break;
  701. }
  702. break;
  703. default:
  704. switch (Triple.getEnvironment()) {
  705. case llvm::Triple::GNUEABIHF:
  706. case llvm::Triple::EABIHF:
  707. ABI = FloatABI::Hard;
  708. break;
  709. case llvm::Triple::GNUEABI:
  710. case llvm::Triple::EABI:
  711. // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
  712. ABI = FloatABI::SoftFP;
  713. break;
  714. case llvm::Triple::Android:
  715. ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  716. break;
  717. default:
  718. // Assume "soft", but warn the user we are guessing.
  719. if (Triple.isOSBinFormatMachO() &&
  720. Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
  721. ABI = FloatABI::Hard;
  722. else
  723. ABI = FloatABI::Soft;
  724. if (Triple.getOS() != llvm::Triple::UnknownOS ||
  725. !Triple.isOSBinFormatMachO())
  726. D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
  727. break;
  728. }
  729. }
  730. }
  731. assert(ABI != FloatABI::Invalid && "must select an ABI");
  732. return ABI;
  733. }
  734. static void getARMTargetFeatures(const ToolChain &TC,
  735. const llvm::Triple &Triple,
  736. const ArgList &Args,
  737. std::vector<const char *> &Features,
  738. bool ForAS) {
  739. const Driver &D = TC.getDriver();
  740. bool KernelOrKext =
  741. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  742. arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
  743. const Arg *WaCPU = nullptr, *WaFPU = nullptr;
  744. const Arg *WaHDiv = nullptr, *WaArch = nullptr;
  745. if (!ForAS) {
  746. // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
  747. // yet (it uses the -mfloat-abi and -msoft-float options), and it is
  748. // stripped out by the ARM target. We should probably pass this a new
  749. // -target-option, which is handled by the -cc1/-cc1as invocation.
  750. //
  751. // FIXME2: For consistency, it would be ideal if we set up the target
  752. // machine state the same when using the frontend or the assembler. We don't
  753. // currently do that for the assembler, we pass the options directly to the
  754. // backend and never even instantiate the frontend TargetInfo. If we did,
  755. // and used its handleTargetFeatures hook, then we could ensure the
  756. // assembler and the frontend behave the same.
  757. // Use software floating point operations?
  758. if (ABI == arm::FloatABI::Soft)
  759. Features.push_back("+soft-float");
  760. // Use software floating point argument passing?
  761. if (ABI != arm::FloatABI::Hard)
  762. Features.push_back("+soft-float-abi");
  763. } else {
  764. // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
  765. // to the assembler correctly.
  766. for (const Arg *A :
  767. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  768. StringRef Value = A->getValue();
  769. if (Value.startswith("-mfpu=")) {
  770. WaFPU = A;
  771. } else if (Value.startswith("-mcpu=")) {
  772. WaCPU = A;
  773. } else if (Value.startswith("-mhwdiv=")) {
  774. WaHDiv = A;
  775. } else if (Value.startswith("-march=")) {
  776. WaArch = A;
  777. }
  778. }
  779. }
  780. // Check -march. ClangAs gives preference to -Wa,-march=.
  781. const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
  782. StringRef ArchName;
  783. if (WaArch) {
  784. if (ArchArg)
  785. D.Diag(clang::diag::warn_drv_unused_argument)
  786. << ArchArg->getAsString(Args);
  787. ArchName = StringRef(WaArch->getValue()).substr(7);
  788. checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
  789. // FIXME: Set Arch.
  790. D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
  791. } else if (ArchArg) {
  792. ArchName = ArchArg->getValue();
  793. checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
  794. }
  795. // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
  796. const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  797. StringRef CPUName;
  798. if (WaCPU) {
  799. if (CPUArg)
  800. D.Diag(clang::diag::warn_drv_unused_argument)
  801. << CPUArg->getAsString(Args);
  802. CPUName = StringRef(WaCPU->getValue()).substr(6);
  803. checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
  804. } else if (CPUArg) {
  805. CPUName = CPUArg->getValue();
  806. checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
  807. }
  808. // Add CPU features for generic CPUs
  809. if (CPUName == "native") {
  810. llvm::StringMap<bool> HostFeatures;
  811. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  812. for (auto &F : HostFeatures)
  813. Features.push_back(
  814. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  815. }
  816. // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
  817. const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
  818. if (WaFPU) {
  819. if (FPUArg)
  820. D.Diag(clang::diag::warn_drv_unused_argument)
  821. << FPUArg->getAsString(Args);
  822. getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
  823. Features);
  824. } else if (FPUArg) {
  825. getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
  826. }
  827. // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
  828. const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
  829. if (WaHDiv) {
  830. if (HDivArg)
  831. D.Diag(clang::diag::warn_drv_unused_argument)
  832. << HDivArg->getAsString(Args);
  833. getARMHWDivFeatures(D, WaHDiv, Args,
  834. StringRef(WaHDiv->getValue()).substr(8), Features);
  835. } else if (HDivArg)
  836. getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
  837. // Setting -msoft-float effectively disables NEON because of the GCC
  838. // implementation, although the same isn't true of VFP or VFP3.
  839. if (ABI == arm::FloatABI::Soft) {
  840. Features.push_back("-neon");
  841. // Also need to explicitly disable features which imply NEON.
  842. Features.push_back("-crypto");
  843. }
  844. // En/disable crc code generation.
  845. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  846. if (A->getOption().matches(options::OPT_mcrc))
  847. Features.push_back("+crc");
  848. else
  849. Features.push_back("-crc");
  850. }
  851. // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
  852. // neither options are specified, see if we are compiling for kernel/kext and
  853. // decide whether to pass "+long-calls" based on the OS and its version.
  854. if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
  855. options::OPT_mno_long_calls)) {
  856. if (A->getOption().matches(options::OPT_mlong_calls))
  857. Features.push_back("+long-calls");
  858. } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  859. !Triple.isWatchOS()) {
  860. Features.push_back("+long-calls");
  861. }
  862. // Kernel code has more strict alignment requirements.
  863. if (KernelOrKext)
  864. Features.push_back("+strict-align");
  865. else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  866. options::OPT_munaligned_access)) {
  867. if (A->getOption().matches(options::OPT_munaligned_access)) {
  868. // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
  869. if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  870. D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
  871. // v8M Baseline follows on from v6M, so doesn't support unaligned memory
  872. // access either.
  873. else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
  874. D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";
  875. } else
  876. Features.push_back("+strict-align");
  877. } else {
  878. // Assume pre-ARMv6 doesn't support unaligned accesses.
  879. //
  880. // ARMv6 may or may not support unaligned accesses depending on the
  881. // SCTLR.U bit, which is architecture-specific. We assume ARMv6
  882. // Darwin and NetBSD targets support unaligned accesses, and others don't.
  883. //
  884. // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
  885. // which raises an alignment fault on unaligned accesses. Linux
  886. // defaults this bit to 0 and handles it as a system-wide (not
  887. // per-process) setting. It is therefore safe to assume that ARMv7+
  888. // Linux targets support unaligned accesses. The same goes for NaCl.
  889. //
  890. // The above behavior is consistent with GCC.
  891. int VersionNum = getARMSubArchVersionNumber(Triple);
  892. if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
  893. if (VersionNum < 6 ||
  894. Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  895. Features.push_back("+strict-align");
  896. } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
  897. if (VersionNum < 7)
  898. Features.push_back("+strict-align");
  899. } else
  900. Features.push_back("+strict-align");
  901. }
  902. // llvm does not support reserving registers in general. There is support
  903. // for reserving r9 on ARM though (defined as a platform-specific register
  904. // in ARM EABI).
  905. if (Args.hasArg(options::OPT_ffixed_r9))
  906. Features.push_back("+reserve-r9");
  907. // The kext linker doesn't know how to deal with movw/movt.
  908. if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
  909. Features.push_back("+no-movt");
  910. }
  911. void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
  912. ArgStringList &CmdArgs, bool KernelOrKext) const {
  913. // Select the ABI to use.
  914. // FIXME: Support -meabi.
  915. // FIXME: Parts of this are duplicated in the backend, unify this somehow.
  916. const char *ABIName = nullptr;
  917. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  918. ABIName = A->getValue();
  919. } else if (Triple.isOSBinFormatMachO()) {
  920. if (useAAPCSForMachO(Triple)) {
  921. ABIName = "aapcs";
  922. } else if (Triple.isWatchABI()) {
  923. ABIName = "aapcs16";
  924. } else {
  925. ABIName = "apcs-gnu";
  926. }
  927. } else if (Triple.isOSWindows()) {
  928. // FIXME: this is invalid for WindowsCE
  929. ABIName = "aapcs";
  930. } else {
  931. // Select the default based on the platform.
  932. switch (Triple.getEnvironment()) {
  933. case llvm::Triple::Android:
  934. case llvm::Triple::GNUEABI:
  935. case llvm::Triple::GNUEABIHF:
  936. ABIName = "aapcs-linux";
  937. break;
  938. case llvm::Triple::EABIHF:
  939. case llvm::Triple::EABI:
  940. ABIName = "aapcs";
  941. break;
  942. default:
  943. if (Triple.getOS() == llvm::Triple::NetBSD)
  944. ABIName = "apcs-gnu";
  945. else
  946. ABIName = "aapcs";
  947. break;
  948. }
  949. }
  950. CmdArgs.push_back("-target-abi");
  951. CmdArgs.push_back(ABIName);
  952. // Determine floating point ABI from the options & target defaults.
  953. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  954. if (ABI == arm::FloatABI::Soft) {
  955. // Floating point operations and argument passing are soft.
  956. // FIXME: This changes CPP defines, we need -target-soft-float.
  957. CmdArgs.push_back("-msoft-float");
  958. CmdArgs.push_back("-mfloat-abi");
  959. CmdArgs.push_back("soft");
  960. } else if (ABI == arm::FloatABI::SoftFP) {
  961. // Floating point operations are hard, but argument passing is soft.
  962. CmdArgs.push_back("-mfloat-abi");
  963. CmdArgs.push_back("soft");
  964. } else {
  965. // Floating point operations and argument passing are hard.
  966. assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
  967. CmdArgs.push_back("-mfloat-abi");
  968. CmdArgs.push_back("hard");
  969. }
  970. // Forward the -mglobal-merge option for explicit control over the pass.
  971. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  972. options::OPT_mno_global_merge)) {
  973. CmdArgs.push_back("-backend-option");
  974. if (A->getOption().matches(options::OPT_mno_global_merge))
  975. CmdArgs.push_back("-arm-global-merge=false");
  976. else
  977. CmdArgs.push_back("-arm-global-merge=true");
  978. }
  979. if (!Args.hasFlag(options::OPT_mimplicit_float,
  980. options::OPT_mno_implicit_float, true))
  981. CmdArgs.push_back("-no-implicit-float");
  982. }
  983. // ARM tools end.
  984. /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
  985. /// targeting.
  986. static std::string getAArch64TargetCPU(const ArgList &Args) {
  987. Arg *A;
  988. std::string CPU;
  989. // If we have -mtune or -mcpu, use that.
  990. if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
  991. CPU = StringRef(A->getValue()).lower();
  992. } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
  993. StringRef Mcpu = A->getValue();
  994. CPU = Mcpu.split("+").first.lower();
  995. }
  996. // Handle CPU name is 'native'.
  997. if (CPU == "native")
  998. return llvm::sys::getHostCPUName();
  999. else if (CPU.size())
  1000. return CPU;
  1001. // Make sure we pick "cyclone" if -arch is used.
  1002. // FIXME: Should this be picked by checking the target triple instead?
  1003. if (Args.getLastArg(options::OPT_arch))
  1004. return "cyclone";
  1005. return "generic";
  1006. }
  1007. void Clang::AddAArch64TargetArgs(const ArgList &Args,
  1008. ArgStringList &CmdArgs) const {
  1009. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  1010. llvm::Triple Triple(TripleStr);
  1011. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1012. Args.hasArg(options::OPT_mkernel) ||
  1013. Args.hasArg(options::OPT_fapple_kext))
  1014. CmdArgs.push_back("-disable-red-zone");
  1015. if (!Args.hasFlag(options::OPT_mimplicit_float,
  1016. options::OPT_mno_implicit_float, true))
  1017. CmdArgs.push_back("-no-implicit-float");
  1018. const char *ABIName = nullptr;
  1019. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1020. ABIName = A->getValue();
  1021. else if (Triple.isOSDarwin())
  1022. ABIName = "darwinpcs";
  1023. else
  1024. ABIName = "aapcs";
  1025. CmdArgs.push_back("-target-abi");
  1026. CmdArgs.push_back(ABIName);
  1027. if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
  1028. options::OPT_mno_fix_cortex_a53_835769)) {
  1029. CmdArgs.push_back("-backend-option");
  1030. if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
  1031. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  1032. else
  1033. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
  1034. } else if (Triple.isAndroid()) {
  1035. // Enabled A53 errata (835769) workaround by default on android
  1036. CmdArgs.push_back("-backend-option");
  1037. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  1038. }
  1039. // Forward the -mglobal-merge option for explicit control over the pass.
  1040. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  1041. options::OPT_mno_global_merge)) {
  1042. CmdArgs.push_back("-backend-option");
  1043. if (A->getOption().matches(options::OPT_mno_global_merge))
  1044. CmdArgs.push_back("-aarch64-global-merge=false");
  1045. else
  1046. CmdArgs.push_back("-aarch64-global-merge=true");
  1047. }
  1048. }
  1049. // Get CPU and ABI names. They are not independent
  1050. // so we have to calculate them together.
  1051. void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
  1052. StringRef &CPUName, StringRef &ABIName) {
  1053. const char *DefMips32CPU = "mips32r2";
  1054. const char *DefMips64CPU = "mips64r2";
  1055. // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
  1056. // default for mips64(el)?-img-linux-gnu.
  1057. if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
  1058. Triple.getEnvironment() == llvm::Triple::GNU) {
  1059. DefMips32CPU = "mips32r6";
  1060. DefMips64CPU = "mips64r6";
  1061. }
  1062. // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
  1063. if (Triple.isAndroid())
  1064. DefMips64CPU = "mips64r6";
  1065. // MIPS3 is the default for mips64*-unknown-openbsd.
  1066. if (Triple.getOS() == llvm::Triple::OpenBSD)
  1067. DefMips64CPU = "mips3";
  1068. if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
  1069. CPUName = A->getValue();
  1070. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  1071. ABIName = A->getValue();
  1072. // Convert a GNU style Mips ABI name to the name
  1073. // accepted by LLVM Mips backend.
  1074. ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
  1075. .Case("32", "o32")
  1076. .Case("64", "n64")
  1077. .Default(ABIName);
  1078. }
  1079. // Setup default CPU and ABI names.
  1080. if (CPUName.empty() && ABIName.empty()) {
  1081. switch (Triple.getArch()) {
  1082. default:
  1083. llvm_unreachable("Unexpected triple arch name");
  1084. case llvm::Triple::mips:
  1085. case llvm::Triple::mipsel:
  1086. CPUName = DefMips32CPU;
  1087. break;
  1088. case llvm::Triple::mips64:
  1089. case llvm::Triple::mips64el:
  1090. CPUName = DefMips64CPU;
  1091. break;
  1092. }
  1093. }
  1094. if (ABIName.empty()) {
  1095. // Deduce ABI name from the target triple.
  1096. if (Triple.getArch() == llvm::Triple::mips ||
  1097. Triple.getArch() == llvm::Triple::mipsel)
  1098. ABIName = "o32";
  1099. else
  1100. ABIName = "n64";
  1101. }
  1102. if (CPUName.empty()) {
  1103. // Deduce CPU name from ABI name.
  1104. CPUName = llvm::StringSwitch<const char *>(ABIName)
  1105. .Cases("o32", "eabi", DefMips32CPU)
  1106. .Cases("n32", "n64", DefMips64CPU)
  1107. .Default("");
  1108. }
  1109. // FIXME: Warn on inconsistent use of -march and -mabi.
  1110. }
  1111. std::string mips::getMipsABILibSuffix(const ArgList &Args,
  1112. const llvm::Triple &Triple) {
  1113. StringRef CPUName, ABIName;
  1114. tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1115. return llvm::StringSwitch<std::string>(ABIName)
  1116. .Case("o32", "")
  1117. .Case("n32", "32")
  1118. .Case("n64", "64");
  1119. }
  1120. // Convert ABI name to the GNU tools acceptable variant.
  1121. static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
  1122. return llvm::StringSwitch<llvm::StringRef>(ABI)
  1123. .Case("o32", "32")
  1124. .Case("n64", "64")
  1125. .Default(ABI);
  1126. }
  1127. // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
  1128. // and -mfloat-abi=.
  1129. static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
  1130. mips::FloatABI ABI = mips::FloatABI::Invalid;
  1131. if (Arg *A =
  1132. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1133. options::OPT_mfloat_abi_EQ)) {
  1134. if (A->getOption().matches(options::OPT_msoft_float))
  1135. ABI = mips::FloatABI::Soft;
  1136. else if (A->getOption().matches(options::OPT_mhard_float))
  1137. ABI = mips::FloatABI::Hard;
  1138. else {
  1139. ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
  1140. .Case("soft", mips::FloatABI::Soft)
  1141. .Case("hard", mips::FloatABI::Hard)
  1142. .Default(mips::FloatABI::Invalid);
  1143. if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1144. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1145. ABI = mips::FloatABI::Hard;
  1146. }
  1147. }
  1148. }
  1149. // If unspecified, choose the default based on the platform.
  1150. if (ABI == mips::FloatABI::Invalid) {
  1151. // Assume "hard", because it's a default value used by gcc.
  1152. // When we start to recognize specific target MIPS processors,
  1153. // we will be able to select the default more correctly.
  1154. ABI = mips::FloatABI::Hard;
  1155. }
  1156. assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
  1157. return ABI;
  1158. }
  1159. static void AddTargetFeature(const ArgList &Args,
  1160. std::vector<const char *> &Features,
  1161. OptSpecifier OnOpt, OptSpecifier OffOpt,
  1162. StringRef FeatureName) {
  1163. if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
  1164. if (A->getOption().matches(OnOpt))
  1165. Features.push_back(Args.MakeArgString("+" + FeatureName));
  1166. else
  1167. Features.push_back(Args.MakeArgString("-" + FeatureName));
  1168. }
  1169. }
  1170. static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1171. const ArgList &Args,
  1172. std::vector<const char *> &Features) {
  1173. StringRef CPUName;
  1174. StringRef ABIName;
  1175. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1176. ABIName = getGnuCompatibleMipsABIName(ABIName);
  1177. AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
  1178. options::OPT_mabicalls, "noabicalls");
  1179. mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
  1180. if (FloatABI == mips::FloatABI::Soft) {
  1181. // FIXME: Note, this is a hack. We need to pass the selected float
  1182. // mode to the MipsTargetInfoBase to define appropriate macros there.
  1183. // Now it is the only method.
  1184. Features.push_back("+soft-float");
  1185. }
  1186. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  1187. StringRef Val = StringRef(A->getValue());
  1188. if (Val == "2008") {
  1189. if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
  1190. Features.push_back("+nan2008");
  1191. else {
  1192. Features.push_back("-nan2008");
  1193. D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
  1194. }
  1195. } else if (Val == "legacy") {
  1196. if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
  1197. Features.push_back("-nan2008");
  1198. else {
  1199. Features.push_back("+nan2008");
  1200. D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
  1201. }
  1202. } else
  1203. D.Diag(diag::err_drv_unsupported_option_argument)
  1204. << A->getOption().getName() << Val;
  1205. }
  1206. AddTargetFeature(Args, Features, options::OPT_msingle_float,
  1207. options::OPT_mdouble_float, "single-float");
  1208. AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
  1209. "mips16");
  1210. AddTargetFeature(Args, Features, options::OPT_mmicromips,
  1211. options::OPT_mno_micromips, "micromips");
  1212. AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
  1213. "dsp");
  1214. AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
  1215. "dspr2");
  1216. AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
  1217. "msa");
  1218. // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
  1219. // pass -mfpxx
  1220. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  1221. options::OPT_mfp64)) {
  1222. if (A->getOption().matches(options::OPT_mfp32))
  1223. Features.push_back(Args.MakeArgString("-fp64"));
  1224. else if (A->getOption().matches(options::OPT_mfpxx)) {
  1225. Features.push_back(Args.MakeArgString("+fpxx"));
  1226. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1227. } else
  1228. Features.push_back(Args.MakeArgString("+fp64"));
  1229. } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
  1230. Features.push_back(Args.MakeArgString("+fpxx"));
  1231. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1232. }
  1233. AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
  1234. options::OPT_modd_spreg, "nooddspreg");
  1235. }
  1236. void Clang::AddMIPSTargetArgs(const ArgList &Args,
  1237. ArgStringList &CmdArgs) const {
  1238. const Driver &D = getToolChain().getDriver();
  1239. StringRef CPUName;
  1240. StringRef ABIName;
  1241. const llvm::Triple &Triple = getToolChain().getTriple();
  1242. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1243. CmdArgs.push_back("-target-abi");
  1244. CmdArgs.push_back(ABIName.data());
  1245. mips::FloatABI ABI = getMipsFloatABI(D, Args);
  1246. if (ABI == mips::FloatABI::Soft) {
  1247. // Floating point operations and argument passing are soft.
  1248. CmdArgs.push_back("-msoft-float");
  1249. CmdArgs.push_back("-mfloat-abi");
  1250. CmdArgs.push_back("soft");
  1251. } else {
  1252. // Floating point operations and argument passing are hard.
  1253. assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
  1254. CmdArgs.push_back("-mfloat-abi");
  1255. CmdArgs.push_back("hard");
  1256. }
  1257. if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
  1258. if (A->getOption().matches(options::OPT_mxgot)) {
  1259. CmdArgs.push_back("-mllvm");
  1260. CmdArgs.push_back("-mxgot");
  1261. }
  1262. }
  1263. if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
  1264. options::OPT_mno_ldc1_sdc1)) {
  1265. if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
  1266. CmdArgs.push_back("-mllvm");
  1267. CmdArgs.push_back("-mno-ldc1-sdc1");
  1268. }
  1269. }
  1270. if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
  1271. options::OPT_mno_check_zero_division)) {
  1272. if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
  1273. CmdArgs.push_back("-mllvm");
  1274. CmdArgs.push_back("-mno-check-zero-division");
  1275. }
  1276. }
  1277. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  1278. StringRef v = A->getValue();
  1279. CmdArgs.push_back("-mllvm");
  1280. CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
  1281. A->claim();
  1282. }
  1283. }
  1284. /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
  1285. static std::string getPPCTargetCPU(const ArgList &Args) {
  1286. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1287. StringRef CPUName = A->getValue();
  1288. if (CPUName == "native") {
  1289. std::string CPU = llvm::sys::getHostCPUName();
  1290. if (!CPU.empty() && CPU != "generic")
  1291. return CPU;
  1292. else
  1293. return "";
  1294. }
  1295. return llvm::StringSwitch<const char *>(CPUName)
  1296. .Case("common", "generic")
  1297. .Case("440", "440")
  1298. .Case("440fp", "440")
  1299. .Case("450", "450")
  1300. .Case("601", "601")
  1301. .Case("602", "602")
  1302. .Case("603", "603")
  1303. .Case("603e", "603e")
  1304. .Case("603ev", "603ev")
  1305. .Case("604", "604")
  1306. .Case("604e", "604e")
  1307. .Case("620", "620")
  1308. .Case("630", "pwr3")
  1309. .Case("G3", "g3")
  1310. .Case("7400", "7400")
  1311. .Case("G4", "g4")
  1312. .Case("7450", "7450")
  1313. .Case("G4+", "g4+")
  1314. .Case("750", "750")
  1315. .Case("970", "970")
  1316. .Case("G5", "g5")
  1317. .Case("a2", "a2")
  1318. .Case("a2q", "a2q")
  1319. .Case("e500mc", "e500mc")
  1320. .Case("e5500", "e5500")
  1321. .Case("power3", "pwr3")
  1322. .Case("power4", "pwr4")
  1323. .Case("power5", "pwr5")
  1324. .Case("power5x", "pwr5x")
  1325. .Case("power6", "pwr6")
  1326. .Case("power6x", "pwr6x")
  1327. .Case("power7", "pwr7")
  1328. .Case("power8", "pwr8")
  1329. .Case("pwr3", "pwr3")
  1330. .Case("pwr4", "pwr4")
  1331. .Case("pwr5", "pwr5")
  1332. .Case("pwr5x", "pwr5x")
  1333. .Case("pwr6", "pwr6")
  1334. .Case("pwr6x", "pwr6x")
  1335. .Case("pwr7", "pwr7")
  1336. .Case("pwr8", "pwr8")
  1337. .Case("powerpc", "ppc")
  1338. .Case("powerpc64", "ppc64")
  1339. .Case("powerpc64le", "ppc64le")
  1340. .Default("");
  1341. }
  1342. return "";
  1343. }
  1344. static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1345. const ArgList &Args,
  1346. std::vector<const char *> &Features) {
  1347. handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
  1348. ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
  1349. if (FloatABI == ppc::FloatABI::Soft &&
  1350. !(Triple.getArch() == llvm::Triple::ppc64 ||
  1351. Triple.getArch() == llvm::Triple::ppc64le))
  1352. Features.push_back("+soft-float");
  1353. else if (FloatABI == ppc::FloatABI::Soft &&
  1354. (Triple.getArch() == llvm::Triple::ppc64 ||
  1355. Triple.getArch() == llvm::Triple::ppc64le))
  1356. D.Diag(diag::err_drv_invalid_mfloat_abi)
  1357. << "soft float is not supported for ppc64";
  1358. // Altivec is a bit weird, allow overriding of the Altivec feature here.
  1359. AddTargetFeature(Args, Features, options::OPT_faltivec,
  1360. options::OPT_fno_altivec, "altivec");
  1361. }
  1362. ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
  1363. ppc::FloatABI ABI = ppc::FloatABI::Invalid;
  1364. if (Arg *A =
  1365. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1366. options::OPT_mfloat_abi_EQ)) {
  1367. if (A->getOption().matches(options::OPT_msoft_float))
  1368. ABI = ppc::FloatABI::Soft;
  1369. else if (A->getOption().matches(options::OPT_mhard_float))
  1370. ABI = ppc::FloatABI::Hard;
  1371. else {
  1372. ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
  1373. .Case("soft", ppc::FloatABI::Soft)
  1374. .Case("hard", ppc::FloatABI::Hard)
  1375. .Default(ppc::FloatABI::Invalid);
  1376. if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1377. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1378. ABI = ppc::FloatABI::Hard;
  1379. }
  1380. }
  1381. }
  1382. // If unspecified, choose the default based on the platform.
  1383. if (ABI == ppc::FloatABI::Invalid) {
  1384. ABI = ppc::FloatABI::Hard;
  1385. }
  1386. return ABI;
  1387. }
  1388. void Clang::AddPPCTargetArgs(const ArgList &Args,
  1389. ArgStringList &CmdArgs) const {
  1390. // Select the ABI to use.
  1391. const char *ABIName = nullptr;
  1392. if (getToolChain().getTriple().isOSLinux())
  1393. switch (getToolChain().getArch()) {
  1394. case llvm::Triple::ppc64: {
  1395. // When targeting a processor that supports QPX, or if QPX is
  1396. // specifically enabled, default to using the ABI that supports QPX (so
  1397. // long as it is not specifically disabled).
  1398. bool HasQPX = false;
  1399. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1400. HasQPX = A->getValue() == StringRef("a2q");
  1401. HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
  1402. if (HasQPX) {
  1403. ABIName = "elfv1-qpx";
  1404. break;
  1405. }
  1406. ABIName = "elfv1";
  1407. break;
  1408. }
  1409. case llvm::Triple::ppc64le:
  1410. ABIName = "elfv2";
  1411. break;
  1412. default:
  1413. break;
  1414. }
  1415. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1416. // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
  1417. // the option if given as we don't have backend support for any targets
  1418. // that don't use the altivec abi.
  1419. if (StringRef(A->getValue()) != "altivec")
  1420. ABIName = A->getValue();
  1421. ppc::FloatABI FloatABI =
  1422. ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
  1423. if (FloatABI == ppc::FloatABI::Soft) {
  1424. // Floating point operations and argument passing are soft.
  1425. CmdArgs.push_back("-msoft-float");
  1426. CmdArgs.push_back("-mfloat-abi");
  1427. CmdArgs.push_back("soft");
  1428. } else {
  1429. // Floating point operations and argument passing are hard.
  1430. assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
  1431. CmdArgs.push_back("-mfloat-abi");
  1432. CmdArgs.push_back("hard");
  1433. }
  1434. if (ABIName) {
  1435. CmdArgs.push_back("-target-abi");
  1436. CmdArgs.push_back(ABIName);
  1437. }
  1438. }
  1439. bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
  1440. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  1441. return A && (A->getValue() == StringRef(Value));
  1442. }
  1443. /// Get the (LLVM) name of the R600 gpu we are targeting.
  1444. static std::string getR600TargetGPU(const ArgList &Args) {
  1445. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1446. const char *GPUName = A->getValue();
  1447. return llvm::StringSwitch<const char *>(GPUName)
  1448. .Cases("rv630", "rv635", "r600")
  1449. .Cases("rv610", "rv620", "rs780", "rs880")
  1450. .Case("rv740", "rv770")
  1451. .Case("palm", "cedar")
  1452. .Cases("sumo", "sumo2", "sumo")
  1453. .Case("hemlock", "cypress")
  1454. .Case("aruba", "cayman")
  1455. .Default(GPUName);
  1456. }
  1457. return "";
  1458. }
  1459. static std::string getLanaiTargetCPU(const ArgList &Args) {
  1460. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1461. return A->getValue();
  1462. }
  1463. return "";
  1464. }
  1465. void Clang::AddSparcTargetArgs(const ArgList &Args,
  1466. ArgStringList &CmdArgs) const {
  1467. const Driver &D = getToolChain().getDriver();
  1468. std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
  1469. bool SoftFloatABI = false;
  1470. if (Arg *A =
  1471. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
  1472. if (A->getOption().matches(options::OPT_msoft_float))
  1473. SoftFloatABI = true;
  1474. }
  1475. // Only the hard-float ABI on Sparc is standardized, and it is the
  1476. // default. GCC also supports a nonstandard soft-float ABI mode, and
  1477. // perhaps LLVM should implement that, too. However, since llvm
  1478. // currently does not support Sparc soft-float, at all, display an
  1479. // error if it's requested.
  1480. if (SoftFloatABI) {
  1481. D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
  1482. << Triple;
  1483. }
  1484. }
  1485. static const char *getSystemZTargetCPU(const ArgList &Args) {
  1486. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1487. return A->getValue();
  1488. return "z10";
  1489. }
  1490. static void getSystemZTargetFeatures(const ArgList &Args,
  1491. std::vector<const char *> &Features) {
  1492. // -m(no-)htm overrides use of the transactional-execution facility.
  1493. if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
  1494. if (A->getOption().matches(options::OPT_mhtm))
  1495. Features.push_back("+transactional-execution");
  1496. else
  1497. Features.push_back("-transactional-execution");
  1498. }
  1499. // -m(no-)vx overrides use of the vector facility.
  1500. if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
  1501. if (A->getOption().matches(options::OPT_mvx))
  1502. Features.push_back("+vector");
  1503. else
  1504. Features.push_back("-vector");
  1505. }
  1506. }
  1507. static const char *getX86TargetCPU(const ArgList &Args,
  1508. const llvm::Triple &Triple) {
  1509. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1510. if (StringRef(A->getValue()) != "native") {
  1511. if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
  1512. return "core-avx2";
  1513. return A->getValue();
  1514. }
  1515. // FIXME: Reject attempts to use -march=native unless the target matches
  1516. // the host.
  1517. //
  1518. // FIXME: We should also incorporate the detected target features for use
  1519. // with -native.
  1520. std::string CPU = llvm::sys::getHostCPUName();
  1521. if (!CPU.empty() && CPU != "generic")
  1522. return Args.MakeArgString(CPU);
  1523. }
  1524. if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1525. // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
  1526. StringRef Arch = A->getValue();
  1527. const char *CPU;
  1528. if (Triple.getArch() == llvm::Triple::x86) {
  1529. CPU = llvm::StringSwitch<const char *>(Arch)
  1530. .Case("IA32", "i386")
  1531. .Case("SSE", "pentium3")
  1532. .Case("SSE2", "pentium4")
  1533. .Case("AVX", "sandybridge")
  1534. .Case("AVX2", "haswell")
  1535. .Default(nullptr);
  1536. } else {
  1537. CPU = llvm::StringSwitch<const char *>(Arch)
  1538. .Case("AVX", "sandybridge")
  1539. .Case("AVX2", "haswell")
  1540. .Default(nullptr);
  1541. }
  1542. if (CPU)
  1543. return CPU;
  1544. }
  1545. // Select the default CPU if none was given (or detection failed).
  1546. if (Triple.getArch() != llvm::Triple::x86_64 &&
  1547. Triple.getArch() != llvm::Triple::x86)
  1548. return nullptr; // This routine is only handling x86 targets.
  1549. bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
  1550. // FIXME: Need target hooks.
  1551. if (Triple.isOSDarwin()) {
  1552. if (Triple.getArchName() == "x86_64h")
  1553. return "core-avx2";
  1554. return Is64Bit ? "core2" : "yonah";
  1555. }
  1556. // Set up default CPU name for PS4 compilers.
  1557. if (Triple.isPS4CPU())
  1558. return "btver2";
  1559. // On Android use targets compatible with gcc
  1560. if (Triple.isAndroid())
  1561. return Is64Bit ? "x86-64" : "i686";
  1562. // Everything else goes to x86-64 in 64-bit mode.
  1563. if (Is64Bit)
  1564. return "x86-64";
  1565. switch (Triple.getOS()) {
  1566. case llvm::Triple::FreeBSD:
  1567. case llvm::Triple::NetBSD:
  1568. case llvm::Triple::OpenBSD:
  1569. return "i486";
  1570. case llvm::Triple::Haiku:
  1571. return "i586";
  1572. case llvm::Triple::Bitrig:
  1573. return "i686";
  1574. default:
  1575. // Fallback to p4.
  1576. return "pentium4";
  1577. }
  1578. }
  1579. /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
  1580. static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
  1581. // If we have -mcpu=, use that.
  1582. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1583. StringRef CPU = A->getValue();
  1584. #ifdef __wasm__
  1585. // Handle "native" by examining the host. "native" isn't meaningful when
  1586. // cross compiling, so only support this when the host is also WebAssembly.
  1587. if (CPU == "native")
  1588. return llvm::sys::getHostCPUName();
  1589. #endif
  1590. return CPU;
  1591. }
  1592. return "generic";
  1593. }
  1594. static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
  1595. bool FromAs = false) {
  1596. switch (T.getArch()) {
  1597. default:
  1598. return "";
  1599. case llvm::Triple::aarch64:
  1600. case llvm::Triple::aarch64_be:
  1601. return getAArch64TargetCPU(Args);
  1602. case llvm::Triple::arm:
  1603. case llvm::Triple::armeb:
  1604. case llvm::Triple::thumb:
  1605. case llvm::Triple::thumbeb: {
  1606. StringRef MArch, MCPU;
  1607. getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
  1608. return arm::getARMTargetCPU(MCPU, MArch, T);
  1609. }
  1610. case llvm::Triple::mips:
  1611. case llvm::Triple::mipsel:
  1612. case llvm::Triple::mips64:
  1613. case llvm::Triple::mips64el: {
  1614. StringRef CPUName;
  1615. StringRef ABIName;
  1616. mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
  1617. return CPUName;
  1618. }
  1619. case llvm::Triple::nvptx:
  1620. case llvm::Triple::nvptx64:
  1621. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1622. return A->getValue();
  1623. return "";
  1624. case llvm::Triple::ppc:
  1625. case llvm::Triple::ppc64:
  1626. case llvm::Triple::ppc64le: {
  1627. std::string TargetCPUName = getPPCTargetCPU(Args);
  1628. // LLVM may default to generating code for the native CPU,
  1629. // but, like gcc, we default to a more generic option for
  1630. // each architecture. (except on Darwin)
  1631. if (TargetCPUName.empty() && !T.isOSDarwin()) {
  1632. if (T.getArch() == llvm::Triple::ppc64)
  1633. TargetCPUName = "ppc64";
  1634. else if (T.getArch() == llvm::Triple::ppc64le)
  1635. TargetCPUName = "ppc64le";
  1636. else
  1637. TargetCPUName = "ppc";
  1638. }
  1639. return TargetCPUName;
  1640. }
  1641. case llvm::Triple::sparc:
  1642. case llvm::Triple::sparcel:
  1643. case llvm::Triple::sparcv9:
  1644. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1645. return A->getValue();
  1646. return "";
  1647. case llvm::Triple::x86:
  1648. case llvm::Triple::x86_64:
  1649. return getX86TargetCPU(Args, T);
  1650. case llvm::Triple::hexagon:
  1651. return "hexagon" +
  1652. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  1653. case llvm::Triple::lanai:
  1654. return getLanaiTargetCPU(Args);
  1655. case llvm::Triple::systemz:
  1656. return getSystemZTargetCPU(Args);
  1657. case llvm::Triple::r600:
  1658. case llvm::Triple::amdgcn:
  1659. return getR600TargetGPU(Args);
  1660. case llvm::Triple::wasm32:
  1661. case llvm::Triple::wasm64:
  1662. return getWebAssemblyTargetCPU(Args);
  1663. }
  1664. }
  1665. static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
  1666. ArgStringList &CmdArgs, bool IsThinLTO) {
  1667. // Tell the linker to load the plugin. This has to come before AddLinkerInputs
  1668. // as gold requires -plugin to come before any -plugin-opt that -Wl might
  1669. // forward.
  1670. CmdArgs.push_back("-plugin");
  1671. std::string Plugin =
  1672. ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
  1673. CmdArgs.push_back(Args.MakeArgString(Plugin));
  1674. // Try to pass driver level flags relevant to LTO code generation down to
  1675. // the plugin.
  1676. // Handle flags for selecting CPU variants.
  1677. std::string CPU = getCPUName(Args, ToolChain.getTriple());
  1678. if (!CPU.empty())
  1679. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
  1680. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  1681. StringRef OOpt;
  1682. if (A->getOption().matches(options::OPT_O4) ||
  1683. A->getOption().matches(options::OPT_Ofast))
  1684. OOpt = "3";
  1685. else if (A->getOption().matches(options::OPT_O))
  1686. OOpt = A->getValue();
  1687. else if (A->getOption().matches(options::OPT_O0))
  1688. OOpt = "0";
  1689. if (!OOpt.empty())
  1690. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
  1691. }
  1692. if (IsThinLTO)
  1693. CmdArgs.push_back("-plugin-opt=thinlto");
  1694. // If an explicit debugger tuning argument appeared, pass it along.
  1695. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  1696. options::OPT_ggdbN_Group)) {
  1697. if (A->getOption().matches(options::OPT_glldb))
  1698. CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
  1699. else if (A->getOption().matches(options::OPT_gsce))
  1700. CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
  1701. else
  1702. CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
  1703. }
  1704. }
  1705. /// This is a helper function for validating the optional refinement step
  1706. /// parameter in reciprocal argument strings. Return false if there is an error
  1707. /// parsing the refinement step. Otherwise, return true and set the Position
  1708. /// of the refinement step in the input string.
  1709. static bool getRefinementStep(StringRef In, const Driver &D,
  1710. const Arg &A, size_t &Position) {
  1711. const char RefinementStepToken = ':';
  1712. Position = In.find(RefinementStepToken);
  1713. if (Position != StringRef::npos) {
  1714. StringRef Option = A.getOption().getName();
  1715. StringRef RefStep = In.substr(Position + 1);
  1716. // Allow exactly one numeric character for the additional refinement
  1717. // step parameter. This is reasonable for all currently-supported
  1718. // operations and architectures because we would expect that a larger value
  1719. // of refinement steps would cause the estimate "optimization" to
  1720. // under-perform the native operation. Also, if the estimate does not
  1721. // converge quickly, it probably will not ever converge, so further
  1722. // refinement steps will not produce a better answer.
  1723. if (RefStep.size() != 1) {
  1724. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1725. return false;
  1726. }
  1727. char RefStepChar = RefStep[0];
  1728. if (RefStepChar < '0' || RefStepChar > '9') {
  1729. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1730. return false;
  1731. }
  1732. }
  1733. return true;
  1734. }
  1735. /// The -mrecip flag requires processing of many optional parameters.
  1736. static void ParseMRecip(const Driver &D, const ArgList &Args,
  1737. ArgStringList &OutStrings) {
  1738. StringRef DisabledPrefixIn = "!";
  1739. StringRef DisabledPrefixOut = "!";
  1740. StringRef EnabledPrefixOut = "";
  1741. StringRef Out = "-mrecip=";
  1742. Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
  1743. if (!A)
  1744. return;
  1745. unsigned NumOptions = A->getNumValues();
  1746. if (NumOptions == 0) {
  1747. // No option is the same as "all".
  1748. OutStrings.push_back(Args.MakeArgString(Out + "all"));
  1749. return;
  1750. }
  1751. // Pass through "all", "none", or "default" with an optional refinement step.
  1752. if (NumOptions == 1) {
  1753. StringRef Val = A->getValue(0);
  1754. size_t RefStepLoc;
  1755. if (!getRefinementStep(Val, D, *A, RefStepLoc))
  1756. return;
  1757. StringRef ValBase = Val.slice(0, RefStepLoc);
  1758. if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
  1759. OutStrings.push_back(Args.MakeArgString(Out + Val));
  1760. return;
  1761. }
  1762. }
  1763. // Each reciprocal type may be enabled or disabled individually.
  1764. // Check each input value for validity, concatenate them all back together,
  1765. // and pass through.
  1766. llvm::StringMap<bool> OptionStrings;
  1767. OptionStrings.insert(std::make_pair("divd", false));
  1768. OptionStrings.insert(std::make_pair("divf", false));
  1769. OptionStrings.insert(std::make_pair("vec-divd", false));
  1770. OptionStrings.insert(std::make_pair("vec-divf", false));
  1771. OptionStrings.insert(std::make_pair("sqrtd", false));
  1772. OptionStrings.insert(std::make_pair("sqrtf", false));
  1773. OptionStrings.insert(std::make_pair("vec-sqrtd", false));
  1774. OptionStrings.insert(std::make_pair("vec-sqrtf", false));
  1775. for (unsigned i = 0; i != NumOptions; ++i) {
  1776. StringRef Val = A->getValue(i);
  1777. bool IsDisabled = Val.startswith(DisabledPrefixIn);
  1778. // Ignore the disablement token for string matching.
  1779. if (IsDisabled)
  1780. Val = Val.substr(1);
  1781. size_t RefStep;
  1782. if (!getRefinementStep(Val, D, *A, RefStep))
  1783. return;
  1784. StringRef ValBase = Val.slice(0, RefStep);
  1785. llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
  1786. if (OptionIter == OptionStrings.end()) {
  1787. // Try again specifying float suffix.
  1788. OptionIter = OptionStrings.find(ValBase.str() + 'f');
  1789. if (OptionIter == OptionStrings.end()) {
  1790. // The input name did not match any known option string.
  1791. D.Diag(diag::err_drv_unknown_argument) << Val;
  1792. return;
  1793. }
  1794. // The option was specified without a float or double suffix.
  1795. // Make sure that the double entry was not already specified.
  1796. // The float entry will be checked below.
  1797. if (OptionStrings[ValBase.str() + 'd']) {
  1798. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1799. return;
  1800. }
  1801. }
  1802. if (OptionIter->second == true) {
  1803. // Duplicate option specified.
  1804. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1805. return;
  1806. }
  1807. // Mark the matched option as found. Do not allow duplicate specifiers.
  1808. OptionIter->second = true;
  1809. // If the precision was not specified, also mark the double entry as found.
  1810. if (ValBase.back() != 'f' && ValBase.back() != 'd')
  1811. OptionStrings[ValBase.str() + 'd'] = true;
  1812. // Build the output string.
  1813. StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
  1814. Out = Args.MakeArgString(Out + Prefix + Val);
  1815. if (i != NumOptions - 1)
  1816. Out = Args.MakeArgString(Out + ",");
  1817. }
  1818. OutStrings.push_back(Args.MakeArgString(Out));
  1819. }
  1820. static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1821. const ArgList &Args,
  1822. std::vector<const char *> &Features) {
  1823. // If -march=native, autodetect the feature list.
  1824. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1825. if (StringRef(A->getValue()) == "native") {
  1826. llvm::StringMap<bool> HostFeatures;
  1827. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  1828. for (auto &F : HostFeatures)
  1829. Features.push_back(
  1830. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  1831. }
  1832. }
  1833. if (Triple.getArchName() == "x86_64h") {
  1834. // x86_64h implies quite a few of the more modern subtarget features
  1835. // for Haswell class CPUs, but not all of them. Opt-out of a few.
  1836. Features.push_back("-rdrnd");
  1837. Features.push_back("-aes");
  1838. Features.push_back("-pclmul");
  1839. Features.push_back("-rtm");
  1840. Features.push_back("-hle");
  1841. Features.push_back("-fsgsbase");
  1842. }
  1843. const llvm::Triple::ArchType ArchType = Triple.getArch();
  1844. // Add features to be compatible with gcc for Android.
  1845. if (Triple.isAndroid()) {
  1846. if (ArchType == llvm::Triple::x86_64) {
  1847. Features.push_back("+sse4.2");
  1848. Features.push_back("+popcnt");
  1849. } else
  1850. Features.push_back("+ssse3");
  1851. }
  1852. // Set features according to the -arch flag on MSVC.
  1853. if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1854. StringRef Arch = A->getValue();
  1855. bool ArchUsed = false;
  1856. // First, look for flags that are shared in x86 and x86-64.
  1857. if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
  1858. if (Arch == "AVX" || Arch == "AVX2") {
  1859. ArchUsed = true;
  1860. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1861. }
  1862. }
  1863. // Then, look for x86-specific flags.
  1864. if (ArchType == llvm::Triple::x86) {
  1865. if (Arch == "IA32") {
  1866. ArchUsed = true;
  1867. } else if (Arch == "SSE" || Arch == "SSE2") {
  1868. ArchUsed = true;
  1869. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1870. }
  1871. }
  1872. if (!ArchUsed)
  1873. D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
  1874. }
  1875. // Now add any that the user explicitly requested on the command line,
  1876. // which may override the defaults.
  1877. handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
  1878. }
  1879. void Clang::AddX86TargetArgs(const ArgList &Args,
  1880. ArgStringList &CmdArgs) const {
  1881. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1882. Args.hasArg(options::OPT_mkernel) ||
  1883. Args.hasArg(options::OPT_fapple_kext))
  1884. CmdArgs.push_back("-disable-red-zone");
  1885. // Default to avoid implicit floating-point for kernel/kext code, but allow
  1886. // that to be overridden with -mno-soft-float.
  1887. bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
  1888. Args.hasArg(options::OPT_fapple_kext));
  1889. if (Arg *A = Args.getLastArg(
  1890. options::OPT_msoft_float, options::OPT_mno_soft_float,
  1891. options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
  1892. const Option &O = A->getOption();
  1893. NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
  1894. O.matches(options::OPT_msoft_float));
  1895. }
  1896. if (NoImplicitFloat)
  1897. CmdArgs.push_back("-no-implicit-float");
  1898. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  1899. StringRef Value = A->getValue();
  1900. if (Value == "intel" || Value == "att") {
  1901. CmdArgs.push_back("-mllvm");
  1902. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  1903. } else {
  1904. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  1905. << A->getOption().getName() << Value;
  1906. }
  1907. }
  1908. // Set flags to support MCU ABI.
  1909. if (Args.hasArg(options::OPT_miamcu)) {
  1910. CmdArgs.push_back("-mfloat-abi");
  1911. CmdArgs.push_back("soft");
  1912. CmdArgs.push_back("-mstack-alignment=4");
  1913. }
  1914. }
  1915. void Clang::AddHexagonTargetArgs(const ArgList &Args,
  1916. ArgStringList &CmdArgs) const {
  1917. CmdArgs.push_back("-mqdsp6-compat");
  1918. CmdArgs.push_back("-Wreturn-type");
  1919. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  1920. std::string N = llvm::utostr(G.getValue());
  1921. std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
  1922. CmdArgs.push_back("-mllvm");
  1923. CmdArgs.push_back(Args.MakeArgString(Opt));
  1924. }
  1925. if (!Args.hasArg(options::OPT_fno_short_enums))
  1926. CmdArgs.push_back("-fshort-enums");
  1927. if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
  1928. CmdArgs.push_back("-mllvm");
  1929. CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
  1930. }
  1931. CmdArgs.push_back("-mllvm");
  1932. CmdArgs.push_back("-machine-sink-split=0");
  1933. }
  1934. void Clang::AddLanaiTargetArgs(const ArgList &Args,
  1935. ArgStringList &CmdArgs) const {
  1936. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1937. StringRef CPUName = A->getValue();
  1938. CmdArgs.push_back("-target-cpu");
  1939. CmdArgs.push_back(Args.MakeArgString(CPUName));
  1940. }
  1941. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  1942. StringRef Value = A->getValue();
  1943. // Only support mregparm=4 to support old usage. Report error for all other
  1944. // cases.
  1945. int Mregparm;
  1946. if (Value.getAsInteger(10, Mregparm)) {
  1947. if (Mregparm != 4) {
  1948. getToolChain().getDriver().Diag(
  1949. diag::err_drv_unsupported_option_argument)
  1950. << A->getOption().getName() << Value;
  1951. }
  1952. }
  1953. }
  1954. }
  1955. void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
  1956. ArgStringList &CmdArgs) const {
  1957. // Default to "hidden" visibility.
  1958. if (!Args.hasArg(options::OPT_fvisibility_EQ,
  1959. options::OPT_fvisibility_ms_compat)) {
  1960. CmdArgs.push_back("-fvisibility");
  1961. CmdArgs.push_back("hidden");
  1962. }
  1963. }
  1964. // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
  1965. static bool DecodeAArch64Features(const Driver &D, StringRef text,
  1966. std::vector<const char *> &Features) {
  1967. SmallVector<StringRef, 8> Split;
  1968. text.split(Split, StringRef("+"), -1, false);
  1969. for (StringRef Feature : Split) {
  1970. const char *result = llvm::StringSwitch<const char *>(Feature)
  1971. .Case("fp", "+fp-armv8")
  1972. .Case("simd", "+neon")
  1973. .Case("crc", "+crc")
  1974. .Case("crypto", "+crypto")
  1975. .Case("fp16", "+fullfp16")
  1976. .Case("profile", "+spe")
  1977. .Case("nofp", "-fp-armv8")
  1978. .Case("nosimd", "-neon")
  1979. .Case("nocrc", "-crc")
  1980. .Case("nocrypto", "-crypto")
  1981. .Case("nofp16", "-fullfp16")
  1982. .Case("noprofile", "-spe")
  1983. .Default(nullptr);
  1984. if (result)
  1985. Features.push_back(result);
  1986. else if (Feature == "neon" || Feature == "noneon")
  1987. D.Diag(diag::err_drv_no_neon_modifier);
  1988. else
  1989. return false;
  1990. }
  1991. return true;
  1992. }
  1993. // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
  1994. // decode CPU and feature.
  1995. static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
  1996. std::vector<const char *> &Features) {
  1997. std::pair<StringRef, StringRef> Split = Mcpu.split("+");
  1998. CPU = Split.first;
  1999. if (CPU == "cortex-a53" || CPU == "cortex-a57" ||
  2000. CPU == "cortex-a72" || CPU == "cortex-a35" || CPU == "exynos-m1" ||
  2001. CPU == "kryo") {
  2002. Features.push_back("+neon");
  2003. Features.push_back("+crc");
  2004. Features.push_back("+crypto");
  2005. } else if (CPU == "cyclone") {
  2006. Features.push_back("+neon");
  2007. Features.push_back("+crypto");
  2008. } else if (CPU == "generic") {
  2009. Features.push_back("+neon");
  2010. } else {
  2011. return false;
  2012. }
  2013. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  2014. return false;
  2015. return true;
  2016. }
  2017. static bool
  2018. getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
  2019. const ArgList &Args,
  2020. std::vector<const char *> &Features) {
  2021. std::string MarchLowerCase = March.lower();
  2022. std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
  2023. if (Split.first == "armv8-a" || Split.first == "armv8a") {
  2024. // ok, no additional features.
  2025. } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
  2026. Features.push_back("+v8.1a");
  2027. } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
  2028. Features.push_back("+v8.2a");
  2029. } else {
  2030. return false;
  2031. }
  2032. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  2033. return false;
  2034. return true;
  2035. }
  2036. static bool
  2037. getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  2038. const ArgList &Args,
  2039. std::vector<const char *> &Features) {
  2040. StringRef CPU;
  2041. std::string McpuLowerCase = Mcpu.lower();
  2042. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
  2043. return false;
  2044. return true;
  2045. }
  2046. static bool
  2047. getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
  2048. const ArgList &Args,
  2049. std::vector<const char *> &Features) {
  2050. std::string MtuneLowerCase = Mtune.lower();
  2051. // Handle CPU name is 'native'.
  2052. if (MtuneLowerCase == "native")
  2053. MtuneLowerCase = llvm::sys::getHostCPUName();
  2054. if (MtuneLowerCase == "cyclone") {
  2055. Features.push_back("+zcm");
  2056. Features.push_back("+zcz");
  2057. }
  2058. return true;
  2059. }
  2060. static bool
  2061. getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  2062. const ArgList &Args,
  2063. std::vector<const char *> &Features) {
  2064. StringRef CPU;
  2065. std::vector<const char *> DecodedFeature;
  2066. std::string McpuLowerCase = Mcpu.lower();
  2067. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
  2068. return false;
  2069. return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
  2070. }
  2071. static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
  2072. std::vector<const char *> &Features) {
  2073. Arg *A;
  2074. bool success = true;
  2075. // Enable NEON by default.
  2076. Features.push_back("+neon");
  2077. if ((A = Args.getLastArg(options::OPT_march_EQ)))
  2078. success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
  2079. else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
  2080. success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  2081. else if (Args.hasArg(options::OPT_arch))
  2082. success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
  2083. Features);
  2084. if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
  2085. success =
  2086. getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
  2087. else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
  2088. success =
  2089. getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  2090. else if (Args.hasArg(options::OPT_arch))
  2091. success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
  2092. Args, Features);
  2093. if (!success)
  2094. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  2095. if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
  2096. Features.push_back("-fp-armv8");
  2097. Features.push_back("-crypto");
  2098. Features.push_back("-neon");
  2099. }
  2100. // En/disable crc
  2101. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  2102. if (A->getOption().matches(options::OPT_mcrc))
  2103. Features.push_back("+crc");
  2104. else
  2105. Features.push_back("-crc");
  2106. }
  2107. if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  2108. options::OPT_munaligned_access))
  2109. if (A->getOption().matches(options::OPT_mno_unaligned_access))
  2110. Features.push_back("+strict-align");
  2111. if (Args.hasArg(options::OPT_ffixed_x18))
  2112. Features.push_back("+reserve-x18");
  2113. }
  2114. static void getHexagonTargetFeatures(const ArgList &Args,
  2115. std::vector<const char *> &Features) {
  2116. bool HasHVX = false, HasHVXD = false;
  2117. // FIXME: This should be able to use handleTargetFeaturesGroup except it is
  2118. // doing dependent option handling here rather than in initFeatureMap or a
  2119. // similar handler.
  2120. for (auto &A : Args) {
  2121. auto &Opt = A->getOption();
  2122. if (Opt.matches(options::OPT_mhexagon_hvx))
  2123. HasHVX = true;
  2124. else if (Opt.matches(options::OPT_mno_hexagon_hvx))
  2125. HasHVXD = HasHVX = false;
  2126. else if (Opt.matches(options::OPT_mhexagon_hvx_double))
  2127. HasHVXD = HasHVX = true;
  2128. else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
  2129. HasHVXD = false;
  2130. else
  2131. continue;
  2132. A->claim();
  2133. }
  2134. Features.push_back(HasHVX ? "+hvx" : "-hvx");
  2135. Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
  2136. }
  2137. static void getWebAssemblyTargetFeatures(const ArgList &Args,
  2138. std::vector<const char *> &Features) {
  2139. handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
  2140. }
  2141. static void getAMDGPUTargetFeatures(const Driver &D, const ArgList &Args,
  2142. std::vector<const char *> &Features) {
  2143. if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi)) {
  2144. StringRef value = dAbi->getValue();
  2145. if (value == "1.0") {
  2146. Features.push_back("+amdgpu-debugger-insert-nops");
  2147. Features.push_back("+amdgpu-debugger-reserve-trap-regs");
  2148. } else {
  2149. D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
  2150. }
  2151. }
  2152. handleTargetFeaturesGroup(
  2153. Args, Features, options::OPT_m_amdgpu_Features_Group);
  2154. }
  2155. static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
  2156. const ArgList &Args, ArgStringList &CmdArgs,
  2157. bool ForAS) {
  2158. const Driver &D = TC.getDriver();
  2159. std::vector<const char *> Features;
  2160. switch (Triple.getArch()) {
  2161. default:
  2162. break;
  2163. case llvm::Triple::mips:
  2164. case llvm::Triple::mipsel:
  2165. case llvm::Triple::mips64:
  2166. case llvm::Triple::mips64el:
  2167. getMIPSTargetFeatures(D, Triple, Args, Features);
  2168. break;
  2169. case llvm::Triple::arm:
  2170. case llvm::Triple::armeb:
  2171. case llvm::Triple::thumb:
  2172. case llvm::Triple::thumbeb:
  2173. getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
  2174. break;
  2175. case llvm::Triple::ppc:
  2176. case llvm::Triple::ppc64:
  2177. case llvm::Triple::ppc64le:
  2178. getPPCTargetFeatures(D, Triple, Args, Features);
  2179. break;
  2180. case llvm::Triple::systemz:
  2181. getSystemZTargetFeatures(Args, Features);
  2182. break;
  2183. case llvm::Triple::aarch64:
  2184. case llvm::Triple::aarch64_be:
  2185. getAArch64TargetFeatures(D, Args, Features);
  2186. break;
  2187. case llvm::Triple::x86:
  2188. case llvm::Triple::x86_64:
  2189. getX86TargetFeatures(D, Triple, Args, Features);
  2190. break;
  2191. case llvm::Triple::hexagon:
  2192. getHexagonTargetFeatures(Args, Features);
  2193. break;
  2194. case llvm::Triple::wasm32:
  2195. case llvm::Triple::wasm64:
  2196. getWebAssemblyTargetFeatures(Args, Features);
  2197. break;
  2198. case llvm::Triple::r600:
  2199. case llvm::Triple::amdgcn:
  2200. getAMDGPUTargetFeatures(D, Args, Features);
  2201. break;
  2202. }
  2203. // Find the last of each feature.
  2204. llvm::StringMap<unsigned> LastOpt;
  2205. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2206. const char *Name = Features[I];
  2207. assert(Name[0] == '-' || Name[0] == '+');
  2208. LastOpt[Name + 1] = I;
  2209. }
  2210. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2211. // If this feature was overridden, ignore it.
  2212. const char *Name = Features[I];
  2213. llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
  2214. assert(LastI != LastOpt.end());
  2215. unsigned Last = LastI->second;
  2216. if (Last != I)
  2217. continue;
  2218. CmdArgs.push_back("-target-feature");
  2219. CmdArgs.push_back(Name);
  2220. }
  2221. }
  2222. static bool
  2223. shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
  2224. const llvm::Triple &Triple) {
  2225. // We use the zero-cost exception tables for Objective-C if the non-fragile
  2226. // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
  2227. // later.
  2228. if (runtime.isNonFragile())
  2229. return true;
  2230. if (!Triple.isMacOSX())
  2231. return false;
  2232. return (!Triple.isMacOSXVersionLT(10, 5) &&
  2233. (Triple.getArch() == llvm::Triple::x86_64 ||
  2234. Triple.getArch() == llvm::Triple::arm));
  2235. }
  2236. /// Adds exception related arguments to the driver command arguments. There's a
  2237. /// master flag, -fexceptions and also language specific flags to enable/disable
  2238. /// C++ and Objective-C exceptions. This makes it possible to for example
  2239. /// disable C++ exceptions but enable Objective-C exceptions.
  2240. static void addExceptionArgs(const ArgList &Args, types::ID InputType,
  2241. const ToolChain &TC, bool KernelOrKext,
  2242. const ObjCRuntime &objcRuntime,
  2243. ArgStringList &CmdArgs) {
  2244. const Driver &D = TC.getDriver();
  2245. const llvm::Triple &Triple = TC.getTriple();
  2246. if (KernelOrKext) {
  2247. // -mkernel and -fapple-kext imply no exceptions, so claim exception related
  2248. // arguments now to avoid warnings about unused arguments.
  2249. Args.ClaimAllArgs(options::OPT_fexceptions);
  2250. Args.ClaimAllArgs(options::OPT_fno_exceptions);
  2251. Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
  2252. Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
  2253. Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
  2254. Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
  2255. return;
  2256. }
  2257. // See if the user explicitly enabled exceptions.
  2258. bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  2259. false);
  2260. // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
  2261. // is not necessarily sensible, but follows GCC.
  2262. if (types::isObjC(InputType) &&
  2263. Args.hasFlag(options::OPT_fobjc_exceptions,
  2264. options::OPT_fno_objc_exceptions, true)) {
  2265. CmdArgs.push_back("-fobjc-exceptions");
  2266. EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
  2267. }
  2268. if (types::isCXX(InputType)) {
  2269. // Disable C++ EH by default on XCore and PS4.
  2270. bool CXXExceptionsEnabled =
  2271. Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
  2272. Arg *ExceptionArg = Args.getLastArg(
  2273. options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
  2274. options::OPT_fexceptions, options::OPT_fno_exceptions);
  2275. if (ExceptionArg)
  2276. CXXExceptionsEnabled =
  2277. ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
  2278. ExceptionArg->getOption().matches(options::OPT_fexceptions);
  2279. if (CXXExceptionsEnabled) {
  2280. if (Triple.isPS4CPU()) {
  2281. ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
  2282. assert(ExceptionArg &&
  2283. "On the PS4 exceptions should only be enabled if passing "
  2284. "an argument");
  2285. if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
  2286. const Arg *RTTIArg = TC.getRTTIArg();
  2287. assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
  2288. D.Diag(diag::err_drv_argument_not_allowed_with)
  2289. << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
  2290. } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
  2291. D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
  2292. } else
  2293. assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
  2294. CmdArgs.push_back("-fcxx-exceptions");
  2295. EH = true;
  2296. }
  2297. }
  2298. if (EH)
  2299. CmdArgs.push_back("-fexceptions");
  2300. }
  2301. static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
  2302. bool Default = true;
  2303. if (TC.getTriple().isOSDarwin()) {
  2304. // The native darwin assembler doesn't support the linker_option directives,
  2305. // so we disable them if we think the .s file will be passed to it.
  2306. Default = TC.useIntegratedAs();
  2307. }
  2308. return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
  2309. Default);
  2310. }
  2311. static bool ShouldDisableDwarfDirectory(const ArgList &Args,
  2312. const ToolChain &TC) {
  2313. bool UseDwarfDirectory =
  2314. Args.hasFlag(options::OPT_fdwarf_directory_asm,
  2315. options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
  2316. return !UseDwarfDirectory;
  2317. }
  2318. /// \brief Check whether the given input tree contains any compilation actions.
  2319. static bool ContainsCompileAction(const Action *A) {
  2320. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
  2321. return true;
  2322. for (const auto &AI : A->inputs())
  2323. if (ContainsCompileAction(AI))
  2324. return true;
  2325. return false;
  2326. }
  2327. /// \brief Check if -relax-all should be passed to the internal assembler.
  2328. /// This is done by default when compiling non-assembler source with -O0.
  2329. static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
  2330. bool RelaxDefault = true;
  2331. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2332. RelaxDefault = A->getOption().matches(options::OPT_O0);
  2333. if (RelaxDefault) {
  2334. RelaxDefault = false;
  2335. for (const auto &Act : C.getActions()) {
  2336. if (ContainsCompileAction(Act)) {
  2337. RelaxDefault = true;
  2338. break;
  2339. }
  2340. }
  2341. }
  2342. return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
  2343. RelaxDefault);
  2344. }
  2345. // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
  2346. // to the corresponding DebugInfoKind.
  2347. static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
  2348. assert(A.getOption().matches(options::OPT_gN_Group) &&
  2349. "Not a -g option that specifies a debug-info level");
  2350. if (A.getOption().matches(options::OPT_g0) ||
  2351. A.getOption().matches(options::OPT_ggdb0))
  2352. return codegenoptions::NoDebugInfo;
  2353. if (A.getOption().matches(options::OPT_gline_tables_only) ||
  2354. A.getOption().matches(options::OPT_ggdb1))
  2355. return codegenoptions::DebugLineTablesOnly;
  2356. return codegenoptions::LimitedDebugInfo;
  2357. }
  2358. // Extract the integer N from a string spelled "-dwarf-N", returning 0
  2359. // on mismatch. The StringRef input (rather than an Arg) allows
  2360. // for use by the "-Xassembler" option parser.
  2361. static unsigned DwarfVersionNum(StringRef ArgValue) {
  2362. return llvm::StringSwitch<unsigned>(ArgValue)
  2363. .Case("-gdwarf-2", 2)
  2364. .Case("-gdwarf-3", 3)
  2365. .Case("-gdwarf-4", 4)
  2366. .Case("-gdwarf-5", 5)
  2367. .Default(0);
  2368. }
  2369. static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
  2370. codegenoptions::DebugInfoKind DebugInfoKind,
  2371. unsigned DwarfVersion,
  2372. llvm::DebuggerKind DebuggerTuning) {
  2373. switch (DebugInfoKind) {
  2374. case codegenoptions::DebugLineTablesOnly:
  2375. CmdArgs.push_back("-debug-info-kind=line-tables-only");
  2376. break;
  2377. case codegenoptions::LimitedDebugInfo:
  2378. CmdArgs.push_back("-debug-info-kind=limited");
  2379. break;
  2380. case codegenoptions::FullDebugInfo:
  2381. CmdArgs.push_back("-debug-info-kind=standalone");
  2382. break;
  2383. default:
  2384. break;
  2385. }
  2386. if (DwarfVersion > 0)
  2387. CmdArgs.push_back(
  2388. Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
  2389. switch (DebuggerTuning) {
  2390. case llvm::DebuggerKind::GDB:
  2391. CmdArgs.push_back("-debugger-tuning=gdb");
  2392. break;
  2393. case llvm::DebuggerKind::LLDB:
  2394. CmdArgs.push_back("-debugger-tuning=lldb");
  2395. break;
  2396. case llvm::DebuggerKind::SCE:
  2397. CmdArgs.push_back("-debugger-tuning=sce");
  2398. break;
  2399. default:
  2400. break;
  2401. }
  2402. }
  2403. static void CollectArgsForIntegratedAssembler(Compilation &C,
  2404. const ArgList &Args,
  2405. ArgStringList &CmdArgs,
  2406. const Driver &D) {
  2407. if (UseRelaxAll(C, Args))
  2408. CmdArgs.push_back("-mrelax-all");
  2409. // Only default to -mincremental-linker-compatible if we think we are
  2410. // targeting the MSVC linker.
  2411. bool DefaultIncrementalLinkerCompatible =
  2412. C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
  2413. if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
  2414. options::OPT_mno_incremental_linker_compatible,
  2415. DefaultIncrementalLinkerCompatible))
  2416. CmdArgs.push_back("-mincremental-linker-compatible");
  2417. // When passing -I arguments to the assembler we sometimes need to
  2418. // unconditionally take the next argument. For example, when parsing
  2419. // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
  2420. // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
  2421. // arg after parsing the '-I' arg.
  2422. bool TakeNextArg = false;
  2423. // When using an integrated assembler, translate -Wa, and -Xassembler
  2424. // options.
  2425. bool CompressDebugSections = false;
  2426. const char *MipsTargetFeature = nullptr;
  2427. for (const Arg *A :
  2428. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  2429. A->claim();
  2430. for (StringRef Value : A->getValues()) {
  2431. if (TakeNextArg) {
  2432. CmdArgs.push_back(Value.data());
  2433. TakeNextArg = false;
  2434. continue;
  2435. }
  2436. switch (C.getDefaultToolChain().getArch()) {
  2437. default:
  2438. break;
  2439. case llvm::Triple::mips:
  2440. case llvm::Triple::mipsel:
  2441. case llvm::Triple::mips64:
  2442. case llvm::Triple::mips64el:
  2443. if (Value == "--trap") {
  2444. CmdArgs.push_back("-target-feature");
  2445. CmdArgs.push_back("+use-tcc-in-div");
  2446. continue;
  2447. }
  2448. if (Value == "--break") {
  2449. CmdArgs.push_back("-target-feature");
  2450. CmdArgs.push_back("-use-tcc-in-div");
  2451. continue;
  2452. }
  2453. if (Value.startswith("-msoft-float")) {
  2454. CmdArgs.push_back("-target-feature");
  2455. CmdArgs.push_back("+soft-float");
  2456. continue;
  2457. }
  2458. if (Value.startswith("-mhard-float")) {
  2459. CmdArgs.push_back("-target-feature");
  2460. CmdArgs.push_back("-soft-float");
  2461. continue;
  2462. }
  2463. MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
  2464. .Case("-mips1", "+mips1")
  2465. .Case("-mips2", "+mips2")
  2466. .Case("-mips3", "+mips3")
  2467. .Case("-mips4", "+mips4")
  2468. .Case("-mips5", "+mips5")
  2469. .Case("-mips32", "+mips32")
  2470. .Case("-mips32r2", "+mips32r2")
  2471. .Case("-mips32r3", "+mips32r3")
  2472. .Case("-mips32r5", "+mips32r5")
  2473. .Case("-mips32r6", "+mips32r6")
  2474. .Case("-mips64", "+mips64")
  2475. .Case("-mips64r2", "+mips64r2")
  2476. .Case("-mips64r3", "+mips64r3")
  2477. .Case("-mips64r5", "+mips64r5")
  2478. .Case("-mips64r6", "+mips64r6")
  2479. .Default(nullptr);
  2480. if (MipsTargetFeature)
  2481. continue;
  2482. }
  2483. if (Value == "-force_cpusubtype_ALL") {
  2484. // Do nothing, this is the default and we don't support anything else.
  2485. } else if (Value == "-L") {
  2486. CmdArgs.push_back("-msave-temp-labels");
  2487. } else if (Value == "--fatal-warnings") {
  2488. CmdArgs.push_back("-massembler-fatal-warnings");
  2489. } else if (Value == "--noexecstack") {
  2490. CmdArgs.push_back("-mnoexecstack");
  2491. } else if (Value == "-compress-debug-sections" ||
  2492. Value == "--compress-debug-sections") {
  2493. CompressDebugSections = true;
  2494. } else if (Value == "-nocompress-debug-sections" ||
  2495. Value == "--nocompress-debug-sections") {
  2496. CompressDebugSections = false;
  2497. } else if (Value.startswith("-I")) {
  2498. CmdArgs.push_back(Value.data());
  2499. // We need to consume the next argument if the current arg is a plain
  2500. // -I. The next arg will be the include directory.
  2501. if (Value == "-I")
  2502. TakeNextArg = true;
  2503. } else if (Value.startswith("-gdwarf-")) {
  2504. // "-gdwarf-N" options are not cc1as options.
  2505. unsigned DwarfVersion = DwarfVersionNum(Value);
  2506. if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
  2507. CmdArgs.push_back(Value.data());
  2508. } else {
  2509. RenderDebugEnablingArgs(Args, CmdArgs,
  2510. codegenoptions::LimitedDebugInfo,
  2511. DwarfVersion, llvm::DebuggerKind::Default);
  2512. }
  2513. } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
  2514. Value.startswith("-mhwdiv") || Value.startswith("-march")) {
  2515. // Do nothing, we'll validate it later.
  2516. } else {
  2517. D.Diag(diag::err_drv_unsupported_option_argument)
  2518. << A->getOption().getName() << Value;
  2519. }
  2520. }
  2521. }
  2522. if (CompressDebugSections) {
  2523. if (llvm::zlib::isAvailable())
  2524. CmdArgs.push_back("-compress-debug-sections");
  2525. else
  2526. D.Diag(diag::warn_debug_compression_unavailable);
  2527. }
  2528. if (MipsTargetFeature != nullptr) {
  2529. CmdArgs.push_back("-target-feature");
  2530. CmdArgs.push_back(MipsTargetFeature);
  2531. }
  2532. }
  2533. // This adds the static libclang_rt.builtins-arch.a directly to the command line
  2534. // FIXME: Make sure we can also emit shared objects if they're requested
  2535. // and available, check for possible errors, etc.
  2536. static void addClangRT(const ToolChain &TC, const ArgList &Args,
  2537. ArgStringList &CmdArgs) {
  2538. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
  2539. }
  2540. namespace {
  2541. enum OpenMPRuntimeKind {
  2542. /// An unknown OpenMP runtime. We can't generate effective OpenMP code
  2543. /// without knowing what runtime to target.
  2544. OMPRT_Unknown,
  2545. /// The LLVM OpenMP runtime. When completed and integrated, this will become
  2546. /// the default for Clang.
  2547. OMPRT_OMP,
  2548. /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
  2549. /// this runtime but can swallow the pragmas, and find and link against the
  2550. /// runtime library itself.
  2551. OMPRT_GOMP,
  2552. /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
  2553. /// OpenMP runtime. We support this mode for users with existing dependencies
  2554. /// on this runtime library name.
  2555. OMPRT_IOMP5
  2556. };
  2557. }
  2558. /// Compute the desired OpenMP runtime from the flag provided.
  2559. static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
  2560. const ArgList &Args) {
  2561. StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
  2562. const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
  2563. if (A)
  2564. RuntimeName = A->getValue();
  2565. auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
  2566. .Case("libomp", OMPRT_OMP)
  2567. .Case("libgomp", OMPRT_GOMP)
  2568. .Case("libiomp5", OMPRT_IOMP5)
  2569. .Default(OMPRT_Unknown);
  2570. if (RT == OMPRT_Unknown) {
  2571. if (A)
  2572. TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
  2573. << A->getOption().getName() << A->getValue();
  2574. else
  2575. // FIXME: We could use a nicer diagnostic here.
  2576. TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
  2577. }
  2578. return RT;
  2579. }
  2580. static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
  2581. const ArgList &Args) {
  2582. if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  2583. options::OPT_fno_openmp, false))
  2584. return;
  2585. switch (getOpenMPRuntime(TC, Args)) {
  2586. case OMPRT_OMP:
  2587. CmdArgs.push_back("-lomp");
  2588. break;
  2589. case OMPRT_GOMP:
  2590. CmdArgs.push_back("-lgomp");
  2591. break;
  2592. case OMPRT_IOMP5:
  2593. CmdArgs.push_back("-liomp5");
  2594. break;
  2595. case OMPRT_Unknown:
  2596. // Already diagnosed.
  2597. break;
  2598. }
  2599. }
  2600. static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
  2601. ArgStringList &CmdArgs, StringRef Sanitizer,
  2602. bool IsShared, bool IsWhole) {
  2603. // Wrap any static runtimes that must be forced into executable in
  2604. // whole-archive.
  2605. if (IsWhole) CmdArgs.push_back("-whole-archive");
  2606. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
  2607. if (IsWhole) CmdArgs.push_back("-no-whole-archive");
  2608. }
  2609. // Tries to use a file with the list of dynamic symbols that need to be exported
  2610. // from the runtime library. Returns true if the file was found.
  2611. static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
  2612. ArgStringList &CmdArgs,
  2613. StringRef Sanitizer) {
  2614. SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
  2615. if (llvm::sys::fs::exists(SanRT + ".syms")) {
  2616. CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
  2617. return true;
  2618. }
  2619. return false;
  2620. }
  2621. static void linkSanitizerRuntimeDeps(const ToolChain &TC,
  2622. ArgStringList &CmdArgs) {
  2623. // Force linking against the system libraries sanitizers depends on
  2624. // (see PR15823 why this is necessary).
  2625. CmdArgs.push_back("--no-as-needed");
  2626. CmdArgs.push_back("-lpthread");
  2627. CmdArgs.push_back("-lrt");
  2628. CmdArgs.push_back("-lm");
  2629. // There's no libdl on FreeBSD.
  2630. if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
  2631. CmdArgs.push_back("-ldl");
  2632. }
  2633. static void
  2634. collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2635. SmallVectorImpl<StringRef> &SharedRuntimes,
  2636. SmallVectorImpl<StringRef> &StaticRuntimes,
  2637. SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
  2638. SmallVectorImpl<StringRef> &HelperStaticRuntimes,
  2639. SmallVectorImpl<StringRef> &RequiredSymbols) {
  2640. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  2641. // Collect shared runtimes.
  2642. if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
  2643. SharedRuntimes.push_back("asan");
  2644. }
  2645. // The stats_client library is also statically linked into DSOs.
  2646. if (SanArgs.needsStatsRt())
  2647. StaticRuntimes.push_back("stats_client");
  2648. // Collect static runtimes.
  2649. if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
  2650. // Don't link static runtimes into DSOs or if compiling for Android.
  2651. return;
  2652. }
  2653. if (SanArgs.needsAsanRt()) {
  2654. if (SanArgs.needsSharedAsanRt()) {
  2655. HelperStaticRuntimes.push_back("asan-preinit");
  2656. } else {
  2657. StaticRuntimes.push_back("asan");
  2658. if (SanArgs.linkCXXRuntimes())
  2659. StaticRuntimes.push_back("asan_cxx");
  2660. }
  2661. }
  2662. if (SanArgs.needsDfsanRt())
  2663. StaticRuntimes.push_back("dfsan");
  2664. if (SanArgs.needsLsanRt())
  2665. StaticRuntimes.push_back("lsan");
  2666. if (SanArgs.needsMsanRt()) {
  2667. StaticRuntimes.push_back("msan");
  2668. if (SanArgs.linkCXXRuntimes())
  2669. StaticRuntimes.push_back("msan_cxx");
  2670. }
  2671. if (SanArgs.needsTsanRt()) {
  2672. StaticRuntimes.push_back("tsan");
  2673. if (SanArgs.linkCXXRuntimes())
  2674. StaticRuntimes.push_back("tsan_cxx");
  2675. }
  2676. if (SanArgs.needsUbsanRt()) {
  2677. StaticRuntimes.push_back("ubsan_standalone");
  2678. if (SanArgs.linkCXXRuntimes())
  2679. StaticRuntimes.push_back("ubsan_standalone_cxx");
  2680. }
  2681. if (SanArgs.needsSafeStackRt())
  2682. StaticRuntimes.push_back("safestack");
  2683. if (SanArgs.needsCfiRt())
  2684. StaticRuntimes.push_back("cfi");
  2685. if (SanArgs.needsCfiDiagRt()) {
  2686. StaticRuntimes.push_back("cfi_diag");
  2687. if (SanArgs.linkCXXRuntimes())
  2688. StaticRuntimes.push_back("ubsan_standalone_cxx");
  2689. }
  2690. if (SanArgs.needsStatsRt()) {
  2691. NonWholeStaticRuntimes.push_back("stats");
  2692. RequiredSymbols.push_back("__sanitizer_stats_register");
  2693. }
  2694. if (SanArgs.needsEsanRt())
  2695. StaticRuntimes.push_back("esan");
  2696. }
  2697. // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
  2698. // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
  2699. static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2700. ArgStringList &CmdArgs) {
  2701. SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
  2702. NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
  2703. collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
  2704. NonWholeStaticRuntimes, HelperStaticRuntimes,
  2705. RequiredSymbols);
  2706. for (auto RT : SharedRuntimes)
  2707. addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
  2708. for (auto RT : HelperStaticRuntimes)
  2709. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  2710. bool AddExportDynamic = false;
  2711. for (auto RT : StaticRuntimes) {
  2712. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  2713. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  2714. }
  2715. for (auto RT : NonWholeStaticRuntimes) {
  2716. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
  2717. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  2718. }
  2719. for (auto S : RequiredSymbols) {
  2720. CmdArgs.push_back("-u");
  2721. CmdArgs.push_back(Args.MakeArgString(S));
  2722. }
  2723. // If there is a static runtime with no dynamic list, force all the symbols
  2724. // to be dynamic to be sure we export sanitizer interface functions.
  2725. if (AddExportDynamic)
  2726. CmdArgs.push_back("-export-dynamic");
  2727. return !StaticRuntimes.empty();
  2728. }
  2729. static bool areOptimizationsEnabled(const ArgList &Args) {
  2730. // Find the last -O arg and see if it is non-zero.
  2731. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2732. return !A->getOption().matches(options::OPT_O0);
  2733. // Defaults to -O0.
  2734. return false;
  2735. }
  2736. static bool shouldUseFramePointerForTarget(const ArgList &Args,
  2737. const llvm::Triple &Triple) {
  2738. switch (Triple.getArch()) {
  2739. case llvm::Triple::xcore:
  2740. case llvm::Triple::wasm32:
  2741. case llvm::Triple::wasm64:
  2742. // XCore never wants frame pointers, regardless of OS.
  2743. // WebAssembly never wants frame pointers.
  2744. return false;
  2745. default:
  2746. break;
  2747. }
  2748. if (Triple.isOSLinux()) {
  2749. switch (Triple.getArch()) {
  2750. // Don't use a frame pointer on linux if optimizing for certain targets.
  2751. case llvm::Triple::mips64:
  2752. case llvm::Triple::mips64el:
  2753. case llvm::Triple::mips:
  2754. case llvm::Triple::mipsel:
  2755. case llvm::Triple::systemz:
  2756. case llvm::Triple::x86:
  2757. case llvm::Triple::x86_64:
  2758. return !areOptimizationsEnabled(Args);
  2759. default:
  2760. return true;
  2761. }
  2762. }
  2763. if (Triple.isOSWindows()) {
  2764. switch (Triple.getArch()) {
  2765. case llvm::Triple::x86:
  2766. return !areOptimizationsEnabled(Args);
  2767. case llvm::Triple::x86_64:
  2768. return Triple.isOSBinFormatMachO();
  2769. case llvm::Triple::arm:
  2770. case llvm::Triple::thumb:
  2771. // Windows on ARM builds with FPO disabled to aid fast stack walking
  2772. return true;
  2773. default:
  2774. // All other supported Windows ISAs use xdata unwind information, so frame
  2775. // pointers are not generally useful.
  2776. return false;
  2777. }
  2778. }
  2779. return true;
  2780. }
  2781. static bool shouldUseFramePointer(const ArgList &Args,
  2782. const llvm::Triple &Triple) {
  2783. if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
  2784. options::OPT_fomit_frame_pointer))
  2785. return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
  2786. if (Args.hasArg(options::OPT_pg))
  2787. return true;
  2788. return shouldUseFramePointerForTarget(Args, Triple);
  2789. }
  2790. static bool shouldUseLeafFramePointer(const ArgList &Args,
  2791. const llvm::Triple &Triple) {
  2792. if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
  2793. options::OPT_momit_leaf_frame_pointer))
  2794. return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
  2795. if (Args.hasArg(options::OPT_pg))
  2796. return true;
  2797. if (Triple.isPS4CPU())
  2798. return false;
  2799. return shouldUseFramePointerForTarget(Args, Triple);
  2800. }
  2801. /// Add a CC1 option to specify the debug compilation directory.
  2802. static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
  2803. SmallString<128> cwd;
  2804. if (!llvm::sys::fs::current_path(cwd)) {
  2805. CmdArgs.push_back("-fdebug-compilation-dir");
  2806. CmdArgs.push_back(Args.MakeArgString(cwd));
  2807. }
  2808. }
  2809. static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
  2810. Arg *FinalOutput = Args.getLastArg(options::OPT_o);
  2811. if (FinalOutput && Args.hasArg(options::OPT_c)) {
  2812. SmallString<128> T(FinalOutput->getValue());
  2813. llvm::sys::path::replace_extension(T, "dwo");
  2814. return Args.MakeArgString(T);
  2815. } else {
  2816. // Use the compilation dir.
  2817. SmallString<128> T(
  2818. Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
  2819. SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
  2820. llvm::sys::path::replace_extension(F, "dwo");
  2821. T += F;
  2822. return Args.MakeArgString(F);
  2823. }
  2824. }
  2825. static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
  2826. const JobAction &JA, const ArgList &Args,
  2827. const InputInfo &Output, const char *OutFile) {
  2828. ArgStringList ExtractArgs;
  2829. ExtractArgs.push_back("--extract-dwo");
  2830. ArgStringList StripArgs;
  2831. StripArgs.push_back("--strip-dwo");
  2832. // Grabbing the output of the earlier compile step.
  2833. StripArgs.push_back(Output.getFilename());
  2834. ExtractArgs.push_back(Output.getFilename());
  2835. ExtractArgs.push_back(OutFile);
  2836. const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
  2837. InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
  2838. // First extract the dwo sections.
  2839. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
  2840. // Then remove them from the original .o file.
  2841. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
  2842. }
  2843. /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
  2844. /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
  2845. static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
  2846. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  2847. if (A->getOption().matches(options::OPT_O4) ||
  2848. A->getOption().matches(options::OPT_Ofast))
  2849. return true;
  2850. if (A->getOption().matches(options::OPT_O0))
  2851. return false;
  2852. assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
  2853. // Vectorize -Os.
  2854. StringRef S(A->getValue());
  2855. if (S == "s")
  2856. return true;
  2857. // Don't vectorize -Oz, unless it's the slp vectorizer.
  2858. if (S == "z")
  2859. return isSlpVec;
  2860. unsigned OptLevel = 0;
  2861. if (S.getAsInteger(10, OptLevel))
  2862. return false;
  2863. return OptLevel > 1;
  2864. }
  2865. return false;
  2866. }
  2867. /// Add -x lang to \p CmdArgs for \p Input.
  2868. static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
  2869. ArgStringList &CmdArgs) {
  2870. // When using -verify-pch, we don't want to provide the type
  2871. // 'precompiled-header' if it was inferred from the file extension
  2872. if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
  2873. return;
  2874. CmdArgs.push_back("-x");
  2875. if (Args.hasArg(options::OPT_rewrite_objc))
  2876. CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
  2877. else
  2878. CmdArgs.push_back(types::getTypeName(Input.getType()));
  2879. }
  2880. static VersionTuple getMSCompatibilityVersion(unsigned Version) {
  2881. if (Version < 100)
  2882. return VersionTuple(Version);
  2883. if (Version < 10000)
  2884. return VersionTuple(Version / 100, Version % 100);
  2885. unsigned Build = 0, Factor = 1;
  2886. for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
  2887. Build = Build + (Version % 10) * Factor;
  2888. return VersionTuple(Version / 100, Version % 100, Build);
  2889. }
  2890. // Claim options we don't want to warn if they are unused. We do this for
  2891. // options that build systems might add but are unused when assembling or only
  2892. // running the preprocessor for example.
  2893. static void claimNoWarnArgs(const ArgList &Args) {
  2894. // Don't warn about unused -f(no-)?lto. This can happen when we're
  2895. // preprocessing, precompiling or assembling.
  2896. Args.ClaimAllArgs(options::OPT_flto_EQ);
  2897. Args.ClaimAllArgs(options::OPT_flto);
  2898. Args.ClaimAllArgs(options::OPT_fno_lto);
  2899. }
  2900. static void appendUserToPath(SmallVectorImpl<char> &Result) {
  2901. #ifdef LLVM_ON_UNIX
  2902. const char *Username = getenv("LOGNAME");
  2903. #else
  2904. const char *Username = getenv("USERNAME");
  2905. #endif
  2906. if (Username) {
  2907. // Validate that LoginName can be used in a path, and get its length.
  2908. size_t Len = 0;
  2909. for (const char *P = Username; *P; ++P, ++Len) {
  2910. if (!isAlphanumeric(*P) && *P != '_') {
  2911. Username = nullptr;
  2912. break;
  2913. }
  2914. }
  2915. if (Username && Len > 0) {
  2916. Result.append(Username, Username + Len);
  2917. return;
  2918. }
  2919. }
  2920. // Fallback to user id.
  2921. #ifdef LLVM_ON_UNIX
  2922. std::string UID = llvm::utostr(getuid());
  2923. #else
  2924. // FIXME: Windows seems to have an 'SID' that might work.
  2925. std::string UID = "9999";
  2926. #endif
  2927. Result.append(UID.begin(), UID.end());
  2928. }
  2929. VersionTuple visualstudio::getMSVCVersion(const Driver *D,
  2930. const llvm::Triple &Triple,
  2931. const llvm::opt::ArgList &Args,
  2932. bool IsWindowsMSVC) {
  2933. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  2934. IsWindowsMSVC) ||
  2935. Args.hasArg(options::OPT_fmsc_version) ||
  2936. Args.hasArg(options::OPT_fms_compatibility_version)) {
  2937. const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
  2938. const Arg *MSCompatibilityVersion =
  2939. Args.getLastArg(options::OPT_fms_compatibility_version);
  2940. if (MSCVersion && MSCompatibilityVersion) {
  2941. if (D)
  2942. D->Diag(diag::err_drv_argument_not_allowed_with)
  2943. << MSCVersion->getAsString(Args)
  2944. << MSCompatibilityVersion->getAsString(Args);
  2945. return VersionTuple();
  2946. }
  2947. if (MSCompatibilityVersion) {
  2948. VersionTuple MSVT;
  2949. if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
  2950. D->Diag(diag::err_drv_invalid_value)
  2951. << MSCompatibilityVersion->getAsString(Args)
  2952. << MSCompatibilityVersion->getValue();
  2953. return MSVT;
  2954. }
  2955. if (MSCVersion) {
  2956. unsigned Version = 0;
  2957. if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
  2958. D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
  2959. << MSCVersion->getValue();
  2960. return getMSCompatibilityVersion(Version);
  2961. }
  2962. unsigned Major, Minor, Micro;
  2963. Triple.getEnvironmentVersion(Major, Minor, Micro);
  2964. if (Major || Minor || Micro)
  2965. return VersionTuple(Major, Minor, Micro);
  2966. // FIXME: Consider bumping this to 19 (MSVC2015) soon.
  2967. return VersionTuple(18);
  2968. }
  2969. return VersionTuple();
  2970. }
  2971. static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
  2972. const InputInfo &Output, const ArgList &Args,
  2973. ArgStringList &CmdArgs) {
  2974. auto *ProfileGenerateArg = Args.getLastArg(
  2975. options::OPT_fprofile_instr_generate,
  2976. options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
  2977. options::OPT_fprofile_generate_EQ,
  2978. options::OPT_fno_profile_instr_generate);
  2979. if (ProfileGenerateArg &&
  2980. ProfileGenerateArg->getOption().matches(
  2981. options::OPT_fno_profile_instr_generate))
  2982. ProfileGenerateArg = nullptr;
  2983. auto *ProfileUseArg = Args.getLastArg(
  2984. options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
  2985. options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
  2986. options::OPT_fno_profile_instr_use);
  2987. if (ProfileUseArg &&
  2988. ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
  2989. ProfileUseArg = nullptr;
  2990. if (ProfileGenerateArg && ProfileUseArg)
  2991. D.Diag(diag::err_drv_argument_not_allowed_with)
  2992. << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
  2993. if (ProfileGenerateArg) {
  2994. if (ProfileGenerateArg->getOption().matches(
  2995. options::OPT_fprofile_instr_generate_EQ))
  2996. CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
  2997. ProfileGenerateArg->getValue()));
  2998. else if (ProfileGenerateArg->getOption().matches(
  2999. options::OPT_fprofile_generate_EQ)) {
  3000. SmallString<128> Path(ProfileGenerateArg->getValue());
  3001. llvm::sys::path::append(Path, "default.profraw");
  3002. CmdArgs.push_back(
  3003. Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
  3004. }
  3005. // The default is to use Clang Instrumentation.
  3006. CmdArgs.push_back("-fprofile-instrument=clang");
  3007. }
  3008. if (ProfileUseArg) {
  3009. if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
  3010. CmdArgs.push_back(Args.MakeArgString(
  3011. Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
  3012. else if ((ProfileUseArg->getOption().matches(
  3013. options::OPT_fprofile_use_EQ) ||
  3014. ProfileUseArg->getOption().matches(
  3015. options::OPT_fprofile_instr_use))) {
  3016. SmallString<128> Path(
  3017. ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
  3018. if (Path.empty() || llvm::sys::fs::is_directory(Path))
  3019. llvm::sys::path::append(Path, "default.profdata");
  3020. CmdArgs.push_back(
  3021. Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
  3022. }
  3023. }
  3024. if (Args.hasArg(options::OPT_ftest_coverage) ||
  3025. Args.hasArg(options::OPT_coverage))
  3026. CmdArgs.push_back("-femit-coverage-notes");
  3027. if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  3028. false) ||
  3029. Args.hasArg(options::OPT_coverage))
  3030. CmdArgs.push_back("-femit-coverage-data");
  3031. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  3032. options::OPT_fno_coverage_mapping, false) &&
  3033. !ProfileGenerateArg)
  3034. D.Diag(diag::err_drv_argument_only_allowed_with)
  3035. << "-fcoverage-mapping"
  3036. << "-fprofile-instr-generate";
  3037. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  3038. options::OPT_fno_coverage_mapping, false))
  3039. CmdArgs.push_back("-fcoverage-mapping");
  3040. if (C.getArgs().hasArg(options::OPT_c) ||
  3041. C.getArgs().hasArg(options::OPT_S)) {
  3042. if (Output.isFilename()) {
  3043. CmdArgs.push_back("-coverage-file");
  3044. SmallString<128> CoverageFilename;
  3045. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
  3046. CoverageFilename = FinalOutput->getValue();
  3047. } else {
  3048. CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
  3049. }
  3050. if (llvm::sys::path::is_relative(CoverageFilename)) {
  3051. SmallString<128> Pwd;
  3052. if (!llvm::sys::fs::current_path(Pwd)) {
  3053. llvm::sys::path::append(Pwd, CoverageFilename);
  3054. CoverageFilename.swap(Pwd);
  3055. }
  3056. }
  3057. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  3058. }
  3059. }
  3060. }
  3061. static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
  3062. ArgStringList &CmdArgs) {
  3063. if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  3064. false) ||
  3065. Args.hasFlag(options::OPT_fprofile_generate,
  3066. options::OPT_fno_profile_instr_generate, false) ||
  3067. Args.hasFlag(options::OPT_fprofile_generate_EQ,
  3068. options::OPT_fno_profile_instr_generate, false) ||
  3069. Args.hasFlag(options::OPT_fprofile_instr_generate,
  3070. options::OPT_fno_profile_instr_generate, false) ||
  3071. Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
  3072. options::OPT_fno_profile_instr_generate, false) ||
  3073. Args.hasArg(options::OPT_fcreate_profile) ||
  3074. Args.hasArg(options::OPT_coverage)))
  3075. CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
  3076. }
  3077. /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
  3078. /// smooshes them together with platform defaults, to decide whether
  3079. /// this compile should be using PIC mode or not. Returns a tuple of
  3080. /// (RelocationModel, PICLevel, IsPIE).
  3081. static std::tuple<llvm::Reloc::Model, unsigned, bool>
  3082. ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
  3083. const ArgList &Args) {
  3084. // FIXME: why does this code...and so much everywhere else, use both
  3085. // ToolChain.getTriple() and Triple?
  3086. bool PIE = ToolChain.isPIEDefault();
  3087. bool PIC = PIE || ToolChain.isPICDefault();
  3088. // The Darwin/MachO default to use PIC does not apply when using -static.
  3089. if (ToolChain.getTriple().isOSBinFormatMachO() &&
  3090. Args.hasArg(options::OPT_static))
  3091. PIE = PIC = false;
  3092. bool IsPICLevelTwo = PIC;
  3093. bool KernelOrKext =
  3094. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  3095. // Android-specific defaults for PIC/PIE
  3096. if (ToolChain.getTriple().isAndroid()) {
  3097. switch (ToolChain.getArch()) {
  3098. case llvm::Triple::arm:
  3099. case llvm::Triple::armeb:
  3100. case llvm::Triple::thumb:
  3101. case llvm::Triple::thumbeb:
  3102. case llvm::Triple::aarch64:
  3103. case llvm::Triple::mips:
  3104. case llvm::Triple::mipsel:
  3105. case llvm::Triple::mips64:
  3106. case llvm::Triple::mips64el:
  3107. PIC = true; // "-fpic"
  3108. break;
  3109. case llvm::Triple::x86:
  3110. case llvm::Triple::x86_64:
  3111. PIC = true; // "-fPIC"
  3112. IsPICLevelTwo = true;
  3113. break;
  3114. default:
  3115. break;
  3116. }
  3117. }
  3118. // OpenBSD-specific defaults for PIE
  3119. if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
  3120. switch (ToolChain.getArch()) {
  3121. case llvm::Triple::mips64:
  3122. case llvm::Triple::mips64el:
  3123. case llvm::Triple::sparcel:
  3124. case llvm::Triple::x86:
  3125. case llvm::Triple::x86_64:
  3126. IsPICLevelTwo = false; // "-fpie"
  3127. break;
  3128. case llvm::Triple::ppc:
  3129. case llvm::Triple::sparc:
  3130. case llvm::Triple::sparcv9:
  3131. IsPICLevelTwo = true; // "-fPIE"
  3132. break;
  3133. default:
  3134. break;
  3135. }
  3136. }
  3137. // The last argument relating to either PIC or PIE wins, and no
  3138. // other argument is used. If the last argument is any flavor of the
  3139. // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
  3140. // option implicitly enables PIC at the same level.
  3141. Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
  3142. options::OPT_fpic, options::OPT_fno_pic,
  3143. options::OPT_fPIE, options::OPT_fno_PIE,
  3144. options::OPT_fpie, options::OPT_fno_pie);
  3145. // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
  3146. // is forced, then neither PIC nor PIE flags will have no effect.
  3147. if (!ToolChain.isPICDefaultForced()) {
  3148. if (LastPICArg) {
  3149. Option O = LastPICArg->getOption();
  3150. if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
  3151. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
  3152. PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
  3153. PIC =
  3154. PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
  3155. IsPICLevelTwo =
  3156. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
  3157. } else {
  3158. PIE = PIC = false;
  3159. if (Triple.isPS4CPU()) {
  3160. Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
  3161. StringRef Model = ModelArg ? ModelArg->getValue() : "";
  3162. if (Model != "kernel") {
  3163. PIC = true;
  3164. ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
  3165. << LastPICArg->getSpelling();
  3166. }
  3167. }
  3168. }
  3169. }
  3170. }
  3171. // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
  3172. // PIC level would've been set to level 1, force it back to level 2 PIC
  3173. // instead.
  3174. if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
  3175. IsPICLevelTwo |= ToolChain.isPICDefault();
  3176. // This kernel flags are a trump-card: they will disable PIC/PIE
  3177. // generation, independent of the argument order.
  3178. if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  3179. !Triple.isWatchOS()))
  3180. PIC = PIE = false;
  3181. if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
  3182. // This is a very special mode. It trumps the other modes, almost no one
  3183. // uses it, and it isn't even valid on any OS but Darwin.
  3184. if (!ToolChain.getTriple().isOSDarwin())
  3185. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  3186. << A->getSpelling() << ToolChain.getTriple().str();
  3187. // FIXME: Warn when this flag trumps some other PIC or PIE flag.
  3188. // Only a forced PIC mode can cause the actual compile to have PIC defines
  3189. // etc., no flags are sufficient. This behavior was selected to closely
  3190. // match that of llvm-gcc and Apple GCC before that.
  3191. PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
  3192. return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
  3193. }
  3194. if (PIC)
  3195. return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
  3196. return std::make_tuple(llvm::Reloc::Static, 0, false);
  3197. }
  3198. static const char *RelocationModelName(llvm::Reloc::Model Model) {
  3199. switch (Model) {
  3200. case llvm::Reloc::Default:
  3201. return nullptr;
  3202. case llvm::Reloc::Static:
  3203. return "static";
  3204. case llvm::Reloc::PIC_:
  3205. return "pic";
  3206. case llvm::Reloc::DynamicNoPIC:
  3207. return "dynamic-no-pic";
  3208. }
  3209. llvm_unreachable("Unknown Reloc::Model kind");
  3210. }
  3211. static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
  3212. ArgStringList &CmdArgs) {
  3213. llvm::Reloc::Model RelocationModel;
  3214. unsigned PICLevel;
  3215. bool IsPIE;
  3216. std::tie(RelocationModel, PICLevel, IsPIE) =
  3217. ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
  3218. if (RelocationModel != llvm::Reloc::Static)
  3219. CmdArgs.push_back("-KPIC");
  3220. }
  3221. void Clang::ConstructJob(Compilation &C, const JobAction &JA,
  3222. const InputInfo &Output, const InputInfoList &Inputs,
  3223. const ArgList &Args, const char *LinkingOutput) const {
  3224. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  3225. const llvm::Triple Triple(TripleStr);
  3226. bool KernelOrKext =
  3227. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  3228. const Driver &D = getToolChain().getDriver();
  3229. ArgStringList CmdArgs;
  3230. bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
  3231. bool IsWindowsCygnus =
  3232. getToolChain().getTriple().isWindowsCygwinEnvironment();
  3233. bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
  3234. bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
  3235. // Check number of inputs for sanity. We need at least one input.
  3236. assert(Inputs.size() >= 1 && "Must have at least one input.");
  3237. const InputInfo &Input = Inputs[0];
  3238. // CUDA compilation may have multiple inputs (source file + results of
  3239. // device-side compilations). All other jobs are expected to have exactly one
  3240. // input.
  3241. bool IsCuda = types::isCuda(Input.getType());
  3242. assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
  3243. // Invoke ourselves in -cc1 mode.
  3244. //
  3245. // FIXME: Implement custom jobs for internal actions.
  3246. CmdArgs.push_back("-cc1");
  3247. // Add the "effective" target triple.
  3248. CmdArgs.push_back("-triple");
  3249. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  3250. const ToolChain *AuxToolChain = nullptr;
  3251. if (IsCuda) {
  3252. // FIXME: We need a (better) way to pass information about
  3253. // particular compilation pass we're constructing here. For now we
  3254. // can check which toolchain we're using and pick the other one to
  3255. // extract the triple.
  3256. if (&getToolChain() == C.getCudaDeviceToolChain())
  3257. AuxToolChain = C.getCudaHostToolChain();
  3258. else if (&getToolChain() == C.getCudaHostToolChain())
  3259. AuxToolChain = C.getCudaDeviceToolChain();
  3260. else
  3261. llvm_unreachable("Can't figure out CUDA compilation mode.");
  3262. assert(AuxToolChain != nullptr && "No aux toolchain.");
  3263. CmdArgs.push_back("-aux-triple");
  3264. CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
  3265. }
  3266. if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
  3267. Triple.getArch() == llvm::Triple::thumb)) {
  3268. unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
  3269. unsigned Version;
  3270. Triple.getArchName().substr(Offset).getAsInteger(10, Version);
  3271. if (Version < 7)
  3272. D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
  3273. << TripleStr;
  3274. }
  3275. // Push all default warning arguments that are specific to
  3276. // the given target. These come before user provided warning options
  3277. // are provided.
  3278. getToolChain().addClangWarningOptions(CmdArgs);
  3279. // Select the appropriate action.
  3280. RewriteKind rewriteKind = RK_None;
  3281. if (isa<AnalyzeJobAction>(JA)) {
  3282. assert(JA.getType() == types::TY_Plist && "Invalid output type.");
  3283. CmdArgs.push_back("-analyze");
  3284. } else if (isa<MigrateJobAction>(JA)) {
  3285. CmdArgs.push_back("-migrate");
  3286. } else if (isa<PreprocessJobAction>(JA)) {
  3287. if (Output.getType() == types::TY_Dependencies)
  3288. CmdArgs.push_back("-Eonly");
  3289. else {
  3290. CmdArgs.push_back("-E");
  3291. if (Args.hasArg(options::OPT_rewrite_objc) &&
  3292. !Args.hasArg(options::OPT_g_Group))
  3293. CmdArgs.push_back("-P");
  3294. }
  3295. } else if (isa<AssembleJobAction>(JA)) {
  3296. CmdArgs.push_back("-emit-obj");
  3297. CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
  3298. // Also ignore explicit -force_cpusubtype_ALL option.
  3299. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  3300. } else if (isa<PrecompileJobAction>(JA)) {
  3301. // Use PCH if the user requested it.
  3302. bool UsePCH = D.CCCUsePCH;
  3303. if (JA.getType() == types::TY_Nothing)
  3304. CmdArgs.push_back("-fsyntax-only");
  3305. else if (UsePCH)
  3306. CmdArgs.push_back("-emit-pch");
  3307. else
  3308. CmdArgs.push_back("-emit-pth");
  3309. } else if (isa<VerifyPCHJobAction>(JA)) {
  3310. CmdArgs.push_back("-verify-pch");
  3311. } else {
  3312. assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
  3313. "Invalid action for clang tool.");
  3314. if (JA.getType() == types::TY_Nothing) {
  3315. CmdArgs.push_back("-fsyntax-only");
  3316. } else if (JA.getType() == types::TY_LLVM_IR ||
  3317. JA.getType() == types::TY_LTO_IR) {
  3318. CmdArgs.push_back("-emit-llvm");
  3319. } else if (JA.getType() == types::TY_LLVM_BC ||
  3320. JA.getType() == types::TY_LTO_BC) {
  3321. CmdArgs.push_back("-emit-llvm-bc");
  3322. } else if (JA.getType() == types::TY_PP_Asm) {
  3323. CmdArgs.push_back("-S");
  3324. } else if (JA.getType() == types::TY_AST) {
  3325. CmdArgs.push_back("-emit-pch");
  3326. } else if (JA.getType() == types::TY_ModuleFile) {
  3327. CmdArgs.push_back("-module-file-info");
  3328. } else if (JA.getType() == types::TY_RewrittenObjC) {
  3329. CmdArgs.push_back("-rewrite-objc");
  3330. rewriteKind = RK_NonFragile;
  3331. } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
  3332. CmdArgs.push_back("-rewrite-objc");
  3333. rewriteKind = RK_Fragile;
  3334. } else {
  3335. assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
  3336. }
  3337. // Preserve use-list order by default when emitting bitcode, so that
  3338. // loading the bitcode up in 'opt' or 'llc' and running passes gives the
  3339. // same result as running passes here. For LTO, we don't need to preserve
  3340. // the use-list order, since serialization to bitcode is part of the flow.
  3341. if (JA.getType() == types::TY_LLVM_BC)
  3342. CmdArgs.push_back("-emit-llvm-uselists");
  3343. if (D.isUsingLTO())
  3344. Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
  3345. }
  3346. if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
  3347. if (!types::isLLVMIR(Input.getType()))
  3348. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  3349. << "-x ir";
  3350. Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
  3351. }
  3352. // Embed-bitcode option.
  3353. if (C.getDriver().embedBitcodeEnabled() &&
  3354. (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
  3355. // Add flags implied by -fembed-bitcode.
  3356. CmdArgs.push_back("-fembed-bitcode");
  3357. // Disable all llvm IR level optimizations.
  3358. CmdArgs.push_back("-disable-llvm-optzns");
  3359. }
  3360. if (C.getDriver().embedBitcodeMarkerOnly())
  3361. CmdArgs.push_back("-fembed-bitcode-marker");
  3362. // We normally speed up the clang process a bit by skipping destructors at
  3363. // exit, but when we're generating diagnostics we can rely on some of the
  3364. // cleanup.
  3365. if (!C.isForDiagnostics())
  3366. CmdArgs.push_back("-disable-free");
  3367. // Disable the verification pass in -asserts builds.
  3368. #ifdef NDEBUG
  3369. CmdArgs.push_back("-disable-llvm-verifier");
  3370. // Discard LLVM value names in -asserts builds.
  3371. CmdArgs.push_back("-discard-value-names");
  3372. #endif
  3373. // Set the main file name, so that debug info works even with
  3374. // -save-temps.
  3375. CmdArgs.push_back("-main-file-name");
  3376. CmdArgs.push_back(getBaseInputName(Args, Input));
  3377. // Some flags which affect the language (via preprocessor
  3378. // defines).
  3379. if (Args.hasArg(options::OPT_static))
  3380. CmdArgs.push_back("-static-define");
  3381. if (isa<AnalyzeJobAction>(JA)) {
  3382. // Enable region store model by default.
  3383. CmdArgs.push_back("-analyzer-store=region");
  3384. // Treat blocks as analysis entry points.
  3385. CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
  3386. CmdArgs.push_back("-analyzer-eagerly-assume");
  3387. // Add default argument set.
  3388. if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
  3389. CmdArgs.push_back("-analyzer-checker=core");
  3390. if (!IsWindowsMSVC) {
  3391. CmdArgs.push_back("-analyzer-checker=unix");
  3392. } else {
  3393. // Enable "unix" checkers that also work on Windows.
  3394. CmdArgs.push_back("-analyzer-checker=unix.API");
  3395. CmdArgs.push_back("-analyzer-checker=unix.Malloc");
  3396. CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
  3397. CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
  3398. CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
  3399. CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
  3400. }
  3401. // Disable some unix checkers for PS4.
  3402. if (IsPS4CPU) {
  3403. CmdArgs.push_back("-analyzer-disable-checker=unix.API");
  3404. CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
  3405. }
  3406. if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
  3407. CmdArgs.push_back("-analyzer-checker=osx");
  3408. CmdArgs.push_back("-analyzer-checker=deadcode");
  3409. if (types::isCXX(Input.getType()))
  3410. CmdArgs.push_back("-analyzer-checker=cplusplus");
  3411. if (!IsPS4CPU) {
  3412. CmdArgs.push_back(
  3413. "-analyzer-checker=security.insecureAPI.UncheckedReturn");
  3414. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
  3415. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
  3416. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
  3417. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
  3418. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
  3419. }
  3420. // Default nullability checks.
  3421. CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
  3422. CmdArgs.push_back(
  3423. "-analyzer-checker=nullability.NullReturnedFromNonnull");
  3424. }
  3425. // Set the output format. The default is plist, for (lame) historical
  3426. // reasons.
  3427. CmdArgs.push_back("-analyzer-output");
  3428. if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
  3429. CmdArgs.push_back(A->getValue());
  3430. else
  3431. CmdArgs.push_back("plist");
  3432. // Disable the presentation of standard compiler warnings when
  3433. // using --analyze. We only want to show static analyzer diagnostics
  3434. // or frontend errors.
  3435. CmdArgs.push_back("-w");
  3436. // Add -Xanalyzer arguments when running as analyzer.
  3437. Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
  3438. }
  3439. CheckCodeGenerationOptions(D, Args);
  3440. llvm::Reloc::Model RelocationModel;
  3441. unsigned PICLevel;
  3442. bool IsPIE;
  3443. std::tie(RelocationModel, PICLevel, IsPIE) =
  3444. ParsePICArgs(getToolChain(), Triple, Args);
  3445. const char *RMName = RelocationModelName(RelocationModel);
  3446. if (RMName) {
  3447. CmdArgs.push_back("-mrelocation-model");
  3448. CmdArgs.push_back(RMName);
  3449. }
  3450. if (PICLevel > 0) {
  3451. CmdArgs.push_back("-pic-level");
  3452. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3453. if (IsPIE) {
  3454. CmdArgs.push_back("-pie-level");
  3455. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3456. }
  3457. }
  3458. if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
  3459. CmdArgs.push_back("-meabi");
  3460. CmdArgs.push_back(A->getValue());
  3461. }
  3462. CmdArgs.push_back("-mthread-model");
  3463. if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
  3464. CmdArgs.push_back(A->getValue());
  3465. else
  3466. CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
  3467. Args.AddLastArg(CmdArgs, options::OPT_fveclib);
  3468. if (!Args.hasFlag(options::OPT_fmerge_all_constants,
  3469. options::OPT_fno_merge_all_constants))
  3470. CmdArgs.push_back("-fno-merge-all-constants");
  3471. // LLVM Code Generator Options.
  3472. if (Args.hasArg(options::OPT_frewrite_map_file) ||
  3473. Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
  3474. for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
  3475. options::OPT_frewrite_map_file_EQ)) {
  3476. CmdArgs.push_back("-frewrite-map-file");
  3477. CmdArgs.push_back(A->getValue());
  3478. A->claim();
  3479. }
  3480. }
  3481. if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
  3482. StringRef v = A->getValue();
  3483. CmdArgs.push_back("-mllvm");
  3484. CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
  3485. A->claim();
  3486. }
  3487. if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
  3488. true))
  3489. CmdArgs.push_back("-fno-jump-tables");
  3490. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  3491. CmdArgs.push_back("-mregparm");
  3492. CmdArgs.push_back(A->getValue());
  3493. }
  3494. if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
  3495. options::OPT_freg_struct_return)) {
  3496. if (getToolChain().getArch() != llvm::Triple::x86) {
  3497. D.Diag(diag::err_drv_unsupported_opt_for_target)
  3498. << A->getSpelling() << getToolChain().getTriple().str();
  3499. } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
  3500. CmdArgs.push_back("-fpcc-struct-return");
  3501. } else {
  3502. assert(A->getOption().matches(options::OPT_freg_struct_return));
  3503. CmdArgs.push_back("-freg-struct-return");
  3504. }
  3505. }
  3506. if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
  3507. CmdArgs.push_back("-mrtd");
  3508. if (shouldUseFramePointer(Args, getToolChain().getTriple()))
  3509. CmdArgs.push_back("-mdisable-fp-elim");
  3510. if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
  3511. options::OPT_fno_zero_initialized_in_bss))
  3512. CmdArgs.push_back("-mno-zero-initialized-in-bss");
  3513. bool OFastEnabled = isOptimizationLevelFast(Args);
  3514. // If -Ofast is the optimization level, then -fstrict-aliasing should be
  3515. // enabled. This alias option is being used to simplify the hasFlag logic.
  3516. OptSpecifier StrictAliasingAliasOption =
  3517. OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
  3518. // We turn strict aliasing off by default if we're in CL mode, since MSVC
  3519. // doesn't do any TBAA.
  3520. bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
  3521. if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
  3522. options::OPT_fno_strict_aliasing, TBAAOnByDefault))
  3523. CmdArgs.push_back("-relaxed-aliasing");
  3524. if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
  3525. options::OPT_fno_struct_path_tbaa))
  3526. CmdArgs.push_back("-no-struct-path-tbaa");
  3527. if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
  3528. false))
  3529. CmdArgs.push_back("-fstrict-enums");
  3530. if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
  3531. options::OPT_fno_strict_vtable_pointers,
  3532. false))
  3533. CmdArgs.push_back("-fstrict-vtable-pointers");
  3534. if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
  3535. options::OPT_fno_optimize_sibling_calls))
  3536. CmdArgs.push_back("-mdisable-tail-calls");
  3537. // Handle segmented stacks.
  3538. if (Args.hasArg(options::OPT_fsplit_stack))
  3539. CmdArgs.push_back("-split-stacks");
  3540. // If -Ofast is the optimization level, then -ffast-math should be enabled.
  3541. // This alias option is being used to simplify the getLastArg logic.
  3542. OptSpecifier FastMathAliasOption =
  3543. OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
  3544. // Handle various floating point optimization flags, mapping them to the
  3545. // appropriate LLVM code generation flags. The pattern for all of these is to
  3546. // default off the codegen optimizations, and if any flag enables them and no
  3547. // flag disables them after the flag enabling them, enable the codegen
  3548. // optimization. This is complicated by several "umbrella" flags.
  3549. if (Arg *A = Args.getLastArg(
  3550. options::OPT_ffast_math, FastMathAliasOption,
  3551. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3552. options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
  3553. options::OPT_fno_honor_infinities))
  3554. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3555. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3556. A->getOption().getID() != options::OPT_fhonor_infinities)
  3557. CmdArgs.push_back("-menable-no-infs");
  3558. if (Arg *A = Args.getLastArg(
  3559. options::OPT_ffast_math, FastMathAliasOption,
  3560. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3561. options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
  3562. options::OPT_fno_honor_nans))
  3563. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3564. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3565. A->getOption().getID() != options::OPT_fhonor_nans)
  3566. CmdArgs.push_back("-menable-no-nans");
  3567. // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
  3568. bool MathErrno = getToolChain().IsMathErrnoDefault();
  3569. if (Arg *A =
  3570. Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3571. options::OPT_fno_fast_math, options::OPT_fmath_errno,
  3572. options::OPT_fno_math_errno)) {
  3573. // Turning on -ffast_math (with either flag) removes the need for MathErrno.
  3574. // However, turning *off* -ffast_math merely restores the toolchain default
  3575. // (which may be false).
  3576. if (A->getOption().getID() == options::OPT_fno_math_errno ||
  3577. A->getOption().getID() == options::OPT_ffast_math ||
  3578. A->getOption().getID() == options::OPT_Ofast)
  3579. MathErrno = false;
  3580. else if (A->getOption().getID() == options::OPT_fmath_errno)
  3581. MathErrno = true;
  3582. }
  3583. if (MathErrno)
  3584. CmdArgs.push_back("-fmath-errno");
  3585. // There are several flags which require disabling very specific
  3586. // optimizations. Any of these being disabled forces us to turn off the
  3587. // entire set of LLVM optimizations, so collect them through all the flag
  3588. // madness.
  3589. bool AssociativeMath = false;
  3590. if (Arg *A = Args.getLastArg(
  3591. options::OPT_ffast_math, FastMathAliasOption,
  3592. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3593. options::OPT_fno_unsafe_math_optimizations,
  3594. options::OPT_fassociative_math, options::OPT_fno_associative_math))
  3595. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3596. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3597. A->getOption().getID() != options::OPT_fno_associative_math)
  3598. AssociativeMath = true;
  3599. bool ReciprocalMath = false;
  3600. if (Arg *A = Args.getLastArg(
  3601. options::OPT_ffast_math, FastMathAliasOption,
  3602. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3603. options::OPT_fno_unsafe_math_optimizations,
  3604. options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
  3605. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3606. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3607. A->getOption().getID() != options::OPT_fno_reciprocal_math)
  3608. ReciprocalMath = true;
  3609. bool SignedZeros = true;
  3610. if (Arg *A = Args.getLastArg(
  3611. options::OPT_ffast_math, FastMathAliasOption,
  3612. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3613. options::OPT_fno_unsafe_math_optimizations,
  3614. options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
  3615. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3616. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3617. A->getOption().getID() != options::OPT_fsigned_zeros)
  3618. SignedZeros = false;
  3619. bool TrappingMath = true;
  3620. if (Arg *A = Args.getLastArg(
  3621. options::OPT_ffast_math, FastMathAliasOption,
  3622. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3623. options::OPT_fno_unsafe_math_optimizations,
  3624. options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
  3625. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3626. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3627. A->getOption().getID() != options::OPT_ftrapping_math)
  3628. TrappingMath = false;
  3629. if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
  3630. !TrappingMath)
  3631. CmdArgs.push_back("-menable-unsafe-fp-math");
  3632. if (!SignedZeros)
  3633. CmdArgs.push_back("-fno-signed-zeros");
  3634. if (ReciprocalMath)
  3635. CmdArgs.push_back("-freciprocal-math");
  3636. // Validate and pass through -fp-contract option.
  3637. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3638. options::OPT_fno_fast_math,
  3639. options::OPT_ffp_contract)) {
  3640. if (A->getOption().getID() == options::OPT_ffp_contract) {
  3641. StringRef Val = A->getValue();
  3642. if (Val == "fast" || Val == "on" || Val == "off") {
  3643. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
  3644. } else {
  3645. D.Diag(diag::err_drv_unsupported_option_argument)
  3646. << A->getOption().getName() << Val;
  3647. }
  3648. } else if (A->getOption().matches(options::OPT_ffast_math) ||
  3649. (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
  3650. // If fast-math is set then set the fp-contract mode to fast.
  3651. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
  3652. }
  3653. }
  3654. ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
  3655. // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
  3656. // and if we find them, tell the frontend to provide the appropriate
  3657. // preprocessor macros. This is distinct from enabling any optimizations as
  3658. // these options induce language changes which must survive serialization
  3659. // and deserialization, etc.
  3660. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3661. options::OPT_fno_fast_math))
  3662. if (!A->getOption().matches(options::OPT_fno_fast_math))
  3663. CmdArgs.push_back("-ffast-math");
  3664. if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
  3665. options::OPT_fno_fast_math))
  3666. if (A->getOption().matches(options::OPT_ffinite_math_only))
  3667. CmdArgs.push_back("-ffinite-math-only");
  3668. // Decide whether to use verbose asm. Verbose assembly is the default on
  3669. // toolchains which have the integrated assembler on by default.
  3670. bool IsIntegratedAssemblerDefault =
  3671. getToolChain().IsIntegratedAssemblerDefault();
  3672. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  3673. IsIntegratedAssemblerDefault) ||
  3674. Args.hasArg(options::OPT_dA))
  3675. CmdArgs.push_back("-masm-verbose");
  3676. if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
  3677. IsIntegratedAssemblerDefault))
  3678. CmdArgs.push_back("-no-integrated-as");
  3679. if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
  3680. CmdArgs.push_back("-mdebug-pass");
  3681. CmdArgs.push_back("Structure");
  3682. }
  3683. if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
  3684. CmdArgs.push_back("-mdebug-pass");
  3685. CmdArgs.push_back("Arguments");
  3686. }
  3687. // Enable -mconstructor-aliases except on darwin, where we have to work around
  3688. // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
  3689. // aliases aren't supported.
  3690. if (!getToolChain().getTriple().isOSDarwin() &&
  3691. !getToolChain().getTriple().isNVPTX())
  3692. CmdArgs.push_back("-mconstructor-aliases");
  3693. // Darwin's kernel doesn't support guard variables; just die if we
  3694. // try to use them.
  3695. if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
  3696. CmdArgs.push_back("-fforbid-guard-variables");
  3697. if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
  3698. false)) {
  3699. CmdArgs.push_back("-mms-bitfields");
  3700. }
  3701. // This is a coarse approximation of what llvm-gcc actually does, both
  3702. // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
  3703. // complicated ways.
  3704. bool AsynchronousUnwindTables =
  3705. Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
  3706. options::OPT_fno_asynchronous_unwind_tables,
  3707. (getToolChain().IsUnwindTablesDefault() ||
  3708. getToolChain().getSanitizerArgs().needsUnwindTables()) &&
  3709. !KernelOrKext);
  3710. if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
  3711. AsynchronousUnwindTables))
  3712. CmdArgs.push_back("-munwind-tables");
  3713. getToolChain().addClangTargetOptions(Args, CmdArgs);
  3714. if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
  3715. CmdArgs.push_back("-mlimit-float-precision");
  3716. CmdArgs.push_back(A->getValue());
  3717. }
  3718. // FIXME: Handle -mtune=.
  3719. (void)Args.hasArg(options::OPT_mtune_EQ);
  3720. if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
  3721. CmdArgs.push_back("-mcode-model");
  3722. CmdArgs.push_back(A->getValue());
  3723. }
  3724. // Add the target cpu
  3725. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
  3726. if (!CPU.empty()) {
  3727. CmdArgs.push_back("-target-cpu");
  3728. CmdArgs.push_back(Args.MakeArgString(CPU));
  3729. }
  3730. if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
  3731. CmdArgs.push_back("-mfpmath");
  3732. CmdArgs.push_back(A->getValue());
  3733. }
  3734. // Add the target features
  3735. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
  3736. // Add target specific flags.
  3737. switch (getToolChain().getArch()) {
  3738. default:
  3739. break;
  3740. case llvm::Triple::arm:
  3741. case llvm::Triple::armeb:
  3742. case llvm::Triple::thumb:
  3743. case llvm::Triple::thumbeb:
  3744. // Use the effective triple, which takes into account the deployment target.
  3745. AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
  3746. break;
  3747. case llvm::Triple::aarch64:
  3748. case llvm::Triple::aarch64_be:
  3749. AddAArch64TargetArgs(Args, CmdArgs);
  3750. break;
  3751. case llvm::Triple::mips:
  3752. case llvm::Triple::mipsel:
  3753. case llvm::Triple::mips64:
  3754. case llvm::Triple::mips64el:
  3755. AddMIPSTargetArgs(Args, CmdArgs);
  3756. break;
  3757. case llvm::Triple::ppc:
  3758. case llvm::Triple::ppc64:
  3759. case llvm::Triple::ppc64le:
  3760. AddPPCTargetArgs(Args, CmdArgs);
  3761. break;
  3762. case llvm::Triple::sparc:
  3763. case llvm::Triple::sparcel:
  3764. case llvm::Triple::sparcv9:
  3765. AddSparcTargetArgs(Args, CmdArgs);
  3766. break;
  3767. case llvm::Triple::x86:
  3768. case llvm::Triple::x86_64:
  3769. AddX86TargetArgs(Args, CmdArgs);
  3770. break;
  3771. case llvm::Triple::lanai:
  3772. AddLanaiTargetArgs(Args, CmdArgs);
  3773. break;
  3774. case llvm::Triple::hexagon:
  3775. AddHexagonTargetArgs(Args, CmdArgs);
  3776. break;
  3777. case llvm::Triple::wasm32:
  3778. case llvm::Triple::wasm64:
  3779. AddWebAssemblyTargetArgs(Args, CmdArgs);
  3780. break;
  3781. }
  3782. // The 'g' groups options involve a somewhat intricate sequence of decisions
  3783. // about what to pass from the driver to the frontend, but by the time they
  3784. // reach cc1 they've been factored into three well-defined orthogonal choices:
  3785. // * what level of debug info to generate
  3786. // * what dwarf version to write
  3787. // * what debugger tuning to use
  3788. // This avoids having to monkey around further in cc1 other than to disable
  3789. // codeview if not running in a Windows environment. Perhaps even that
  3790. // decision should be made in the driver as well though.
  3791. unsigned DwarfVersion = 0;
  3792. llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
  3793. // These two are potentially updated by AddClangCLArgs.
  3794. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  3795. bool EmitCodeView = false;
  3796. // Add clang-cl arguments.
  3797. types::ID InputType = Input.getType();
  3798. if (getToolChain().getDriver().IsCLMode())
  3799. AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
  3800. // Pass the linker version in use.
  3801. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  3802. CmdArgs.push_back("-target-linker-version");
  3803. CmdArgs.push_back(A->getValue());
  3804. }
  3805. if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
  3806. CmdArgs.push_back("-momit-leaf-frame-pointer");
  3807. // Explicitly error on some things we know we don't support and can't just
  3808. // ignore.
  3809. if (!Args.hasArg(options::OPT_fallow_unsupported)) {
  3810. Arg *Unsupported;
  3811. if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
  3812. getToolChain().getArch() == llvm::Triple::x86) {
  3813. if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
  3814. (Unsupported = Args.getLastArg(options::OPT_mkernel)))
  3815. D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
  3816. << Unsupported->getOption().getName();
  3817. }
  3818. }
  3819. Args.AddAllArgs(CmdArgs, options::OPT_v);
  3820. Args.AddLastArg(CmdArgs, options::OPT_H);
  3821. if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
  3822. CmdArgs.push_back("-header-include-file");
  3823. CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
  3824. : "-");
  3825. }
  3826. Args.AddLastArg(CmdArgs, options::OPT_P);
  3827. Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
  3828. if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
  3829. CmdArgs.push_back("-diagnostic-log-file");
  3830. CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
  3831. : "-");
  3832. }
  3833. Args.ClaimAllArgs(options::OPT_g_Group);
  3834. Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
  3835. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  3836. // If the last option explicitly specified a debug-info level, use it.
  3837. if (A->getOption().matches(options::OPT_gN_Group)) {
  3838. DebugInfoKind = DebugLevelToInfoKind(*A);
  3839. // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
  3840. // But -gsplit-dwarf is not a g_group option, hence we have to check the
  3841. // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
  3842. if (SplitDwarfArg && DebugInfoKind < codegenoptions::LimitedDebugInfo &&
  3843. A->getIndex() > SplitDwarfArg->getIndex())
  3844. SplitDwarfArg = nullptr;
  3845. } else
  3846. // For any other 'g' option, use Limited.
  3847. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  3848. }
  3849. // If a debugger tuning argument appeared, remember it.
  3850. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  3851. options::OPT_ggdbN_Group)) {
  3852. if (A->getOption().matches(options::OPT_glldb))
  3853. DebuggerTuning = llvm::DebuggerKind::LLDB;
  3854. else if (A->getOption().matches(options::OPT_gsce))
  3855. DebuggerTuning = llvm::DebuggerKind::SCE;
  3856. else
  3857. DebuggerTuning = llvm::DebuggerKind::GDB;
  3858. }
  3859. // If a -gdwarf argument appeared, remember it.
  3860. if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
  3861. options::OPT_gdwarf_4, options::OPT_gdwarf_5))
  3862. DwarfVersion = DwarfVersionNum(A->getSpelling());
  3863. // Forward -gcodeview.
  3864. // 'EmitCodeView might have been set by CL-compatibility argument parsing.
  3865. if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
  3866. // DwarfVersion remains at 0 if no explicit choice was made.
  3867. CmdArgs.push_back("-gcodeview");
  3868. } else if (DwarfVersion == 0 &&
  3869. DebugInfoKind != codegenoptions::NoDebugInfo) {
  3870. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  3871. }
  3872. // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
  3873. Args.ClaimAllArgs(options::OPT_g_flags_Group);
  3874. // PS4 defaults to no column info
  3875. if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
  3876. /*Default=*/ !IsPS4CPU))
  3877. CmdArgs.push_back("-dwarf-column-info");
  3878. // FIXME: Move backend command line options to the module.
  3879. if (Args.hasArg(options::OPT_gmodules)) {
  3880. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  3881. CmdArgs.push_back("-dwarf-ext-refs");
  3882. CmdArgs.push_back("-fmodule-format=obj");
  3883. }
  3884. // -gsplit-dwarf should turn on -g and enable the backend dwarf
  3885. // splitting and extraction.
  3886. // FIXME: Currently only works on Linux.
  3887. if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
  3888. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  3889. CmdArgs.push_back("-backend-option");
  3890. CmdArgs.push_back("-split-dwarf=Enable");
  3891. }
  3892. // After we've dealt with all combinations of things that could
  3893. // make DebugInfoKind be other than None or DebugLineTablesOnly,
  3894. // figure out if we need to "upgrade" it to standalone debug info.
  3895. // We parse these two '-f' options whether or not they will be used,
  3896. // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
  3897. bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
  3898. options::OPT_fno_standalone_debug,
  3899. getToolChain().GetDefaultStandaloneDebug());
  3900. if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
  3901. DebugInfoKind = codegenoptions::FullDebugInfo;
  3902. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
  3903. DebuggerTuning);
  3904. // -ggnu-pubnames turns on gnu style pubnames in the backend.
  3905. if (Args.hasArg(options::OPT_ggnu_pubnames)) {
  3906. CmdArgs.push_back("-backend-option");
  3907. CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
  3908. }
  3909. // -gdwarf-aranges turns on the emission of the aranges section in the
  3910. // backend.
  3911. // Always enabled on the PS4.
  3912. if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
  3913. CmdArgs.push_back("-backend-option");
  3914. CmdArgs.push_back("-generate-arange-section");
  3915. }
  3916. if (Args.hasFlag(options::OPT_fdebug_types_section,
  3917. options::OPT_fno_debug_types_section, false)) {
  3918. CmdArgs.push_back("-backend-option");
  3919. CmdArgs.push_back("-generate-type-units");
  3920. }
  3921. // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
  3922. // default.
  3923. bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI ||
  3924. Triple.getArch() == llvm::Triple::wasm32 ||
  3925. Triple.getArch() == llvm::Triple::wasm64;
  3926. if (Args.hasFlag(options::OPT_ffunction_sections,
  3927. options::OPT_fno_function_sections, UseSeparateSections)) {
  3928. CmdArgs.push_back("-ffunction-sections");
  3929. }
  3930. if (Args.hasFlag(options::OPT_fwhole_program_vtables,
  3931. options::OPT_fno_whole_program_vtables, false)) {
  3932. if (!D.isUsingLTO())
  3933. D.Diag(diag::err_drv_argument_only_allowed_with)
  3934. << "-fwhole-program-vtables"
  3935. << "-flto";
  3936. CmdArgs.push_back("-fwhole-program-vtables");
  3937. clang::SmallString<64> Path(D.ResourceDir);
  3938. llvm::sys::path::append(Path, "vtables_blacklist.txt");
  3939. if (llvm::sys::fs::exists(Path)) {
  3940. SmallString<64> BlacklistOpt("-fwhole-program-vtables-blacklist=");
  3941. BlacklistOpt += Path.str();
  3942. CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
  3943. }
  3944. for (const Arg *A :
  3945. Args.filtered(options::OPT_fwhole_program_vtables_blacklist_EQ)) {
  3946. A->claim();
  3947. if (!llvm::sys::fs::exists(A->getValue()))
  3948. D.Diag(clang::diag::err_drv_no_such_file) << A->getValue();
  3949. }
  3950. Args.AddAllArgs(CmdArgs, options::OPT_fwhole_program_vtables_blacklist_EQ);
  3951. }
  3952. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  3953. UseSeparateSections)) {
  3954. CmdArgs.push_back("-fdata-sections");
  3955. }
  3956. if (!Args.hasFlag(options::OPT_funique_section_names,
  3957. options::OPT_fno_unique_section_names, true))
  3958. CmdArgs.push_back("-fno-unique-section-names");
  3959. Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
  3960. addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
  3961. // Add runtime flag for PS4 when PGO or Coverage are enabled.
  3962. if (getToolChain().getTriple().isPS4CPU())
  3963. addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
  3964. // Pass options for controlling the default header search paths.
  3965. if (Args.hasArg(options::OPT_nostdinc)) {
  3966. CmdArgs.push_back("-nostdsysteminc");
  3967. CmdArgs.push_back("-nobuiltininc");
  3968. } else {
  3969. if (Args.hasArg(options::OPT_nostdlibinc))
  3970. CmdArgs.push_back("-nostdsysteminc");
  3971. Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
  3972. Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
  3973. }
  3974. // Pass the path to compiler resource files.
  3975. CmdArgs.push_back("-resource-dir");
  3976. CmdArgs.push_back(D.ResourceDir.c_str());
  3977. Args.AddLastArg(CmdArgs, options::OPT_working_directory);
  3978. bool ARCMTEnabled = false;
  3979. if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
  3980. if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
  3981. options::OPT_ccc_arcmt_modify,
  3982. options::OPT_ccc_arcmt_migrate)) {
  3983. ARCMTEnabled = true;
  3984. switch (A->getOption().getID()) {
  3985. default:
  3986. llvm_unreachable("missed a case");
  3987. case options::OPT_ccc_arcmt_check:
  3988. CmdArgs.push_back("-arcmt-check");
  3989. break;
  3990. case options::OPT_ccc_arcmt_modify:
  3991. CmdArgs.push_back("-arcmt-modify");
  3992. break;
  3993. case options::OPT_ccc_arcmt_migrate:
  3994. CmdArgs.push_back("-arcmt-migrate");
  3995. CmdArgs.push_back("-mt-migrate-directory");
  3996. CmdArgs.push_back(A->getValue());
  3997. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
  3998. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
  3999. break;
  4000. }
  4001. }
  4002. } else {
  4003. Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
  4004. Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
  4005. Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
  4006. }
  4007. if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
  4008. if (ARCMTEnabled) {
  4009. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  4010. << "-ccc-arcmt-migrate";
  4011. }
  4012. CmdArgs.push_back("-mt-migrate-directory");
  4013. CmdArgs.push_back(A->getValue());
  4014. if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
  4015. options::OPT_objcmt_migrate_subscripting,
  4016. options::OPT_objcmt_migrate_property)) {
  4017. // None specified, means enable them all.
  4018. CmdArgs.push_back("-objcmt-migrate-literals");
  4019. CmdArgs.push_back("-objcmt-migrate-subscripting");
  4020. CmdArgs.push_back("-objcmt-migrate-property");
  4021. } else {
  4022. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  4023. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  4024. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  4025. }
  4026. } else {
  4027. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  4028. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  4029. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  4030. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
  4031. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
  4032. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
  4033. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
  4034. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
  4035. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
  4036. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
  4037. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
  4038. Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
  4039. Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
  4040. Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
  4041. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
  4042. Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
  4043. }
  4044. // Add preprocessing options like -I, -D, etc. if we are using the
  4045. // preprocessor.
  4046. //
  4047. // FIXME: Support -fpreprocessed
  4048. if (types::getPreprocessedType(InputType) != types::TY_INVALID)
  4049. AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
  4050. AuxToolChain);
  4051. // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
  4052. // that "The compiler can only warn and ignore the option if not recognized".
  4053. // When building with ccache, it will pass -D options to clang even on
  4054. // preprocessed inputs and configure concludes that -fPIC is not supported.
  4055. Args.ClaimAllArgs(options::OPT_D);
  4056. // Manually translate -O4 to -O3; let clang reject others.
  4057. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  4058. if (A->getOption().matches(options::OPT_O4)) {
  4059. CmdArgs.push_back("-O3");
  4060. D.Diag(diag::warn_O4_is_O3);
  4061. } else {
  4062. A->render(Args, CmdArgs);
  4063. }
  4064. }
  4065. // Warn about ignored options to clang.
  4066. for (const Arg *A :
  4067. Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
  4068. D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
  4069. A->claim();
  4070. }
  4071. claimNoWarnArgs(Args);
  4072. Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
  4073. Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
  4074. if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
  4075. CmdArgs.push_back("-pedantic");
  4076. Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
  4077. Args.AddLastArg(CmdArgs, options::OPT_w);
  4078. // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
  4079. // (-ansi is equivalent to -std=c89 or -std=c++98).
  4080. //
  4081. // If a std is supplied, only add -trigraphs if it follows the
  4082. // option.
  4083. bool ImplyVCPPCXXVer = false;
  4084. if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
  4085. if (Std->getOption().matches(options::OPT_ansi))
  4086. if (types::isCXX(InputType))
  4087. CmdArgs.push_back("-std=c++98");
  4088. else
  4089. CmdArgs.push_back("-std=c89");
  4090. else
  4091. Std->render(Args, CmdArgs);
  4092. // If -f(no-)trigraphs appears after the language standard flag, honor it.
  4093. if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
  4094. options::OPT_ftrigraphs,
  4095. options::OPT_fno_trigraphs))
  4096. if (A != Std)
  4097. A->render(Args, CmdArgs);
  4098. } else {
  4099. // Honor -std-default.
  4100. //
  4101. // FIXME: Clang doesn't correctly handle -std= when the input language
  4102. // doesn't match. For the time being just ignore this for C++ inputs;
  4103. // eventually we want to do all the standard defaulting here instead of
  4104. // splitting it between the driver and clang -cc1.
  4105. if (!types::isCXX(InputType))
  4106. Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
  4107. /*Joined=*/true);
  4108. else if (IsWindowsMSVC)
  4109. ImplyVCPPCXXVer = true;
  4110. Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
  4111. options::OPT_fno_trigraphs);
  4112. }
  4113. // GCC's behavior for -Wwrite-strings is a bit strange:
  4114. // * In C, this "warning flag" changes the types of string literals from
  4115. // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
  4116. // for the discarded qualifier.
  4117. // * In C++, this is just a normal warning flag.
  4118. //
  4119. // Implementing this warning correctly in C is hard, so we follow GCC's
  4120. // behavior for now. FIXME: Directly diagnose uses of a string literal as
  4121. // a non-const char* in C, rather than using this crude hack.
  4122. if (!types::isCXX(InputType)) {
  4123. // FIXME: This should behave just like a warning flag, and thus should also
  4124. // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
  4125. Arg *WriteStrings =
  4126. Args.getLastArg(options::OPT_Wwrite_strings,
  4127. options::OPT_Wno_write_strings, options::OPT_w);
  4128. if (WriteStrings &&
  4129. WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
  4130. CmdArgs.push_back("-fconst-strings");
  4131. }
  4132. // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
  4133. // during C++ compilation, which it is by default. GCC keeps this define even
  4134. // in the presence of '-w', match this behavior bug-for-bug.
  4135. if (types::isCXX(InputType) &&
  4136. Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
  4137. true)) {
  4138. CmdArgs.push_back("-fdeprecated-macro");
  4139. }
  4140. // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
  4141. if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
  4142. if (Asm->getOption().matches(options::OPT_fasm))
  4143. CmdArgs.push_back("-fgnu-keywords");
  4144. else
  4145. CmdArgs.push_back("-fno-gnu-keywords");
  4146. }
  4147. if (ShouldDisableDwarfDirectory(Args, getToolChain()))
  4148. CmdArgs.push_back("-fno-dwarf-directory-asm");
  4149. if (ShouldDisableAutolink(Args, getToolChain()))
  4150. CmdArgs.push_back("-fno-autolink");
  4151. // Add in -fdebug-compilation-dir if necessary.
  4152. addDebugCompDirArg(Args, CmdArgs);
  4153. for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
  4154. StringRef Map = A->getValue();
  4155. if (Map.find('=') == StringRef::npos)
  4156. D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
  4157. else
  4158. CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
  4159. A->claim();
  4160. }
  4161. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
  4162. options::OPT_ftemplate_depth_EQ)) {
  4163. CmdArgs.push_back("-ftemplate-depth");
  4164. CmdArgs.push_back(A->getValue());
  4165. }
  4166. if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
  4167. CmdArgs.push_back("-foperator-arrow-depth");
  4168. CmdArgs.push_back(A->getValue());
  4169. }
  4170. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
  4171. CmdArgs.push_back("-fconstexpr-depth");
  4172. CmdArgs.push_back(A->getValue());
  4173. }
  4174. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
  4175. CmdArgs.push_back("-fconstexpr-steps");
  4176. CmdArgs.push_back(A->getValue());
  4177. }
  4178. if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
  4179. CmdArgs.push_back("-fbracket-depth");
  4180. CmdArgs.push_back(A->getValue());
  4181. }
  4182. if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
  4183. options::OPT_Wlarge_by_value_copy_def)) {
  4184. if (A->getNumValues()) {
  4185. StringRef bytes = A->getValue();
  4186. CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
  4187. } else
  4188. CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
  4189. }
  4190. if (Args.hasArg(options::OPT_relocatable_pch))
  4191. CmdArgs.push_back("-relocatable-pch");
  4192. if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
  4193. CmdArgs.push_back("-fconstant-string-class");
  4194. CmdArgs.push_back(A->getValue());
  4195. }
  4196. if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
  4197. CmdArgs.push_back("-ftabstop");
  4198. CmdArgs.push_back(A->getValue());
  4199. }
  4200. CmdArgs.push_back("-ferror-limit");
  4201. if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
  4202. CmdArgs.push_back(A->getValue());
  4203. else
  4204. CmdArgs.push_back("19");
  4205. if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
  4206. CmdArgs.push_back("-fmacro-backtrace-limit");
  4207. CmdArgs.push_back(A->getValue());
  4208. }
  4209. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
  4210. CmdArgs.push_back("-ftemplate-backtrace-limit");
  4211. CmdArgs.push_back(A->getValue());
  4212. }
  4213. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
  4214. CmdArgs.push_back("-fconstexpr-backtrace-limit");
  4215. CmdArgs.push_back(A->getValue());
  4216. }
  4217. if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
  4218. CmdArgs.push_back("-fspell-checking-limit");
  4219. CmdArgs.push_back(A->getValue());
  4220. }
  4221. // Pass -fmessage-length=.
  4222. CmdArgs.push_back("-fmessage-length");
  4223. if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
  4224. CmdArgs.push_back(A->getValue());
  4225. } else {
  4226. // If -fmessage-length=N was not specified, determine whether this is a
  4227. // terminal and, if so, implicitly define -fmessage-length appropriately.
  4228. unsigned N = llvm::sys::Process::StandardErrColumns();
  4229. CmdArgs.push_back(Args.MakeArgString(Twine(N)));
  4230. }
  4231. // -fvisibility= and -fvisibility-ms-compat are of a piece.
  4232. if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
  4233. options::OPT_fvisibility_ms_compat)) {
  4234. if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
  4235. CmdArgs.push_back("-fvisibility");
  4236. CmdArgs.push_back(A->getValue());
  4237. } else {
  4238. assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
  4239. CmdArgs.push_back("-fvisibility");
  4240. CmdArgs.push_back("hidden");
  4241. CmdArgs.push_back("-ftype-visibility");
  4242. CmdArgs.push_back("default");
  4243. }
  4244. }
  4245. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
  4246. Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
  4247. // -fhosted is default.
  4248. if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
  4249. KernelOrKext)
  4250. CmdArgs.push_back("-ffreestanding");
  4251. // Forward -f (flag) options which we can pass directly.
  4252. Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
  4253. Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
  4254. Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
  4255. // Emulated TLS is enabled by default on Android, and can be enabled manually
  4256. // with -femulated-tls.
  4257. bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
  4258. if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
  4259. EmulatedTLSDefault))
  4260. CmdArgs.push_back("-femulated-tls");
  4261. // AltiVec-like language extensions aren't relevant for assembling.
  4262. if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
  4263. Args.AddLastArg(CmdArgs, options::OPT_faltivec);
  4264. Args.AddLastArg(CmdArgs, options::OPT_fzvector);
  4265. }
  4266. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
  4267. Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
  4268. // Forward flags for OpenMP
  4269. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  4270. options::OPT_fno_openmp, false))
  4271. switch (getOpenMPRuntime(getToolChain(), Args)) {
  4272. case OMPRT_OMP:
  4273. case OMPRT_IOMP5:
  4274. // Clang can generate useful OpenMP code for these two runtime libraries.
  4275. CmdArgs.push_back("-fopenmp");
  4276. // If no option regarding the use of TLS in OpenMP codegeneration is
  4277. // given, decide a default based on the target. Otherwise rely on the
  4278. // options and pass the right information to the frontend.
  4279. if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
  4280. options::OPT_fnoopenmp_use_tls, /*Default=*/true))
  4281. CmdArgs.push_back("-fnoopenmp-use-tls");
  4282. break;
  4283. default:
  4284. // By default, if Clang doesn't know how to generate useful OpenMP code
  4285. // for a specific runtime library, we just don't pass the '-fopenmp' flag
  4286. // down to the actual compilation.
  4287. // FIXME: It would be better to have a mode which *only* omits IR
  4288. // generation based on the OpenMP support so that we get consistent
  4289. // semantic analysis, etc.
  4290. break;
  4291. }
  4292. const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
  4293. Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
  4294. // Report an error for -faltivec on anything other than PowerPC.
  4295. if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
  4296. const llvm::Triple::ArchType Arch = getToolChain().getArch();
  4297. if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  4298. Arch == llvm::Triple::ppc64le))
  4299. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  4300. << "ppc/ppc64/ppc64le";
  4301. }
  4302. // -fzvector is incompatible with -faltivec.
  4303. if (Arg *A = Args.getLastArg(options::OPT_fzvector))
  4304. if (Args.hasArg(options::OPT_faltivec))
  4305. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  4306. << "-faltivec";
  4307. if (getToolChain().SupportsProfiling())
  4308. Args.AddLastArg(CmdArgs, options::OPT_pg);
  4309. // -flax-vector-conversions is default.
  4310. if (!Args.hasFlag(options::OPT_flax_vector_conversions,
  4311. options::OPT_fno_lax_vector_conversions))
  4312. CmdArgs.push_back("-fno-lax-vector-conversions");
  4313. if (Args.getLastArg(options::OPT_fapple_kext) ||
  4314. (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
  4315. CmdArgs.push_back("-fapple-kext");
  4316. Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
  4317. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
  4318. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
  4319. Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
  4320. Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
  4321. if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
  4322. CmdArgs.push_back("-ftrapv-handler");
  4323. CmdArgs.push_back(A->getValue());
  4324. }
  4325. Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
  4326. // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
  4327. // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
  4328. if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
  4329. if (A->getOption().matches(options::OPT_fwrapv))
  4330. CmdArgs.push_back("-fwrapv");
  4331. } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
  4332. options::OPT_fno_strict_overflow)) {
  4333. if (A->getOption().matches(options::OPT_fno_strict_overflow))
  4334. CmdArgs.push_back("-fwrapv");
  4335. }
  4336. if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
  4337. options::OPT_fno_reroll_loops))
  4338. if (A->getOption().matches(options::OPT_freroll_loops))
  4339. CmdArgs.push_back("-freroll-loops");
  4340. Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
  4341. Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
  4342. options::OPT_fno_unroll_loops);
  4343. Args.AddLastArg(CmdArgs, options::OPT_pthread);
  4344. // -stack-protector=0 is default.
  4345. unsigned StackProtectorLevel = 0;
  4346. if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
  4347. options::OPT_fstack_protector_all,
  4348. options::OPT_fstack_protector_strong,
  4349. options::OPT_fstack_protector)) {
  4350. if (A->getOption().matches(options::OPT_fstack_protector)) {
  4351. StackProtectorLevel = std::max<unsigned>(
  4352. LangOptions::SSPOn,
  4353. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
  4354. } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
  4355. StackProtectorLevel = LangOptions::SSPStrong;
  4356. else if (A->getOption().matches(options::OPT_fstack_protector_all))
  4357. StackProtectorLevel = LangOptions::SSPReq;
  4358. } else {
  4359. StackProtectorLevel =
  4360. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
  4361. }
  4362. if (StackProtectorLevel) {
  4363. CmdArgs.push_back("-stack-protector");
  4364. CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
  4365. }
  4366. // --param ssp-buffer-size=
  4367. for (const Arg *A : Args.filtered(options::OPT__param)) {
  4368. StringRef Str(A->getValue());
  4369. if (Str.startswith("ssp-buffer-size=")) {
  4370. if (StackProtectorLevel) {
  4371. CmdArgs.push_back("-stack-protector-buffer-size");
  4372. // FIXME: Verify the argument is a valid integer.
  4373. CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
  4374. }
  4375. A->claim();
  4376. }
  4377. }
  4378. // Translate -mstackrealign
  4379. if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
  4380. false))
  4381. CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
  4382. if (Args.hasArg(options::OPT_mstack_alignment)) {
  4383. StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
  4384. CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
  4385. }
  4386. if (Args.hasArg(options::OPT_mstack_probe_size)) {
  4387. StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
  4388. if (!Size.empty())
  4389. CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
  4390. else
  4391. CmdArgs.push_back("-mstack-probe-size=0");
  4392. }
  4393. switch (getToolChain().getArch()) {
  4394. case llvm::Triple::aarch64:
  4395. case llvm::Triple::aarch64_be:
  4396. case llvm::Triple::arm:
  4397. case llvm::Triple::armeb:
  4398. case llvm::Triple::thumb:
  4399. case llvm::Triple::thumbeb:
  4400. CmdArgs.push_back("-fallow-half-arguments-and-returns");
  4401. break;
  4402. default:
  4403. break;
  4404. }
  4405. if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
  4406. options::OPT_mno_restrict_it)) {
  4407. if (A->getOption().matches(options::OPT_mrestrict_it)) {
  4408. CmdArgs.push_back("-backend-option");
  4409. CmdArgs.push_back("-arm-restrict-it");
  4410. } else {
  4411. CmdArgs.push_back("-backend-option");
  4412. CmdArgs.push_back("-arm-no-restrict-it");
  4413. }
  4414. } else if (Triple.isOSWindows() &&
  4415. (Triple.getArch() == llvm::Triple::arm ||
  4416. Triple.getArch() == llvm::Triple::thumb)) {
  4417. // Windows on ARM expects restricted IT blocks
  4418. CmdArgs.push_back("-backend-option");
  4419. CmdArgs.push_back("-arm-restrict-it");
  4420. }
  4421. // Forward -f options with positive and negative forms; we translate
  4422. // these by hand.
  4423. if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
  4424. StringRef fname = A->getValue();
  4425. if (!llvm::sys::fs::exists(fname))
  4426. D.Diag(diag::err_drv_no_such_file) << fname;
  4427. else
  4428. A->render(Args, CmdArgs);
  4429. }
  4430. // -fbuiltin is default unless -mkernel is used.
  4431. bool UseBuiltins =
  4432. Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
  4433. !Args.hasArg(options::OPT_mkernel));
  4434. if (!UseBuiltins)
  4435. CmdArgs.push_back("-fno-builtin");
  4436. // -ffreestanding implies -fno-builtin.
  4437. if (Args.hasArg(options::OPT_ffreestanding))
  4438. UseBuiltins = false;
  4439. // Process the -fno-builtin-* options.
  4440. for (const auto &Arg : Args) {
  4441. const Option &O = Arg->getOption();
  4442. if (!O.matches(options::OPT_fno_builtin_))
  4443. continue;
  4444. Arg->claim();
  4445. // If -fno-builtin is specified, then there's no need to pass the option to
  4446. // the frontend.
  4447. if (!UseBuiltins)
  4448. continue;
  4449. StringRef FuncName = Arg->getValue();
  4450. CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
  4451. }
  4452. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4453. options::OPT_fno_assume_sane_operator_new))
  4454. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4455. // -fblocks=0 is default.
  4456. if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
  4457. getToolChain().IsBlocksDefault()) ||
  4458. (Args.hasArg(options::OPT_fgnu_runtime) &&
  4459. Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
  4460. !Args.hasArg(options::OPT_fno_blocks))) {
  4461. CmdArgs.push_back("-fblocks");
  4462. if (!Args.hasArg(options::OPT_fgnu_runtime) &&
  4463. !getToolChain().hasBlocksRuntime())
  4464. CmdArgs.push_back("-fblocks-runtime-optional");
  4465. }
  4466. // -fmodules enables the use of precompiled modules (off by default).
  4467. // Users can pass -fno-cxx-modules to turn off modules support for
  4468. // C++/Objective-C++ programs.
  4469. bool HaveModules = false;
  4470. if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
  4471. bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
  4472. options::OPT_fno_cxx_modules, true);
  4473. if (AllowedInCXX || !types::isCXX(InputType)) {
  4474. CmdArgs.push_back("-fmodules");
  4475. HaveModules = true;
  4476. }
  4477. }
  4478. // -fmodule-maps enables implicit reading of module map files. By default,
  4479. // this is enabled if we are using precompiled modules.
  4480. if (Args.hasFlag(options::OPT_fimplicit_module_maps,
  4481. options::OPT_fno_implicit_module_maps, HaveModules)) {
  4482. CmdArgs.push_back("-fimplicit-module-maps");
  4483. }
  4484. // -fmodules-decluse checks that modules used are declared so (off by
  4485. // default).
  4486. if (Args.hasFlag(options::OPT_fmodules_decluse,
  4487. options::OPT_fno_modules_decluse, false)) {
  4488. CmdArgs.push_back("-fmodules-decluse");
  4489. }
  4490. // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
  4491. // all #included headers are part of modules.
  4492. if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
  4493. options::OPT_fno_modules_strict_decluse, false)) {
  4494. CmdArgs.push_back("-fmodules-strict-decluse");
  4495. }
  4496. // -fno-implicit-modules turns off implicitly compiling modules on demand.
  4497. if (!Args.hasFlag(options::OPT_fimplicit_modules,
  4498. options::OPT_fno_implicit_modules)) {
  4499. CmdArgs.push_back("-fno-implicit-modules");
  4500. } else if (HaveModules) {
  4501. // -fmodule-cache-path specifies where our implicitly-built module files
  4502. // should be written.
  4503. SmallString<128> Path;
  4504. if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
  4505. Path = A->getValue();
  4506. if (C.isForDiagnostics()) {
  4507. // When generating crash reports, we want to emit the modules along with
  4508. // the reproduction sources, so we ignore any provided module path.
  4509. Path = Output.getFilename();
  4510. llvm::sys::path::replace_extension(Path, ".cache");
  4511. llvm::sys::path::append(Path, "modules");
  4512. } else if (Path.empty()) {
  4513. // No module path was provided: use the default.
  4514. llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
  4515. llvm::sys::path::append(Path, "org.llvm.clang.");
  4516. appendUserToPath(Path);
  4517. llvm::sys::path::append(Path, "ModuleCache");
  4518. }
  4519. const char Arg[] = "-fmodules-cache-path=";
  4520. Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
  4521. CmdArgs.push_back(Args.MakeArgString(Path));
  4522. }
  4523. // -fmodule-name specifies the module that is currently being built (or
  4524. // used for header checking by -fmodule-maps).
  4525. Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
  4526. // -fmodule-map-file can be used to specify files containing module
  4527. // definitions.
  4528. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
  4529. // -fmodule-file can be used to specify files containing precompiled modules.
  4530. if (HaveModules)
  4531. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
  4532. else
  4533. Args.ClaimAllArgs(options::OPT_fmodule_file);
  4534. // When building modules and generating crashdumps, we need to dump a module
  4535. // dependency VFS alongside the output.
  4536. if (HaveModules && C.isForDiagnostics()) {
  4537. SmallString<128> VFSDir(Output.getFilename());
  4538. llvm::sys::path::replace_extension(VFSDir, ".cache");
  4539. // Add the cache directory as a temp so the crash diagnostics pick it up.
  4540. C.addTempFile(Args.MakeArgString(VFSDir));
  4541. llvm::sys::path::append(VFSDir, "vfs");
  4542. CmdArgs.push_back("-module-dependency-dir");
  4543. CmdArgs.push_back(Args.MakeArgString(VFSDir));
  4544. }
  4545. if (HaveModules)
  4546. Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
  4547. // Pass through all -fmodules-ignore-macro arguments.
  4548. Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
  4549. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
  4550. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
  4551. Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
  4552. if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
  4553. if (Args.hasArg(options::OPT_fbuild_session_timestamp))
  4554. D.Diag(diag::err_drv_argument_not_allowed_with)
  4555. << A->getAsString(Args) << "-fbuild-session-timestamp";
  4556. llvm::sys::fs::file_status Status;
  4557. if (llvm::sys::fs::status(A->getValue(), Status))
  4558. D.Diag(diag::err_drv_no_such_file) << A->getValue();
  4559. CmdArgs.push_back(Args.MakeArgString(
  4560. "-fbuild-session-timestamp=" +
  4561. Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
  4562. }
  4563. if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
  4564. if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
  4565. options::OPT_fbuild_session_file))
  4566. D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
  4567. Args.AddLastArg(CmdArgs,
  4568. options::OPT_fmodules_validate_once_per_build_session);
  4569. }
  4570. Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
  4571. // -faccess-control is default.
  4572. if (Args.hasFlag(options::OPT_fno_access_control,
  4573. options::OPT_faccess_control, false))
  4574. CmdArgs.push_back("-fno-access-control");
  4575. // -felide-constructors is the default.
  4576. if (Args.hasFlag(options::OPT_fno_elide_constructors,
  4577. options::OPT_felide_constructors, false))
  4578. CmdArgs.push_back("-fno-elide-constructors");
  4579. ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
  4580. if (KernelOrKext || (types::isCXX(InputType) &&
  4581. (RTTIMode == ToolChain::RM_DisabledExplicitly ||
  4582. RTTIMode == ToolChain::RM_DisabledImplicitly)))
  4583. CmdArgs.push_back("-fno-rtti");
  4584. // -fshort-enums=0 is default for all architectures except Hexagon.
  4585. if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
  4586. getToolChain().getArch() == llvm::Triple::hexagon))
  4587. CmdArgs.push_back("-fshort-enums");
  4588. // -fsigned-char is default.
  4589. if (Arg *A = Args.getLastArg(
  4590. options::OPT_fsigned_char, options::OPT_fno_signed_char,
  4591. options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
  4592. if (A->getOption().matches(options::OPT_funsigned_char) ||
  4593. A->getOption().matches(options::OPT_fno_signed_char)) {
  4594. CmdArgs.push_back("-fno-signed-char");
  4595. }
  4596. } else if (!isSignedCharDefault(getToolChain().getTriple())) {
  4597. CmdArgs.push_back("-fno-signed-char");
  4598. }
  4599. // -fuse-cxa-atexit is default.
  4600. if (!Args.hasFlag(
  4601. options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
  4602. !IsWindowsCygnus && !IsWindowsGNU &&
  4603. getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
  4604. getToolChain().getArch() != llvm::Triple::hexagon &&
  4605. getToolChain().getArch() != llvm::Triple::xcore &&
  4606. ((getToolChain().getTriple().getVendor() !=
  4607. llvm::Triple::MipsTechnologies) ||
  4608. getToolChain().getTriple().hasEnvironment())) ||
  4609. KernelOrKext)
  4610. CmdArgs.push_back("-fno-use-cxa-atexit");
  4611. // -fms-extensions=0 is default.
  4612. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  4613. IsWindowsMSVC))
  4614. CmdArgs.push_back("-fms-extensions");
  4615. // -fno-use-line-directives is default.
  4616. if (Args.hasFlag(options::OPT_fuse_line_directives,
  4617. options::OPT_fno_use_line_directives, false))
  4618. CmdArgs.push_back("-fuse-line-directives");
  4619. // -fms-compatibility=0 is default.
  4620. if (Args.hasFlag(options::OPT_fms_compatibility,
  4621. options::OPT_fno_ms_compatibility,
  4622. (IsWindowsMSVC &&
  4623. Args.hasFlag(options::OPT_fms_extensions,
  4624. options::OPT_fno_ms_extensions, true))))
  4625. CmdArgs.push_back("-fms-compatibility");
  4626. // -fms-compatibility-version=18.00 is default.
  4627. VersionTuple MSVT = visualstudio::getMSVCVersion(
  4628. &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
  4629. if (!MSVT.empty())
  4630. CmdArgs.push_back(
  4631. Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
  4632. bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
  4633. if (ImplyVCPPCXXVer) {
  4634. if (IsMSVC2015Compatible)
  4635. CmdArgs.push_back("-std=c++14");
  4636. else
  4637. CmdArgs.push_back("-std=c++11");
  4638. }
  4639. // -fno-borland-extensions is default.
  4640. if (Args.hasFlag(options::OPT_fborland_extensions,
  4641. options::OPT_fno_borland_extensions, false))
  4642. CmdArgs.push_back("-fborland-extensions");
  4643. // -fno-declspec is default, except for PS4.
  4644. if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
  4645. getToolChain().getTriple().isPS4()))
  4646. CmdArgs.push_back("-fdeclspec");
  4647. else if (Args.hasArg(options::OPT_fno_declspec))
  4648. CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
  4649. // -fthreadsafe-static is default, except for MSVC compatibility versions less
  4650. // than 19.
  4651. if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
  4652. options::OPT_fno_threadsafe_statics,
  4653. !IsWindowsMSVC || IsMSVC2015Compatible))
  4654. CmdArgs.push_back("-fno-threadsafe-statics");
  4655. // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
  4656. // needs it.
  4657. if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
  4658. options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
  4659. CmdArgs.push_back("-fdelayed-template-parsing");
  4660. // -fgnu-keywords default varies depending on language; only pass if
  4661. // specified.
  4662. if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
  4663. options::OPT_fno_gnu_keywords))
  4664. A->render(Args, CmdArgs);
  4665. if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
  4666. false))
  4667. CmdArgs.push_back("-fgnu89-inline");
  4668. if (Args.hasArg(options::OPT_fno_inline))
  4669. CmdArgs.push_back("-fno-inline");
  4670. if (Args.hasArg(options::OPT_fno_inline_functions))
  4671. CmdArgs.push_back("-fno-inline-functions");
  4672. ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
  4673. // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
  4674. // legacy is the default. Except for deployment taget of 10.5,
  4675. // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
  4676. // gets ignored silently.
  4677. if (objcRuntime.isNonFragile()) {
  4678. if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
  4679. options::OPT_fno_objc_legacy_dispatch,
  4680. objcRuntime.isLegacyDispatchDefaultForArch(
  4681. getToolChain().getArch()))) {
  4682. if (getToolChain().UseObjCMixedDispatch())
  4683. CmdArgs.push_back("-fobjc-dispatch-method=mixed");
  4684. else
  4685. CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
  4686. }
  4687. }
  4688. // When ObjectiveC legacy runtime is in effect on MacOSX,
  4689. // turn on the option to do Array/Dictionary subscripting
  4690. // by default.
  4691. if (getToolChain().getArch() == llvm::Triple::x86 &&
  4692. getToolChain().getTriple().isMacOSX() &&
  4693. !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
  4694. objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
  4695. objcRuntime.isNeXTFamily())
  4696. CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
  4697. // -fencode-extended-block-signature=1 is default.
  4698. if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
  4699. CmdArgs.push_back("-fencode-extended-block-signature");
  4700. }
  4701. // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
  4702. // NOTE: This logic is duplicated in ToolChains.cpp.
  4703. bool ARC = isObjCAutoRefCount(Args);
  4704. if (ARC) {
  4705. getToolChain().CheckObjCARC();
  4706. CmdArgs.push_back("-fobjc-arc");
  4707. // FIXME: It seems like this entire block, and several around it should be
  4708. // wrapped in isObjC, but for now we just use it here as this is where it
  4709. // was being used previously.
  4710. if (types::isCXX(InputType) && types::isObjC(InputType)) {
  4711. if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  4712. CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
  4713. else
  4714. CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
  4715. }
  4716. // Allow the user to enable full exceptions code emission.
  4717. // We define off for Objective-CC, on for Objective-C++.
  4718. if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
  4719. options::OPT_fno_objc_arc_exceptions,
  4720. /*default*/ types::isCXX(InputType)))
  4721. CmdArgs.push_back("-fobjc-arc-exceptions");
  4722. }
  4723. // -fobjc-infer-related-result-type is the default, except in the Objective-C
  4724. // rewriter.
  4725. if (rewriteKind != RK_None)
  4726. CmdArgs.push_back("-fno-objc-infer-related-result-type");
  4727. // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
  4728. // takes precedence.
  4729. const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
  4730. if (!GCArg)
  4731. GCArg = Args.getLastArg(options::OPT_fobjc_gc);
  4732. if (GCArg) {
  4733. if (ARC) {
  4734. D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
  4735. } else if (getToolChain().SupportsObjCGC()) {
  4736. GCArg->render(Args, CmdArgs);
  4737. } else {
  4738. // FIXME: We should move this to a hard error.
  4739. D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
  4740. }
  4741. }
  4742. // Pass down -fobjc-weak or -fno-objc-weak if present.
  4743. if (types::isObjC(InputType)) {
  4744. auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
  4745. options::OPT_fno_objc_weak);
  4746. if (!WeakArg) {
  4747. // nothing to do
  4748. } else if (GCArg) {
  4749. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  4750. D.Diag(diag::err_objc_weak_with_gc);
  4751. } else if (!objcRuntime.allowsWeak()) {
  4752. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  4753. D.Diag(diag::err_objc_weak_unsupported);
  4754. } else {
  4755. WeakArg->render(Args, CmdArgs);
  4756. }
  4757. }
  4758. if (Args.hasFlag(options::OPT_fapplication_extension,
  4759. options::OPT_fno_application_extension, false))
  4760. CmdArgs.push_back("-fapplication-extension");
  4761. // Handle GCC-style exception args.
  4762. if (!C.getDriver().IsCLMode())
  4763. addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
  4764. CmdArgs);
  4765. if (getToolChain().UseSjLjExceptions(Args))
  4766. CmdArgs.push_back("-fsjlj-exceptions");
  4767. // C++ "sane" operator new.
  4768. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4769. options::OPT_fno_assume_sane_operator_new))
  4770. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4771. // -fsized-deallocation is off by default, as it is an ABI-breaking change for
  4772. // most platforms.
  4773. if (Args.hasFlag(options::OPT_fsized_deallocation,
  4774. options::OPT_fno_sized_deallocation, false))
  4775. CmdArgs.push_back("-fsized-deallocation");
  4776. // -fconstant-cfstrings is default, and may be subject to argument translation
  4777. // on Darwin.
  4778. if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
  4779. options::OPT_fno_constant_cfstrings) ||
  4780. !Args.hasFlag(options::OPT_mconstant_cfstrings,
  4781. options::OPT_mno_constant_cfstrings))
  4782. CmdArgs.push_back("-fno-constant-cfstrings");
  4783. // -fshort-wchar default varies depending on platform; only
  4784. // pass if specified.
  4785. if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
  4786. options::OPT_fno_short_wchar))
  4787. A->render(Args, CmdArgs);
  4788. // -fno-pascal-strings is default, only pass non-default.
  4789. if (Args.hasFlag(options::OPT_fpascal_strings,
  4790. options::OPT_fno_pascal_strings, false))
  4791. CmdArgs.push_back("-fpascal-strings");
  4792. // Honor -fpack-struct= and -fpack-struct, if given. Note that
  4793. // -fno-pack-struct doesn't apply to -fpack-struct=.
  4794. if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
  4795. std::string PackStructStr = "-fpack-struct=";
  4796. PackStructStr += A->getValue();
  4797. CmdArgs.push_back(Args.MakeArgString(PackStructStr));
  4798. } else if (Args.hasFlag(options::OPT_fpack_struct,
  4799. options::OPT_fno_pack_struct, false)) {
  4800. CmdArgs.push_back("-fpack-struct=1");
  4801. }
  4802. // Handle -fmax-type-align=N and -fno-type-align
  4803. bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
  4804. if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
  4805. if (!SkipMaxTypeAlign) {
  4806. std::string MaxTypeAlignStr = "-fmax-type-align=";
  4807. MaxTypeAlignStr += A->getValue();
  4808. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4809. }
  4810. } else if (getToolChain().getTriple().isOSDarwin()) {
  4811. if (!SkipMaxTypeAlign) {
  4812. std::string MaxTypeAlignStr = "-fmax-type-align=16";
  4813. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4814. }
  4815. }
  4816. // -fcommon is the default unless compiling kernel code or the target says so
  4817. bool NoCommonDefault =
  4818. KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
  4819. if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
  4820. !NoCommonDefault))
  4821. CmdArgs.push_back("-fno-common");
  4822. // -fsigned-bitfields is default, and clang doesn't yet support
  4823. // -funsigned-bitfields.
  4824. if (!Args.hasFlag(options::OPT_fsigned_bitfields,
  4825. options::OPT_funsigned_bitfields))
  4826. D.Diag(diag::warn_drv_clang_unsupported)
  4827. << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
  4828. // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
  4829. if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
  4830. D.Diag(diag::err_drv_clang_unsupported)
  4831. << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
  4832. // -finput_charset=UTF-8 is default. Reject others
  4833. if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
  4834. StringRef value = inputCharset->getValue();
  4835. if (value != "UTF-8")
  4836. D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
  4837. << value;
  4838. }
  4839. // -fexec_charset=UTF-8 is default. Reject others
  4840. if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
  4841. StringRef value = execCharset->getValue();
  4842. if (value != "UTF-8")
  4843. D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
  4844. << value;
  4845. }
  4846. // -fcaret-diagnostics is default.
  4847. if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
  4848. options::OPT_fno_caret_diagnostics, true))
  4849. CmdArgs.push_back("-fno-caret-diagnostics");
  4850. // -fdiagnostics-fixit-info is default, only pass non-default.
  4851. if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
  4852. options::OPT_fno_diagnostics_fixit_info))
  4853. CmdArgs.push_back("-fno-diagnostics-fixit-info");
  4854. // Enable -fdiagnostics-show-option by default.
  4855. if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
  4856. options::OPT_fno_diagnostics_show_option))
  4857. CmdArgs.push_back("-fdiagnostics-show-option");
  4858. if (const Arg *A =
  4859. Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
  4860. CmdArgs.push_back("-fdiagnostics-show-category");
  4861. CmdArgs.push_back(A->getValue());
  4862. }
  4863. if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
  4864. CmdArgs.push_back("-fdiagnostics-format");
  4865. CmdArgs.push_back(A->getValue());
  4866. }
  4867. if (Arg *A = Args.getLastArg(
  4868. options::OPT_fdiagnostics_show_note_include_stack,
  4869. options::OPT_fno_diagnostics_show_note_include_stack)) {
  4870. if (A->getOption().matches(
  4871. options::OPT_fdiagnostics_show_note_include_stack))
  4872. CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
  4873. else
  4874. CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
  4875. }
  4876. // Color diagnostics are the default, unless the terminal doesn't support
  4877. // them.
  4878. // Support both clang's -f[no-]color-diagnostics and gcc's
  4879. // -f[no-]diagnostics-colors[=never|always|auto].
  4880. enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
  4881. for (const auto &Arg : Args) {
  4882. const Option &O = Arg->getOption();
  4883. if (!O.matches(options::OPT_fcolor_diagnostics) &&
  4884. !O.matches(options::OPT_fdiagnostics_color) &&
  4885. !O.matches(options::OPT_fno_color_diagnostics) &&
  4886. !O.matches(options::OPT_fno_diagnostics_color) &&
  4887. !O.matches(options::OPT_fdiagnostics_color_EQ))
  4888. continue;
  4889. Arg->claim();
  4890. if (O.matches(options::OPT_fcolor_diagnostics) ||
  4891. O.matches(options::OPT_fdiagnostics_color)) {
  4892. ShowColors = Colors_On;
  4893. } else if (O.matches(options::OPT_fno_color_diagnostics) ||
  4894. O.matches(options::OPT_fno_diagnostics_color)) {
  4895. ShowColors = Colors_Off;
  4896. } else {
  4897. assert(O.matches(options::OPT_fdiagnostics_color_EQ));
  4898. StringRef value(Arg->getValue());
  4899. if (value == "always")
  4900. ShowColors = Colors_On;
  4901. else if (value == "never")
  4902. ShowColors = Colors_Off;
  4903. else if (value == "auto")
  4904. ShowColors = Colors_Auto;
  4905. else
  4906. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  4907. << ("-fdiagnostics-color=" + value).str();
  4908. }
  4909. }
  4910. if (ShowColors == Colors_On ||
  4911. (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
  4912. CmdArgs.push_back("-fcolor-diagnostics");
  4913. if (Args.hasArg(options::OPT_fansi_escape_codes))
  4914. CmdArgs.push_back("-fansi-escape-codes");
  4915. if (!Args.hasFlag(options::OPT_fshow_source_location,
  4916. options::OPT_fno_show_source_location))
  4917. CmdArgs.push_back("-fno-show-source-location");
  4918. if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
  4919. true))
  4920. CmdArgs.push_back("-fno-show-column");
  4921. if (!Args.hasFlag(options::OPT_fspell_checking,
  4922. options::OPT_fno_spell_checking))
  4923. CmdArgs.push_back("-fno-spell-checking");
  4924. // -fno-asm-blocks is default.
  4925. if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
  4926. false))
  4927. CmdArgs.push_back("-fasm-blocks");
  4928. // -fgnu-inline-asm is default.
  4929. if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
  4930. options::OPT_fno_gnu_inline_asm, true))
  4931. CmdArgs.push_back("-fno-gnu-inline-asm");
  4932. // Enable vectorization per default according to the optimization level
  4933. // selected. For optimization levels that want vectorization we use the alias
  4934. // option to simplify the hasFlag logic.
  4935. bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
  4936. OptSpecifier VectorizeAliasOption =
  4937. EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
  4938. if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
  4939. options::OPT_fno_vectorize, EnableVec))
  4940. CmdArgs.push_back("-vectorize-loops");
  4941. // -fslp-vectorize is enabled based on the optimization level selected.
  4942. bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
  4943. OptSpecifier SLPVectAliasOption =
  4944. EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
  4945. if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
  4946. options::OPT_fno_slp_vectorize, EnableSLPVec))
  4947. CmdArgs.push_back("-vectorize-slp");
  4948. // -fno-slp-vectorize-aggressive is default.
  4949. if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
  4950. options::OPT_fno_slp_vectorize_aggressive, false))
  4951. CmdArgs.push_back("-vectorize-slp-aggressive");
  4952. if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
  4953. A->render(Args, CmdArgs);
  4954. // -fdollars-in-identifiers default varies depending on platform and
  4955. // language; only pass if specified.
  4956. if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
  4957. options::OPT_fno_dollars_in_identifiers)) {
  4958. if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
  4959. CmdArgs.push_back("-fdollars-in-identifiers");
  4960. else
  4961. CmdArgs.push_back("-fno-dollars-in-identifiers");
  4962. }
  4963. // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
  4964. // practical purposes.
  4965. if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
  4966. options::OPT_fno_unit_at_a_time)) {
  4967. if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
  4968. D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
  4969. }
  4970. if (Args.hasFlag(options::OPT_fapple_pragma_pack,
  4971. options::OPT_fno_apple_pragma_pack, false))
  4972. CmdArgs.push_back("-fapple-pragma-pack");
  4973. // le32-specific flags:
  4974. // -fno-math-builtin: clang should not convert math builtins to intrinsics
  4975. // by default.
  4976. if (getToolChain().getArch() == llvm::Triple::le32) {
  4977. CmdArgs.push_back("-fno-math-builtin");
  4978. }
  4979. // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
  4980. //
  4981. // FIXME: Now that PR4941 has been fixed this can be enabled.
  4982. #if 0
  4983. if (getToolChain().getTriple().isOSDarwin() &&
  4984. (getToolChain().getArch() == llvm::Triple::arm ||
  4985. getToolChain().getArch() == llvm::Triple::thumb)) {
  4986. if (!Args.hasArg(options::OPT_fbuiltin_strcat))
  4987. CmdArgs.push_back("-fno-builtin-strcat");
  4988. if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
  4989. CmdArgs.push_back("-fno-builtin-strcpy");
  4990. }
  4991. #endif
  4992. // Enable rewrite includes if the user's asked for it or if we're generating
  4993. // diagnostics.
  4994. // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
  4995. // nice to enable this when doing a crashdump for modules as well.
  4996. if (Args.hasFlag(options::OPT_frewrite_includes,
  4997. options::OPT_fno_rewrite_includes, false) ||
  4998. (C.isForDiagnostics() && !HaveModules))
  4999. CmdArgs.push_back("-frewrite-includes");
  5000. // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
  5001. if (Arg *A = Args.getLastArg(options::OPT_traditional,
  5002. options::OPT_traditional_cpp)) {
  5003. if (isa<PreprocessJobAction>(JA))
  5004. CmdArgs.push_back("-traditional-cpp");
  5005. else
  5006. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  5007. }
  5008. Args.AddLastArg(CmdArgs, options::OPT_dM);
  5009. Args.AddLastArg(CmdArgs, options::OPT_dD);
  5010. // Handle serialized diagnostics.
  5011. if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
  5012. CmdArgs.push_back("-serialize-diagnostic-file");
  5013. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  5014. }
  5015. if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
  5016. CmdArgs.push_back("-fretain-comments-from-system-headers");
  5017. // Forward -fcomment-block-commands to -cc1.
  5018. Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
  5019. // Forward -fparse-all-comments to -cc1.
  5020. Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
  5021. // Turn -fplugin=name.so into -load name.so
  5022. for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
  5023. CmdArgs.push_back("-load");
  5024. CmdArgs.push_back(A->getValue());
  5025. A->claim();
  5026. }
  5027. // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
  5028. // parser.
  5029. Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
  5030. for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
  5031. A->claim();
  5032. // We translate this by hand to the -cc1 argument, since nightly test uses
  5033. // it and developers have been trained to spell it with -mllvm.
  5034. if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
  5035. CmdArgs.push_back("-disable-llvm-optzns");
  5036. } else
  5037. A->render(Args, CmdArgs);
  5038. }
  5039. // With -save-temps, we want to save the unoptimized bitcode output from the
  5040. // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
  5041. // by the frontend.
  5042. if (C.getDriver().isSaveTempsEnabled() && isa<CompileJobAction>(JA))
  5043. CmdArgs.push_back("-disable-llvm-passes");
  5044. if (Output.getType() == types::TY_Dependencies) {
  5045. // Handled with other dependency code.
  5046. } else if (Output.isFilename()) {
  5047. CmdArgs.push_back("-o");
  5048. CmdArgs.push_back(Output.getFilename());
  5049. } else {
  5050. assert(Output.isNothing() && "Invalid output.");
  5051. }
  5052. addDashXForInput(Args, Input, CmdArgs);
  5053. if (Input.isFilename())
  5054. CmdArgs.push_back(Input.getFilename());
  5055. else
  5056. Input.getInputArg().renderAsInput(Args, CmdArgs);
  5057. Args.AddAllArgs(CmdArgs, options::OPT_undef);
  5058. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5059. // Optionally embed the -cc1 level arguments into the debug info, for build
  5060. // analysis.
  5061. if (getToolChain().UseDwarfDebugFlags()) {
  5062. ArgStringList OriginalArgs;
  5063. for (const auto &Arg : Args)
  5064. Arg->render(Args, OriginalArgs);
  5065. SmallString<256> Flags;
  5066. Flags += Exec;
  5067. for (const char *OriginalArg : OriginalArgs) {
  5068. SmallString<128> EscapedArg;
  5069. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  5070. Flags += " ";
  5071. Flags += EscapedArg;
  5072. }
  5073. CmdArgs.push_back("-dwarf-debug-flags");
  5074. CmdArgs.push_back(Args.MakeArgString(Flags));
  5075. }
  5076. // Add the split debug info name to the command lines here so we
  5077. // can propagate it to the backend.
  5078. bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
  5079. (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
  5080. isa<BackendJobAction>(JA));
  5081. const char *SplitDwarfOut;
  5082. if (SplitDwarf) {
  5083. CmdArgs.push_back("-split-dwarf-file");
  5084. SplitDwarfOut = SplitDebugName(Args, Input);
  5085. CmdArgs.push_back(SplitDwarfOut);
  5086. }
  5087. // Host-side cuda compilation receives device-side outputs as Inputs[1...].
  5088. // Include them with -fcuda-include-gpubinary.
  5089. if (IsCuda && Inputs.size() > 1)
  5090. for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
  5091. CmdArgs.push_back("-fcuda-include-gpubinary");
  5092. CmdArgs.push_back(I->getFilename());
  5093. }
  5094. // Finally add the compile command to the compilation.
  5095. if (Args.hasArg(options::OPT__SLASH_fallback) &&
  5096. Output.getType() == types::TY_Object &&
  5097. (InputType == types::TY_C || InputType == types::TY_CXX)) {
  5098. auto CLCommand =
  5099. getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
  5100. C.addCommand(llvm::make_unique<FallbackCommand>(
  5101. JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
  5102. } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
  5103. isa<PrecompileJobAction>(JA)) {
  5104. // In /fallback builds, run the main compilation even if the pch generation
  5105. // fails, so that the main compilation's fallback to cl.exe runs.
  5106. C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
  5107. CmdArgs, Inputs));
  5108. } else {
  5109. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5110. }
  5111. // Handle the debug info splitting at object creation time if we're
  5112. // creating an object.
  5113. // TODO: Currently only works on linux with newer objcopy.
  5114. if (SplitDwarf && Output.getType() == types::TY_Object)
  5115. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
  5116. if (Arg *A = Args.getLastArg(options::OPT_pg))
  5117. if (Args.hasArg(options::OPT_fomit_frame_pointer))
  5118. D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
  5119. << A->getAsString(Args);
  5120. // Claim some arguments which clang supports automatically.
  5121. // -fpch-preprocess is used with gcc to add a special marker in the output to
  5122. // include the PCH file. Clang's PTH solution is completely transparent, so we
  5123. // do not need to deal with it at all.
  5124. Args.ClaimAllArgs(options::OPT_fpch_preprocess);
  5125. // Claim some arguments which clang doesn't support, but we don't
  5126. // care to warn the user about.
  5127. Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
  5128. Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
  5129. // Disable warnings for clang -E -emit-llvm foo.c
  5130. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5131. }
  5132. /// Add options related to the Objective-C runtime/ABI.
  5133. ///
  5134. /// Returns true if the runtime is non-fragile.
  5135. ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
  5136. ArgStringList &cmdArgs,
  5137. RewriteKind rewriteKind) const {
  5138. // Look for the controlling runtime option.
  5139. Arg *runtimeArg =
  5140. args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
  5141. options::OPT_fobjc_runtime_EQ);
  5142. // Just forward -fobjc-runtime= to the frontend. This supercedes
  5143. // options about fragility.
  5144. if (runtimeArg &&
  5145. runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
  5146. ObjCRuntime runtime;
  5147. StringRef value = runtimeArg->getValue();
  5148. if (runtime.tryParse(value)) {
  5149. getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
  5150. << value;
  5151. }
  5152. runtimeArg->render(args, cmdArgs);
  5153. return runtime;
  5154. }
  5155. // Otherwise, we'll need the ABI "version". Version numbers are
  5156. // slightly confusing for historical reasons:
  5157. // 1 - Traditional "fragile" ABI
  5158. // 2 - Non-fragile ABI, version 1
  5159. // 3 - Non-fragile ABI, version 2
  5160. unsigned objcABIVersion = 1;
  5161. // If -fobjc-abi-version= is present, use that to set the version.
  5162. if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
  5163. StringRef value = abiArg->getValue();
  5164. if (value == "1")
  5165. objcABIVersion = 1;
  5166. else if (value == "2")
  5167. objcABIVersion = 2;
  5168. else if (value == "3")
  5169. objcABIVersion = 3;
  5170. else
  5171. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
  5172. } else {
  5173. // Otherwise, determine if we are using the non-fragile ABI.
  5174. bool nonFragileABIIsDefault =
  5175. (rewriteKind == RK_NonFragile ||
  5176. (rewriteKind == RK_None &&
  5177. getToolChain().IsObjCNonFragileABIDefault()));
  5178. if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
  5179. options::OPT_fno_objc_nonfragile_abi,
  5180. nonFragileABIIsDefault)) {
  5181. // Determine the non-fragile ABI version to use.
  5182. #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
  5183. unsigned nonFragileABIVersion = 1;
  5184. #else
  5185. unsigned nonFragileABIVersion = 2;
  5186. #endif
  5187. if (Arg *abiArg =
  5188. args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
  5189. StringRef value = abiArg->getValue();
  5190. if (value == "1")
  5191. nonFragileABIVersion = 1;
  5192. else if (value == "2")
  5193. nonFragileABIVersion = 2;
  5194. else
  5195. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  5196. << value;
  5197. }
  5198. objcABIVersion = 1 + nonFragileABIVersion;
  5199. } else {
  5200. objcABIVersion = 1;
  5201. }
  5202. }
  5203. // We don't actually care about the ABI version other than whether
  5204. // it's non-fragile.
  5205. bool isNonFragile = objcABIVersion != 1;
  5206. // If we have no runtime argument, ask the toolchain for its default runtime.
  5207. // However, the rewriter only really supports the Mac runtime, so assume that.
  5208. ObjCRuntime runtime;
  5209. if (!runtimeArg) {
  5210. switch (rewriteKind) {
  5211. case RK_None:
  5212. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  5213. break;
  5214. case RK_Fragile:
  5215. runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
  5216. break;
  5217. case RK_NonFragile:
  5218. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  5219. break;
  5220. }
  5221. // -fnext-runtime
  5222. } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
  5223. // On Darwin, make this use the default behavior for the toolchain.
  5224. if (getToolChain().getTriple().isOSDarwin()) {
  5225. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  5226. // Otherwise, build for a generic macosx port.
  5227. } else {
  5228. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  5229. }
  5230. // -fgnu-runtime
  5231. } else {
  5232. assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
  5233. // Legacy behaviour is to target the gnustep runtime if we are in
  5234. // non-fragile mode or the GCC runtime in fragile mode.
  5235. if (isNonFragile)
  5236. runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
  5237. else
  5238. runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
  5239. }
  5240. cmdArgs.push_back(
  5241. args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
  5242. return runtime;
  5243. }
  5244. static bool maybeConsumeDash(const std::string &EH, size_t &I) {
  5245. bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
  5246. I += HaveDash;
  5247. return !HaveDash;
  5248. }
  5249. namespace {
  5250. struct EHFlags {
  5251. bool Synch = false;
  5252. bool Asynch = false;
  5253. bool NoUnwindC = false;
  5254. };
  5255. } // end anonymous namespace
  5256. /// /EH controls whether to run destructor cleanups when exceptions are
  5257. /// thrown. There are three modifiers:
  5258. /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
  5259. /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
  5260. /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
  5261. /// - c: Assume that extern "C" functions are implicitly nounwind.
  5262. /// The default is /EHs-c-, meaning cleanups are disabled.
  5263. static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
  5264. EHFlags EH;
  5265. std::vector<std::string> EHArgs =
  5266. Args.getAllArgValues(options::OPT__SLASH_EH);
  5267. for (auto EHVal : EHArgs) {
  5268. for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
  5269. switch (EHVal[I]) {
  5270. case 'a':
  5271. EH.Asynch = maybeConsumeDash(EHVal, I);
  5272. if (EH.Asynch)
  5273. EH.Synch = false;
  5274. continue;
  5275. case 'c':
  5276. EH.NoUnwindC = maybeConsumeDash(EHVal, I);
  5277. continue;
  5278. case 's':
  5279. EH.Synch = maybeConsumeDash(EHVal, I);
  5280. if (EH.Synch)
  5281. EH.Asynch = false;
  5282. continue;
  5283. default:
  5284. break;
  5285. }
  5286. D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
  5287. break;
  5288. }
  5289. }
  5290. // The /GX, /GX- flags are only processed if there are not /EH flags.
  5291. // The default is that /GX is not specified.
  5292. if (EHArgs.empty() &&
  5293. Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
  5294. /*default=*/false)) {
  5295. EH.Synch = true;
  5296. EH.NoUnwindC = true;
  5297. }
  5298. return EH;
  5299. }
  5300. void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
  5301. ArgStringList &CmdArgs,
  5302. codegenoptions::DebugInfoKind *DebugInfoKind,
  5303. bool *EmitCodeView) const {
  5304. unsigned RTOptionID = options::OPT__SLASH_MT;
  5305. if (Args.hasArg(options::OPT__SLASH_LDd))
  5306. // The /LDd option implies /MTd. The dependent lib part can be overridden,
  5307. // but defining _DEBUG is sticky.
  5308. RTOptionID = options::OPT__SLASH_MTd;
  5309. if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
  5310. RTOptionID = A->getOption().getID();
  5311. StringRef FlagForCRT;
  5312. switch (RTOptionID) {
  5313. case options::OPT__SLASH_MD:
  5314. if (Args.hasArg(options::OPT__SLASH_LDd))
  5315. CmdArgs.push_back("-D_DEBUG");
  5316. CmdArgs.push_back("-D_MT");
  5317. CmdArgs.push_back("-D_DLL");
  5318. FlagForCRT = "--dependent-lib=msvcrt";
  5319. break;
  5320. case options::OPT__SLASH_MDd:
  5321. CmdArgs.push_back("-D_DEBUG");
  5322. CmdArgs.push_back("-D_MT");
  5323. CmdArgs.push_back("-D_DLL");
  5324. FlagForCRT = "--dependent-lib=msvcrtd";
  5325. break;
  5326. case options::OPT__SLASH_MT:
  5327. if (Args.hasArg(options::OPT__SLASH_LDd))
  5328. CmdArgs.push_back("-D_DEBUG");
  5329. CmdArgs.push_back("-D_MT");
  5330. FlagForCRT = "--dependent-lib=libcmt";
  5331. break;
  5332. case options::OPT__SLASH_MTd:
  5333. CmdArgs.push_back("-D_DEBUG");
  5334. CmdArgs.push_back("-D_MT");
  5335. FlagForCRT = "--dependent-lib=libcmtd";
  5336. break;
  5337. default:
  5338. llvm_unreachable("Unexpected option ID.");
  5339. }
  5340. if (Args.hasArg(options::OPT__SLASH_Zl)) {
  5341. CmdArgs.push_back("-D_VC_NODEFAULTLIB");
  5342. } else {
  5343. CmdArgs.push_back(FlagForCRT.data());
  5344. // This provides POSIX compatibility (maps 'open' to '_open'), which most
  5345. // users want. The /Za flag to cl.exe turns this off, but it's not
  5346. // implemented in clang.
  5347. CmdArgs.push_back("--dependent-lib=oldnames");
  5348. }
  5349. // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
  5350. // would produce interleaved output, so ignore /showIncludes in such cases.
  5351. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
  5352. if (Arg *A = Args.getLastArg(options::OPT_show_includes))
  5353. A->render(Args, CmdArgs);
  5354. // This controls whether or not we emit RTTI data for polymorphic types.
  5355. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  5356. /*default=*/false))
  5357. CmdArgs.push_back("-fno-rtti-data");
  5358. // Emit CodeView if -Z7 is present.
  5359. *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
  5360. if (*EmitCodeView)
  5361. *DebugInfoKind = codegenoptions::LimitedDebugInfo;
  5362. if (*EmitCodeView)
  5363. CmdArgs.push_back("-gcodeview");
  5364. const Driver &D = getToolChain().getDriver();
  5365. EHFlags EH = parseClangCLEHFlags(D, Args);
  5366. if (EH.Synch || EH.Asynch) {
  5367. if (types::isCXX(InputType))
  5368. CmdArgs.push_back("-fcxx-exceptions");
  5369. CmdArgs.push_back("-fexceptions");
  5370. }
  5371. if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
  5372. CmdArgs.push_back("-fexternc-nounwind");
  5373. // /EP should expand to -E -P.
  5374. if (Args.hasArg(options::OPT__SLASH_EP)) {
  5375. CmdArgs.push_back("-E");
  5376. CmdArgs.push_back("-P");
  5377. }
  5378. unsigned VolatileOptionID;
  5379. if (getToolChain().getArch() == llvm::Triple::x86_64 ||
  5380. getToolChain().getArch() == llvm::Triple::x86)
  5381. VolatileOptionID = options::OPT__SLASH_volatile_ms;
  5382. else
  5383. VolatileOptionID = options::OPT__SLASH_volatile_iso;
  5384. if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
  5385. VolatileOptionID = A->getOption().getID();
  5386. if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
  5387. CmdArgs.push_back("-fms-volatile");
  5388. Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
  5389. Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
  5390. if (MostGeneralArg && BestCaseArg)
  5391. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5392. << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
  5393. if (MostGeneralArg) {
  5394. Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
  5395. Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
  5396. Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
  5397. Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
  5398. Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
  5399. if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
  5400. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5401. << FirstConflict->getAsString(Args)
  5402. << SecondConflict->getAsString(Args);
  5403. if (SingleArg)
  5404. CmdArgs.push_back("-fms-memptr-rep=single");
  5405. else if (MultipleArg)
  5406. CmdArgs.push_back("-fms-memptr-rep=multiple");
  5407. else
  5408. CmdArgs.push_back("-fms-memptr-rep=virtual");
  5409. }
  5410. if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
  5411. A->render(Args, CmdArgs);
  5412. if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
  5413. CmdArgs.push_back("-fdiagnostics-format");
  5414. if (Args.hasArg(options::OPT__SLASH_fallback))
  5415. CmdArgs.push_back("msvc-fallback");
  5416. else
  5417. CmdArgs.push_back("msvc");
  5418. }
  5419. }
  5420. visualstudio::Compiler *Clang::getCLFallback() const {
  5421. if (!CLFallback)
  5422. CLFallback.reset(new visualstudio::Compiler(getToolChain()));
  5423. return CLFallback.get();
  5424. }
  5425. void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
  5426. ArgStringList &CmdArgs) const {
  5427. StringRef CPUName;
  5428. StringRef ABIName;
  5429. const llvm::Triple &Triple = getToolChain().getTriple();
  5430. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  5431. CmdArgs.push_back("-target-abi");
  5432. CmdArgs.push_back(ABIName.data());
  5433. }
  5434. void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
  5435. const InputInfo &Output, const InputInfoList &Inputs,
  5436. const ArgList &Args,
  5437. const char *LinkingOutput) const {
  5438. ArgStringList CmdArgs;
  5439. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  5440. const InputInfo &Input = Inputs[0];
  5441. std::string TripleStr =
  5442. getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
  5443. const llvm::Triple Triple(TripleStr);
  5444. // Don't warn about "clang -w -c foo.s"
  5445. Args.ClaimAllArgs(options::OPT_w);
  5446. // and "clang -emit-llvm -c foo.s"
  5447. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5448. claimNoWarnArgs(Args);
  5449. // Invoke ourselves in -cc1as mode.
  5450. //
  5451. // FIXME: Implement custom jobs for internal actions.
  5452. CmdArgs.push_back("-cc1as");
  5453. // Add the "effective" target triple.
  5454. CmdArgs.push_back("-triple");
  5455. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  5456. // Set the output mode, we currently only expect to be used as a real
  5457. // assembler.
  5458. CmdArgs.push_back("-filetype");
  5459. CmdArgs.push_back("obj");
  5460. // Set the main file name, so that debug info works even with
  5461. // -save-temps or preprocessed assembly.
  5462. CmdArgs.push_back("-main-file-name");
  5463. CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
  5464. // Add the target cpu
  5465. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
  5466. if (!CPU.empty()) {
  5467. CmdArgs.push_back("-target-cpu");
  5468. CmdArgs.push_back(Args.MakeArgString(CPU));
  5469. }
  5470. // Add the target features
  5471. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
  5472. // Ignore explicit -force_cpusubtype_ALL option.
  5473. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  5474. // Pass along any -I options so we get proper .include search paths.
  5475. Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
  5476. // Determine the original source input.
  5477. const Action *SourceAction = &JA;
  5478. while (SourceAction->getKind() != Action::InputClass) {
  5479. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  5480. SourceAction = SourceAction->getInputs()[0];
  5481. }
  5482. // Forward -g and handle debug info related flags, assuming we are dealing
  5483. // with an actual assembly file.
  5484. bool WantDebug = false;
  5485. unsigned DwarfVersion = 0;
  5486. Args.ClaimAllArgs(options::OPT_g_Group);
  5487. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  5488. WantDebug = !A->getOption().matches(options::OPT_g0) &&
  5489. !A->getOption().matches(options::OPT_ggdb0);
  5490. if (WantDebug)
  5491. DwarfVersion = DwarfVersionNum(A->getSpelling());
  5492. }
  5493. if (DwarfVersion == 0)
  5494. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  5495. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  5496. if (SourceAction->getType() == types::TY_Asm ||
  5497. SourceAction->getType() == types::TY_PP_Asm) {
  5498. // You might think that it would be ok to set DebugInfoKind outside of
  5499. // the guard for source type, however there is a test which asserts
  5500. // that some assembler invocation receives no -debug-info-kind,
  5501. // and it's not clear whether that test is just overly restrictive.
  5502. DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
  5503. : codegenoptions::NoDebugInfo);
  5504. // Add the -fdebug-compilation-dir flag if needed.
  5505. addDebugCompDirArg(Args, CmdArgs);
  5506. // Set the AT_producer to the clang version when using the integrated
  5507. // assembler on assembly source files.
  5508. CmdArgs.push_back("-dwarf-debug-producer");
  5509. std::string QuotedClangVersion("'" + getClangFullVersion() + "'");
  5510. CmdArgs.push_back(Args.MakeArgString(QuotedClangVersion));
  5511. // And pass along -I options
  5512. Args.AddAllArgs(CmdArgs, options::OPT_I);
  5513. }
  5514. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
  5515. llvm::DebuggerKind::Default);
  5516. // Handle -fPIC et al -- the relocation-model affects the assembler
  5517. // for some targets.
  5518. llvm::Reloc::Model RelocationModel;
  5519. unsigned PICLevel;
  5520. bool IsPIE;
  5521. std::tie(RelocationModel, PICLevel, IsPIE) =
  5522. ParsePICArgs(getToolChain(), Triple, Args);
  5523. const char *RMName = RelocationModelName(RelocationModel);
  5524. if (RMName) {
  5525. CmdArgs.push_back("-mrelocation-model");
  5526. CmdArgs.push_back(RMName);
  5527. }
  5528. // Optionally embed the -cc1as level arguments into the debug info, for build
  5529. // analysis.
  5530. if (getToolChain().UseDwarfDebugFlags()) {
  5531. ArgStringList OriginalArgs;
  5532. for (const auto &Arg : Args)
  5533. Arg->render(Args, OriginalArgs);
  5534. SmallString<256> Flags;
  5535. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5536. Flags += Exec;
  5537. for (const char *OriginalArg : OriginalArgs) {
  5538. SmallString<128> EscapedArg;
  5539. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  5540. Flags += " ";
  5541. Flags += EscapedArg;
  5542. }
  5543. CmdArgs.push_back("-dwarf-debug-flags");
  5544. CmdArgs.push_back(Args.MakeArgString(Flags));
  5545. }
  5546. // FIXME: Add -static support, once we have it.
  5547. // Add target specific flags.
  5548. switch (getToolChain().getArch()) {
  5549. default:
  5550. break;
  5551. case llvm::Triple::mips:
  5552. case llvm::Triple::mipsel:
  5553. case llvm::Triple::mips64:
  5554. case llvm::Triple::mips64el:
  5555. AddMIPSTargetArgs(Args, CmdArgs);
  5556. break;
  5557. }
  5558. // Consume all the warning flags. Usually this would be handled more
  5559. // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
  5560. // doesn't handle that so rather than warning about unused flags that are
  5561. // actually used, we'll lie by omission instead.
  5562. // FIXME: Stop lying and consume only the appropriate driver flags
  5563. Args.ClaimAllArgs(options::OPT_W_Group);
  5564. CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
  5565. getToolChain().getDriver());
  5566. Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
  5567. assert(Output.isFilename() && "Unexpected lipo output.");
  5568. CmdArgs.push_back("-o");
  5569. CmdArgs.push_back(Output.getFilename());
  5570. assert(Input.isFilename() && "Invalid input.");
  5571. CmdArgs.push_back(Input.getFilename());
  5572. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5573. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5574. // Handle the debug info splitting at object creation time if we're
  5575. // creating an object.
  5576. // TODO: Currently only works on linux with newer objcopy.
  5577. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  5578. getToolChain().getTriple().isOSLinux())
  5579. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  5580. SplitDebugName(Args, Input));
  5581. }
  5582. void GnuTool::anchor() {}
  5583. void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
  5584. const InputInfo &Output,
  5585. const InputInfoList &Inputs, const ArgList &Args,
  5586. const char *LinkingOutput) const {
  5587. const Driver &D = getToolChain().getDriver();
  5588. ArgStringList CmdArgs;
  5589. for (const auto &A : Args) {
  5590. if (forwardToGCC(A->getOption())) {
  5591. // It is unfortunate that we have to claim here, as this means
  5592. // we will basically never report anything interesting for
  5593. // platforms using a generic gcc, even if we are just using gcc
  5594. // to get to the assembler.
  5595. A->claim();
  5596. // Don't forward any -g arguments to assembly steps.
  5597. if (isa<AssembleJobAction>(JA) &&
  5598. A->getOption().matches(options::OPT_g_Group))
  5599. continue;
  5600. // Don't forward any -W arguments to assembly and link steps.
  5601. if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
  5602. A->getOption().matches(options::OPT_W_Group))
  5603. continue;
  5604. A->render(Args, CmdArgs);
  5605. }
  5606. }
  5607. RenderExtraToolArgs(JA, CmdArgs);
  5608. // If using a driver driver, force the arch.
  5609. if (getToolChain().getTriple().isOSDarwin()) {
  5610. CmdArgs.push_back("-arch");
  5611. CmdArgs.push_back(
  5612. Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
  5613. }
  5614. // Try to force gcc to match the tool chain we want, if we recognize
  5615. // the arch.
  5616. //
  5617. // FIXME: The triple class should directly provide the information we want
  5618. // here.
  5619. switch (getToolChain().getArch()) {
  5620. default:
  5621. break;
  5622. case llvm::Triple::x86:
  5623. case llvm::Triple::ppc:
  5624. CmdArgs.push_back("-m32");
  5625. break;
  5626. case llvm::Triple::x86_64:
  5627. case llvm::Triple::ppc64:
  5628. case llvm::Triple::ppc64le:
  5629. CmdArgs.push_back("-m64");
  5630. break;
  5631. case llvm::Triple::sparcel:
  5632. CmdArgs.push_back("-EL");
  5633. break;
  5634. }
  5635. if (Output.isFilename()) {
  5636. CmdArgs.push_back("-o");
  5637. CmdArgs.push_back(Output.getFilename());
  5638. } else {
  5639. assert(Output.isNothing() && "Unexpected output");
  5640. CmdArgs.push_back("-fsyntax-only");
  5641. }
  5642. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5643. // Only pass -x if gcc will understand it; otherwise hope gcc
  5644. // understands the suffix correctly. The main use case this would go
  5645. // wrong in is for linker inputs if they happened to have an odd
  5646. // suffix; really the only way to get this to happen is a command
  5647. // like '-x foobar a.c' which will treat a.c like a linker input.
  5648. //
  5649. // FIXME: For the linker case specifically, can we safely convert
  5650. // inputs into '-Wl,' options?
  5651. for (const auto &II : Inputs) {
  5652. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5653. if (types::isLLVMIR(II.getType()))
  5654. D.Diag(diag::err_drv_no_linker_llvm_support)
  5655. << getToolChain().getTripleString();
  5656. else if (II.getType() == types::TY_AST)
  5657. D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
  5658. else if (II.getType() == types::TY_ModuleFile)
  5659. D.Diag(diag::err_drv_no_module_support)
  5660. << getToolChain().getTripleString();
  5661. if (types::canTypeBeUserSpecified(II.getType())) {
  5662. CmdArgs.push_back("-x");
  5663. CmdArgs.push_back(types::getTypeName(II.getType()));
  5664. }
  5665. if (II.isFilename())
  5666. CmdArgs.push_back(II.getFilename());
  5667. else {
  5668. const Arg &A = II.getInputArg();
  5669. // Reverse translate some rewritten options.
  5670. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
  5671. CmdArgs.push_back("-lstdc++");
  5672. continue;
  5673. }
  5674. // Don't render as input, we need gcc to do the translations.
  5675. A.render(Args, CmdArgs);
  5676. }
  5677. }
  5678. const std::string customGCCName = D.getCCCGenericGCCName();
  5679. const char *GCCName;
  5680. if (!customGCCName.empty())
  5681. GCCName = customGCCName.c_str();
  5682. else if (D.CCCIsCXX()) {
  5683. GCCName = "g++";
  5684. } else
  5685. GCCName = "gcc";
  5686. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
  5687. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5688. }
  5689. void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
  5690. ArgStringList &CmdArgs) const {
  5691. CmdArgs.push_back("-E");
  5692. }
  5693. void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
  5694. ArgStringList &CmdArgs) const {
  5695. const Driver &D = getToolChain().getDriver();
  5696. switch (JA.getType()) {
  5697. // If -flto, etc. are present then make sure not to force assembly output.
  5698. case types::TY_LLVM_IR:
  5699. case types::TY_LTO_IR:
  5700. case types::TY_LLVM_BC:
  5701. case types::TY_LTO_BC:
  5702. CmdArgs.push_back("-c");
  5703. break;
  5704. // We assume we've got an "integrated" assembler in that gcc will produce an
  5705. // object file itself.
  5706. case types::TY_Object:
  5707. CmdArgs.push_back("-c");
  5708. break;
  5709. case types::TY_PP_Asm:
  5710. CmdArgs.push_back("-S");
  5711. break;
  5712. case types::TY_Nothing:
  5713. CmdArgs.push_back("-fsyntax-only");
  5714. break;
  5715. default:
  5716. D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
  5717. }
  5718. }
  5719. void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
  5720. ArgStringList &CmdArgs) const {
  5721. // The types are (hopefully) good enough.
  5722. }
  5723. // Hexagon tools start.
  5724. void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
  5725. ArgStringList &CmdArgs) const {
  5726. }
  5727. void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  5728. const InputInfo &Output,
  5729. const InputInfoList &Inputs,
  5730. const ArgList &Args,
  5731. const char *LinkingOutput) const {
  5732. claimNoWarnArgs(Args);
  5733. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  5734. const Driver &D = HTC.getDriver();
  5735. ArgStringList CmdArgs;
  5736. std::string MArchString = "-march=hexagon";
  5737. CmdArgs.push_back(Args.MakeArgString(MArchString));
  5738. RenderExtraToolArgs(JA, CmdArgs);
  5739. std::string AsName = "hexagon-llvm-mc";
  5740. std::string MCpuString = "-mcpu=hexagon" +
  5741. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  5742. CmdArgs.push_back("-filetype=obj");
  5743. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  5744. if (Output.isFilename()) {
  5745. CmdArgs.push_back("-o");
  5746. CmdArgs.push_back(Output.getFilename());
  5747. } else {
  5748. assert(Output.isNothing() && "Unexpected output");
  5749. CmdArgs.push_back("-fsyntax-only");
  5750. }
  5751. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  5752. std::string N = llvm::utostr(G.getValue());
  5753. CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
  5754. }
  5755. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5756. // Only pass -x if gcc will understand it; otherwise hope gcc
  5757. // understands the suffix correctly. The main use case this would go
  5758. // wrong in is for linker inputs if they happened to have an odd
  5759. // suffix; really the only way to get this to happen is a command
  5760. // like '-x foobar a.c' which will treat a.c like a linker input.
  5761. //
  5762. // FIXME: For the linker case specifically, can we safely convert
  5763. // inputs into '-Wl,' options?
  5764. for (const auto &II : Inputs) {
  5765. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5766. if (types::isLLVMIR(II.getType()))
  5767. D.Diag(clang::diag::err_drv_no_linker_llvm_support)
  5768. << HTC.getTripleString();
  5769. else if (II.getType() == types::TY_AST)
  5770. D.Diag(clang::diag::err_drv_no_ast_support)
  5771. << HTC.getTripleString();
  5772. else if (II.getType() == types::TY_ModuleFile)
  5773. D.Diag(diag::err_drv_no_module_support)
  5774. << HTC.getTripleString();
  5775. if (II.isFilename())
  5776. CmdArgs.push_back(II.getFilename());
  5777. else
  5778. // Don't render as input, we need gcc to do the translations.
  5779. // FIXME: What is this?
  5780. II.getInputArg().render(Args, CmdArgs);
  5781. }
  5782. auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
  5783. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5784. }
  5785. void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
  5786. ArgStringList &CmdArgs) const {
  5787. }
  5788. static void
  5789. constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
  5790. const toolchains::HexagonToolChain &HTC,
  5791. const InputInfo &Output, const InputInfoList &Inputs,
  5792. const ArgList &Args, ArgStringList &CmdArgs,
  5793. const char *LinkingOutput) {
  5794. const Driver &D = HTC.getDriver();
  5795. //----------------------------------------------------------------------------
  5796. //
  5797. //----------------------------------------------------------------------------
  5798. bool IsStatic = Args.hasArg(options::OPT_static);
  5799. bool IsShared = Args.hasArg(options::OPT_shared);
  5800. bool IsPIE = Args.hasArg(options::OPT_pie);
  5801. bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
  5802. bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
  5803. bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
  5804. bool UseG0 = false;
  5805. bool UseShared = IsShared && !IsStatic;
  5806. //----------------------------------------------------------------------------
  5807. // Silence warnings for various options
  5808. //----------------------------------------------------------------------------
  5809. Args.ClaimAllArgs(options::OPT_g_Group);
  5810. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5811. Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
  5812. // handled somewhere else.
  5813. Args.ClaimAllArgs(options::OPT_static_libgcc);
  5814. //----------------------------------------------------------------------------
  5815. //
  5816. //----------------------------------------------------------------------------
  5817. if (Args.hasArg(options::OPT_s))
  5818. CmdArgs.push_back("-s");
  5819. if (Args.hasArg(options::OPT_r))
  5820. CmdArgs.push_back("-r");
  5821. for (const auto &Opt : HTC.ExtraOpts)
  5822. CmdArgs.push_back(Opt.c_str());
  5823. CmdArgs.push_back("-march=hexagon");
  5824. std::string CpuVer =
  5825. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  5826. std::string MCpuString = "-mcpu=hexagon" + CpuVer;
  5827. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  5828. if (IsShared) {
  5829. CmdArgs.push_back("-shared");
  5830. // The following should be the default, but doing as hexagon-gcc does.
  5831. CmdArgs.push_back("-call_shared");
  5832. }
  5833. if (IsStatic)
  5834. CmdArgs.push_back("-static");
  5835. if (IsPIE && !IsShared)
  5836. CmdArgs.push_back("-pie");
  5837. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  5838. std::string N = llvm::utostr(G.getValue());
  5839. CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
  5840. UseG0 = G.getValue() == 0;
  5841. }
  5842. //----------------------------------------------------------------------------
  5843. //
  5844. //----------------------------------------------------------------------------
  5845. CmdArgs.push_back("-o");
  5846. CmdArgs.push_back(Output.getFilename());
  5847. //----------------------------------------------------------------------------
  5848. // moslib
  5849. //----------------------------------------------------------------------------
  5850. std::vector<std::string> OsLibs;
  5851. bool HasStandalone = false;
  5852. for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
  5853. A->claim();
  5854. OsLibs.emplace_back(A->getValue());
  5855. HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
  5856. }
  5857. if (OsLibs.empty()) {
  5858. OsLibs.push_back("standalone");
  5859. HasStandalone = true;
  5860. }
  5861. //----------------------------------------------------------------------------
  5862. // Start Files
  5863. //----------------------------------------------------------------------------
  5864. const std::string MCpuSuffix = "/" + CpuVer;
  5865. const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
  5866. const std::string RootDir =
  5867. HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
  5868. const std::string StartSubDir =
  5869. "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
  5870. auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
  5871. const char *Name) -> std::string {
  5872. std::string RelName = SubDir + Name;
  5873. std::string P = HTC.GetFilePath(RelName.c_str());
  5874. if (llvm::sys::fs::exists(P))
  5875. return P;
  5876. return RootDir + RelName;
  5877. };
  5878. if (IncStdLib && IncStartFiles) {
  5879. if (!IsShared) {
  5880. if (HasStandalone) {
  5881. std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
  5882. CmdArgs.push_back(Args.MakeArgString(Crt0SA));
  5883. }
  5884. std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
  5885. CmdArgs.push_back(Args.MakeArgString(Crt0));
  5886. }
  5887. std::string Init = UseShared
  5888. ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
  5889. : Find(RootDir, StartSubDir, "/init.o");
  5890. CmdArgs.push_back(Args.MakeArgString(Init));
  5891. }
  5892. //----------------------------------------------------------------------------
  5893. // Library Search Paths
  5894. //----------------------------------------------------------------------------
  5895. const ToolChain::path_list &LibPaths = HTC.getFilePaths();
  5896. for (const auto &LibPath : LibPaths)
  5897. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
  5898. //----------------------------------------------------------------------------
  5899. //
  5900. //----------------------------------------------------------------------------
  5901. Args.AddAllArgs(CmdArgs,
  5902. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  5903. options::OPT_t, options::OPT_u_Group});
  5904. AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
  5905. //----------------------------------------------------------------------------
  5906. // Libraries
  5907. //----------------------------------------------------------------------------
  5908. if (IncStdLib && IncDefLibs) {
  5909. if (D.CCCIsCXX()) {
  5910. HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
  5911. CmdArgs.push_back("-lm");
  5912. }
  5913. CmdArgs.push_back("--start-group");
  5914. if (!IsShared) {
  5915. for (const std::string &Lib : OsLibs)
  5916. CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
  5917. CmdArgs.push_back("-lc");
  5918. }
  5919. CmdArgs.push_back("-lgcc");
  5920. CmdArgs.push_back("--end-group");
  5921. }
  5922. //----------------------------------------------------------------------------
  5923. // End files
  5924. //----------------------------------------------------------------------------
  5925. if (IncStdLib && IncStartFiles) {
  5926. std::string Fini = UseShared
  5927. ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
  5928. : Find(RootDir, StartSubDir, "/fini.o");
  5929. CmdArgs.push_back(Args.MakeArgString(Fini));
  5930. }
  5931. }
  5932. void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5933. const InputInfo &Output,
  5934. const InputInfoList &Inputs,
  5935. const ArgList &Args,
  5936. const char *LinkingOutput) const {
  5937. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  5938. ArgStringList CmdArgs;
  5939. constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
  5940. LinkingOutput);
  5941. std::string Linker = HTC.GetProgramPath("hexagon-link");
  5942. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  5943. CmdArgs, Inputs));
  5944. }
  5945. // Hexagon tools end.
  5946. void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5947. const InputInfo &Output,
  5948. const InputInfoList &Inputs,
  5949. const ArgList &Args,
  5950. const char *LinkingOutput) const {
  5951. std::string Linker = getToolChain().GetProgramPath(getShortName());
  5952. ArgStringList CmdArgs;
  5953. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  5954. CmdArgs.push_back(Output.getFilename());
  5955. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  5956. CmdArgs, Inputs));
  5957. }
  5958. // AMDGPU tools end.
  5959. wasm::Linker::Linker(const ToolChain &TC)
  5960. : GnuTool("wasm::Linker", "lld", TC) {}
  5961. bool wasm::Linker::isLinkJob() const {
  5962. return true;
  5963. }
  5964. bool wasm::Linker::hasIntegratedCPP() const {
  5965. return false;
  5966. }
  5967. void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5968. const InputInfo &Output,
  5969. const InputInfoList &Inputs,
  5970. const ArgList &Args,
  5971. const char *LinkingOutput) const {
  5972. const ToolChain &ToolChain = getToolChain();
  5973. const Driver &D = ToolChain.getDriver();
  5974. const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
  5975. ArgStringList CmdArgs;
  5976. CmdArgs.push_back("-flavor");
  5977. CmdArgs.push_back("ld");
  5978. // Enable garbage collection of unused input sections by default, since code
  5979. // size is of particular importance. This is significantly facilitated by
  5980. // the enabling of -ffunction-sections and -fdata-sections in
  5981. // Clang::ConstructJob.
  5982. if (areOptimizationsEnabled(Args))
  5983. CmdArgs.push_back("--gc-sections");
  5984. if (Args.hasArg(options::OPT_rdynamic))
  5985. CmdArgs.push_back("-export-dynamic");
  5986. if (Args.hasArg(options::OPT_s))
  5987. CmdArgs.push_back("--strip-all");
  5988. if (Args.hasArg(options::OPT_shared))
  5989. CmdArgs.push_back("-shared");
  5990. if (Args.hasArg(options::OPT_static))
  5991. CmdArgs.push_back("-Bstatic");
  5992. Args.AddAllArgs(CmdArgs, options::OPT_L);
  5993. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  5994. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  5995. if (Args.hasArg(options::OPT_shared))
  5996. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("rcrt1.o")));
  5997. else if (Args.hasArg(options::OPT_pie))
  5998. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
  5999. else
  6000. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  6001. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  6002. }
  6003. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  6004. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6005. if (D.CCCIsCXX())
  6006. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  6007. if (Args.hasArg(options::OPT_pthread))
  6008. CmdArgs.push_back("-lpthread");
  6009. CmdArgs.push_back("-lc");
  6010. CmdArgs.push_back("-lcompiler_rt");
  6011. }
  6012. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6013. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  6014. CmdArgs.push_back("-o");
  6015. CmdArgs.push_back(Output.getFilename());
  6016. C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
  6017. }
  6018. const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
  6019. std::string MArch;
  6020. if (!Arch.empty())
  6021. MArch = Arch;
  6022. else
  6023. MArch = Triple.getArchName();
  6024. MArch = StringRef(MArch).split("+").first.lower();
  6025. // Handle -march=native.
  6026. if (MArch == "native") {
  6027. std::string CPU = llvm::sys::getHostCPUName();
  6028. if (CPU != "generic") {
  6029. // Translate the native cpu into the architecture suffix for that CPU.
  6030. StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
  6031. // If there is no valid architecture suffix for this CPU we don't know how
  6032. // to handle it, so return no architecture.
  6033. if (Suffix.empty())
  6034. MArch = "";
  6035. else
  6036. MArch = std::string("arm") + Suffix.str();
  6037. }
  6038. }
  6039. return MArch;
  6040. }
  6041. /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
  6042. StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
  6043. std::string MArch = getARMArch(Arch, Triple);
  6044. // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
  6045. // here means an -march=native that we can't handle, so instead return no CPU.
  6046. if (MArch.empty())
  6047. return StringRef();
  6048. // We need to return an empty string here on invalid MArch values as the
  6049. // various places that call this function can't cope with a null result.
  6050. return Triple.getARMCPUForArch(MArch);
  6051. }
  6052. /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
  6053. std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
  6054. const llvm::Triple &Triple) {
  6055. // FIXME: Warn on inconsistent use of -mcpu and -march.
  6056. // If we have -mcpu=, use that.
  6057. if (!CPU.empty()) {
  6058. std::string MCPU = StringRef(CPU).split("+").first.lower();
  6059. // Handle -mcpu=native.
  6060. if (MCPU == "native")
  6061. return llvm::sys::getHostCPUName();
  6062. else
  6063. return MCPU;
  6064. }
  6065. return getARMCPUForMArch(Arch, Triple);
  6066. }
  6067. /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
  6068. /// CPU (or Arch, if CPU is generic).
  6069. // FIXME: This is redundant with -mcpu, why does LLVM use this.
  6070. StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
  6071. const llvm::Triple &Triple) {
  6072. unsigned ArchKind;
  6073. if (CPU == "generic") {
  6074. std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
  6075. ArchKind = llvm::ARM::parseArch(ARMArch);
  6076. if (ArchKind == llvm::ARM::AK_INVALID)
  6077. // In case of generic Arch, i.e. "arm",
  6078. // extract arch from default cpu of the Triple
  6079. ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
  6080. } else {
  6081. // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
  6082. // armv7k triple if it's actually been specified via "-arch armv7k".
  6083. ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
  6084. ? (unsigned)llvm::ARM::AK_ARMV7K
  6085. : llvm::ARM::parseCPUArch(CPU);
  6086. }
  6087. if (ArchKind == llvm::ARM::AK_INVALID)
  6088. return "";
  6089. return llvm::ARM::getSubArch(ArchKind);
  6090. }
  6091. void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
  6092. const llvm::Triple &Triple) {
  6093. if (Args.hasArg(options::OPT_r))
  6094. return;
  6095. // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
  6096. // to generate BE-8 executables.
  6097. if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
  6098. CmdArgs.push_back("--be8");
  6099. }
  6100. mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
  6101. // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
  6102. // was first introduced in Release 3. However, other compilers have
  6103. // traditionally allowed it for Release 2 so we should do the same.
  6104. return (NanEncoding)llvm::StringSwitch<int>(CPU)
  6105. .Case("mips1", NanLegacy)
  6106. .Case("mips2", NanLegacy)
  6107. .Case("mips3", NanLegacy)
  6108. .Case("mips4", NanLegacy)
  6109. .Case("mips5", NanLegacy)
  6110. .Case("mips32", NanLegacy)
  6111. .Case("mips32r2", NanLegacy | Nan2008)
  6112. .Case("mips32r3", NanLegacy | Nan2008)
  6113. .Case("mips32r5", NanLegacy | Nan2008)
  6114. .Case("mips32r6", Nan2008)
  6115. .Case("mips64", NanLegacy)
  6116. .Case("mips64r2", NanLegacy | Nan2008)
  6117. .Case("mips64r3", NanLegacy | Nan2008)
  6118. .Case("mips64r5", NanLegacy | Nan2008)
  6119. .Case("mips64r6", Nan2008)
  6120. .Default(NanLegacy);
  6121. }
  6122. bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
  6123. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  6124. return A && (A->getValue() == StringRef(Value));
  6125. }
  6126. bool mips::isUCLibc(const ArgList &Args) {
  6127. Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
  6128. return A && A->getOption().matches(options::OPT_muclibc);
  6129. }
  6130. bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
  6131. if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
  6132. return llvm::StringSwitch<bool>(NaNArg->getValue())
  6133. .Case("2008", true)
  6134. .Case("legacy", false)
  6135. .Default(false);
  6136. // NaN2008 is the default for MIPS32r6/MIPS64r6.
  6137. return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
  6138. .Cases("mips32r6", "mips64r6", true)
  6139. .Default(false);
  6140. return false;
  6141. }
  6142. bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
  6143. StringRef ABIName, mips::FloatABI FloatABI) {
  6144. if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
  6145. Triple.getVendor() != llvm::Triple::MipsTechnologies)
  6146. return false;
  6147. if (ABIName != "32")
  6148. return false;
  6149. // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
  6150. // present.
  6151. if (FloatABI == mips::FloatABI::Soft)
  6152. return false;
  6153. return llvm::StringSwitch<bool>(CPUName)
  6154. .Cases("mips2", "mips3", "mips4", "mips5", true)
  6155. .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
  6156. .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
  6157. .Default(false);
  6158. }
  6159. bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
  6160. StringRef CPUName, StringRef ABIName,
  6161. mips::FloatABI FloatABI) {
  6162. bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
  6163. // FPXX shouldn't be used if -msingle-float is present.
  6164. if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
  6165. options::OPT_mdouble_float))
  6166. if (A->getOption().matches(options::OPT_msingle_float))
  6167. UseFPXX = false;
  6168. return UseFPXX;
  6169. }
  6170. llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
  6171. // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
  6172. // archs which Darwin doesn't use.
  6173. // The matching this routine does is fairly pointless, since it is neither the
  6174. // complete architecture list, nor a reasonable subset. The problem is that
  6175. // historically the driver driver accepts this and also ties its -march=
  6176. // handling to the architecture name, so we need to be careful before removing
  6177. // support for it.
  6178. // This code must be kept in sync with Clang's Darwin specific argument
  6179. // translation.
  6180. return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
  6181. .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
  6182. .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
  6183. .Case("ppc64", llvm::Triple::ppc64)
  6184. .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
  6185. .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
  6186. llvm::Triple::x86)
  6187. .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
  6188. // This is derived from the driver driver.
  6189. .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
  6190. .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
  6191. .Cases("armv7s", "xscale", llvm::Triple::arm)
  6192. .Case("arm64", llvm::Triple::aarch64)
  6193. .Case("r600", llvm::Triple::r600)
  6194. .Case("amdgcn", llvm::Triple::amdgcn)
  6195. .Case("nvptx", llvm::Triple::nvptx)
  6196. .Case("nvptx64", llvm::Triple::nvptx64)
  6197. .Case("amdil", llvm::Triple::amdil)
  6198. .Case("spir", llvm::Triple::spir)
  6199. .Default(llvm::Triple::UnknownArch);
  6200. }
  6201. void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
  6202. const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
  6203. T.setArch(Arch);
  6204. if (Str == "x86_64h")
  6205. T.setArchName(Str);
  6206. else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
  6207. T.setOS(llvm::Triple::UnknownOS);
  6208. T.setObjectFormat(llvm::Triple::MachO);
  6209. }
  6210. }
  6211. const char *Clang::getBaseInputName(const ArgList &Args,
  6212. const InputInfo &Input) {
  6213. return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
  6214. }
  6215. const char *Clang::getBaseInputStem(const ArgList &Args,
  6216. const InputInfoList &Inputs) {
  6217. const char *Str = getBaseInputName(Args, Inputs[0]);
  6218. if (const char *End = strrchr(Str, '.'))
  6219. return Args.MakeArgString(std::string(Str, End));
  6220. return Str;
  6221. }
  6222. const char *Clang::getDependencyFileName(const ArgList &Args,
  6223. const InputInfoList &Inputs) {
  6224. // FIXME: Think about this more.
  6225. std::string Res;
  6226. if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
  6227. std::string Str(OutputOpt->getValue());
  6228. Res = Str.substr(0, Str.rfind('.'));
  6229. } else {
  6230. Res = getBaseInputStem(Args, Inputs);
  6231. }
  6232. return Args.MakeArgString(Res + ".d");
  6233. }
  6234. void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6235. const InputInfo &Output,
  6236. const InputInfoList &Inputs,
  6237. const ArgList &Args,
  6238. const char *LinkingOutput) const {
  6239. const ToolChain &ToolChain = getToolChain();
  6240. const Driver &D = ToolChain.getDriver();
  6241. ArgStringList CmdArgs;
  6242. // Silence warning for "clang -g foo.o -o foo"
  6243. Args.ClaimAllArgs(options::OPT_g_Group);
  6244. // and "clang -emit-llvm foo.o -o foo"
  6245. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6246. // and for "clang -w foo.o -o foo". Other warning options are already
  6247. // handled somewhere else.
  6248. Args.ClaimAllArgs(options::OPT_w);
  6249. if (!D.SysRoot.empty())
  6250. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  6251. // CloudABI only supports static linkage.
  6252. CmdArgs.push_back("-Bstatic");
  6253. // CloudABI uses Position Independent Executables exclusively.
  6254. CmdArgs.push_back("-pie");
  6255. CmdArgs.push_back("--no-dynamic-linker");
  6256. CmdArgs.push_back("-zrelro");
  6257. CmdArgs.push_back("--eh-frame-hdr");
  6258. CmdArgs.push_back("--gc-sections");
  6259. if (Output.isFilename()) {
  6260. CmdArgs.push_back("-o");
  6261. CmdArgs.push_back(Output.getFilename());
  6262. } else {
  6263. assert(Output.isNothing() && "Invalid output.");
  6264. }
  6265. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6266. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
  6267. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
  6268. }
  6269. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6270. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  6271. Args.AddAllArgs(CmdArgs,
  6272. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  6273. options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
  6274. if (D.isUsingLTO())
  6275. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  6276. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  6277. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6278. if (D.CCCIsCXX())
  6279. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  6280. CmdArgs.push_back("-lc");
  6281. CmdArgs.push_back("-lcompiler_rt");
  6282. }
  6283. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6284. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  6285. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  6286. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6287. }
  6288. void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6289. const InputInfo &Output,
  6290. const InputInfoList &Inputs,
  6291. const ArgList &Args,
  6292. const char *LinkingOutput) const {
  6293. ArgStringList CmdArgs;
  6294. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  6295. const InputInfo &Input = Inputs[0];
  6296. // Determine the original source input.
  6297. const Action *SourceAction = &JA;
  6298. while (SourceAction->getKind() != Action::InputClass) {
  6299. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  6300. SourceAction = SourceAction->getInputs()[0];
  6301. }
  6302. // If -fno-integrated-as is used add -Q to the darwin assember driver to make
  6303. // sure it runs its system assembler not clang's integrated assembler.
  6304. // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
  6305. // FIXME: at run-time detect assembler capabilities or rely on version
  6306. // information forwarded by -target-assembler-version.
  6307. if (Args.hasArg(options::OPT_fno_integrated_as)) {
  6308. const llvm::Triple &T(getToolChain().getTriple());
  6309. if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
  6310. CmdArgs.push_back("-Q");
  6311. }
  6312. // Forward -g, assuming we are dealing with an actual assembly file.
  6313. if (SourceAction->getType() == types::TY_Asm ||
  6314. SourceAction->getType() == types::TY_PP_Asm) {
  6315. if (Args.hasArg(options::OPT_gstabs))
  6316. CmdArgs.push_back("--gstabs");
  6317. else if (Args.hasArg(options::OPT_g_Group))
  6318. CmdArgs.push_back("-g");
  6319. }
  6320. // Derived from asm spec.
  6321. AddMachOArch(Args, CmdArgs);
  6322. // Use -force_cpusubtype_ALL on x86 by default.
  6323. if (getToolChain().getArch() == llvm::Triple::x86 ||
  6324. getToolChain().getArch() == llvm::Triple::x86_64 ||
  6325. Args.hasArg(options::OPT_force__cpusubtype__ALL))
  6326. CmdArgs.push_back("-force_cpusubtype_ALL");
  6327. if (getToolChain().getArch() != llvm::Triple::x86_64 &&
  6328. (((Args.hasArg(options::OPT_mkernel) ||
  6329. Args.hasArg(options::OPT_fapple_kext)) &&
  6330. getMachOToolChain().isKernelStatic()) ||
  6331. Args.hasArg(options::OPT_static)))
  6332. CmdArgs.push_back("-static");
  6333. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6334. assert(Output.isFilename() && "Unexpected lipo output.");
  6335. CmdArgs.push_back("-o");
  6336. CmdArgs.push_back(Output.getFilename());
  6337. assert(Input.isFilename() && "Invalid input.");
  6338. CmdArgs.push_back(Input.getFilename());
  6339. // asm_final spec is empty.
  6340. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6341. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6342. }
  6343. void darwin::MachOTool::anchor() {}
  6344. void darwin::MachOTool::AddMachOArch(const ArgList &Args,
  6345. ArgStringList &CmdArgs) const {
  6346. StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
  6347. // Derived from darwin_arch spec.
  6348. CmdArgs.push_back("-arch");
  6349. CmdArgs.push_back(Args.MakeArgString(ArchName));
  6350. // FIXME: Is this needed anymore?
  6351. if (ArchName == "arm")
  6352. CmdArgs.push_back("-force_cpusubtype_ALL");
  6353. }
  6354. bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
  6355. // We only need to generate a temp path for LTO if we aren't compiling object
  6356. // files. When compiling source files, we run 'dsymutil' after linking. We
  6357. // don't run 'dsymutil' when compiling object files.
  6358. for (const auto &Input : Inputs)
  6359. if (Input.getType() != types::TY_Object)
  6360. return true;
  6361. return false;
  6362. }
  6363. void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
  6364. ArgStringList &CmdArgs,
  6365. const InputInfoList &Inputs) const {
  6366. const Driver &D = getToolChain().getDriver();
  6367. const toolchains::MachO &MachOTC = getMachOToolChain();
  6368. unsigned Version[5] = {0, 0, 0, 0, 0};
  6369. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  6370. if (!Driver::GetReleaseVersion(A->getValue(), Version))
  6371. D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
  6372. }
  6373. // Newer linkers support -demangle. Pass it if supported and not disabled by
  6374. // the user.
  6375. if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  6376. CmdArgs.push_back("-demangle");
  6377. if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
  6378. CmdArgs.push_back("-export_dynamic");
  6379. // If we are using App Extension restrictions, pass a flag to the linker
  6380. // telling it that the compiled code has been audited.
  6381. if (Args.hasFlag(options::OPT_fapplication_extension,
  6382. options::OPT_fno_application_extension, false))
  6383. CmdArgs.push_back("-application_extension");
  6384. if (D.isUsingLTO()) {
  6385. // If we are using LTO, then automatically create a temporary file path for
  6386. // the linker to use, so that it's lifetime will extend past a possible
  6387. // dsymutil step.
  6388. if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
  6389. const char *TmpPath = C.getArgs().MakeArgString(
  6390. D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
  6391. C.addTempFile(TmpPath);
  6392. CmdArgs.push_back("-object_path_lto");
  6393. CmdArgs.push_back(TmpPath);
  6394. }
  6395. // Use -lto_library option to specify the libLTO.dylib path. Try to find
  6396. // it in clang installed libraries. If not found, the option is not used
  6397. // and 'ld' will use its default mechanism to search for libLTO.dylib.
  6398. if (Version[0] >= 133) {
  6399. // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
  6400. StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
  6401. SmallString<128> LibLTOPath(P);
  6402. llvm::sys::path::append(LibLTOPath, "lib");
  6403. llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
  6404. if (llvm::sys::fs::exists(LibLTOPath)) {
  6405. CmdArgs.push_back("-lto_library");
  6406. CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
  6407. } else {
  6408. D.Diag(diag::warn_drv_lto_libpath);
  6409. }
  6410. }
  6411. }
  6412. // Derived from the "link" spec.
  6413. Args.AddAllArgs(CmdArgs, options::OPT_static);
  6414. if (!Args.hasArg(options::OPT_static))
  6415. CmdArgs.push_back("-dynamic");
  6416. if (Args.hasArg(options::OPT_fgnu_runtime)) {
  6417. // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
  6418. // here. How do we wish to handle such things?
  6419. }
  6420. if (!Args.hasArg(options::OPT_dynamiclib)) {
  6421. AddMachOArch(Args, CmdArgs);
  6422. // FIXME: Why do this only on this path?
  6423. Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
  6424. Args.AddLastArg(CmdArgs, options::OPT_bundle);
  6425. Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
  6426. Args.AddAllArgs(CmdArgs, options::OPT_client__name);
  6427. Arg *A;
  6428. if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
  6429. (A = Args.getLastArg(options::OPT_current__version)) ||
  6430. (A = Args.getLastArg(options::OPT_install__name)))
  6431. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  6432. << "-dynamiclib";
  6433. Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
  6434. Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
  6435. Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
  6436. } else {
  6437. CmdArgs.push_back("-dylib");
  6438. Arg *A;
  6439. if ((A = Args.getLastArg(options::OPT_bundle)) ||
  6440. (A = Args.getLastArg(options::OPT_bundle__loader)) ||
  6441. (A = Args.getLastArg(options::OPT_client__name)) ||
  6442. (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
  6443. (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
  6444. (A = Args.getLastArg(options::OPT_private__bundle)))
  6445. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  6446. << "-dynamiclib";
  6447. Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
  6448. "-dylib_compatibility_version");
  6449. Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
  6450. "-dylib_current_version");
  6451. AddMachOArch(Args, CmdArgs);
  6452. Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
  6453. "-dylib_install_name");
  6454. }
  6455. Args.AddLastArg(CmdArgs, options::OPT_all__load);
  6456. Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
  6457. Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
  6458. if (MachOTC.isTargetIOSBased())
  6459. Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
  6460. Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
  6461. Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
  6462. Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
  6463. Args.AddLastArg(CmdArgs, options::OPT_dynamic);
  6464. Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
  6465. Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
  6466. Args.AddAllArgs(CmdArgs, options::OPT_force__load);
  6467. Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
  6468. Args.AddAllArgs(CmdArgs, options::OPT_image__base);
  6469. Args.AddAllArgs(CmdArgs, options::OPT_init);
  6470. // Add the deployment target.
  6471. MachOTC.addMinVersionArgs(Args, CmdArgs);
  6472. Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
  6473. Args.AddLastArg(CmdArgs, options::OPT_multi__module);
  6474. Args.AddLastArg(CmdArgs, options::OPT_single__module);
  6475. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
  6476. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
  6477. if (const Arg *A =
  6478. Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
  6479. options::OPT_fno_pie, options::OPT_fno_PIE)) {
  6480. if (A->getOption().matches(options::OPT_fpie) ||
  6481. A->getOption().matches(options::OPT_fPIE))
  6482. CmdArgs.push_back("-pie");
  6483. else
  6484. CmdArgs.push_back("-no_pie");
  6485. }
  6486. // for embed-bitcode, use -bitcode_bundle in linker command
  6487. if (C.getDriver().embedBitcodeEnabled() ||
  6488. C.getDriver().embedBitcodeMarkerOnly()) {
  6489. // Check if the toolchain supports bitcode build flow.
  6490. if (MachOTC.SupportsEmbeddedBitcode())
  6491. CmdArgs.push_back("-bitcode_bundle");
  6492. else
  6493. D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
  6494. }
  6495. Args.AddLastArg(CmdArgs, options::OPT_prebind);
  6496. Args.AddLastArg(CmdArgs, options::OPT_noprebind);
  6497. Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
  6498. Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
  6499. Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
  6500. Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
  6501. Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
  6502. Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
  6503. Args.AddAllArgs(CmdArgs, options::OPT_segprot);
  6504. Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
  6505. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
  6506. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
  6507. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
  6508. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
  6509. Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
  6510. Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
  6511. // Give --sysroot= preference, over the Apple specific behavior to also use
  6512. // --isysroot as the syslibroot.
  6513. StringRef sysroot = C.getSysRoot();
  6514. if (sysroot != "") {
  6515. CmdArgs.push_back("-syslibroot");
  6516. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  6517. } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  6518. CmdArgs.push_back("-syslibroot");
  6519. CmdArgs.push_back(A->getValue());
  6520. }
  6521. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
  6522. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
  6523. Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
  6524. Args.AddAllArgs(CmdArgs, options::OPT_undefined);
  6525. Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
  6526. Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
  6527. Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
  6528. Args.AddAllArgs(CmdArgs, options::OPT_y);
  6529. Args.AddLastArg(CmdArgs, options::OPT_w);
  6530. Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
  6531. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
  6532. Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
  6533. Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
  6534. Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
  6535. Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
  6536. Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
  6537. Args.AddLastArg(CmdArgs, options::OPT_whyload);
  6538. Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
  6539. Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
  6540. Args.AddLastArg(CmdArgs, options::OPT_dylinker);
  6541. Args.AddLastArg(CmdArgs, options::OPT_Mach);
  6542. }
  6543. void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6544. const InputInfo &Output,
  6545. const InputInfoList &Inputs,
  6546. const ArgList &Args,
  6547. const char *LinkingOutput) const {
  6548. assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
  6549. // If the number of arguments surpasses the system limits, we will encode the
  6550. // input files in a separate file, shortening the command line. To this end,
  6551. // build a list of input file names that can be passed via a file with the
  6552. // -filelist linker option.
  6553. llvm::opt::ArgStringList InputFileList;
  6554. // The logic here is derived from gcc's behavior; most of which
  6555. // comes from specs (starting with link_command). Consult gcc for
  6556. // more information.
  6557. ArgStringList CmdArgs;
  6558. /// Hack(tm) to ignore linking errors when we are doing ARC migration.
  6559. if (Args.hasArg(options::OPT_ccc_arcmt_check,
  6560. options::OPT_ccc_arcmt_migrate)) {
  6561. for (const auto &Arg : Args)
  6562. Arg->claim();
  6563. const char *Exec =
  6564. Args.MakeArgString(getToolChain().GetProgramPath("touch"));
  6565. CmdArgs.push_back(Output.getFilename());
  6566. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
  6567. return;
  6568. }
  6569. // I'm not sure why this particular decomposition exists in gcc, but
  6570. // we follow suite for ease of comparison.
  6571. AddLinkArgs(C, Args, CmdArgs, Inputs);
  6572. // It seems that the 'e' option is completely ignored for dynamic executables
  6573. // (the default), and with static executables, the last one wins, as expected.
  6574. Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
  6575. options::OPT_Z_Flag, options::OPT_u_Group,
  6576. options::OPT_e, options::OPT_r});
  6577. // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
  6578. // members of static archive libraries which implement Objective-C classes or
  6579. // categories.
  6580. if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
  6581. CmdArgs.push_back("-ObjC");
  6582. CmdArgs.push_back("-o");
  6583. CmdArgs.push_back(Output.getFilename());
  6584. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6585. getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
  6586. // SafeStack requires its own runtime libraries
  6587. // These libraries should be linked first, to make sure the
  6588. // __safestack_init constructor executes before everything else
  6589. if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
  6590. getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
  6591. "libclang_rt.safestack_osx.a",
  6592. /*AlwaysLink=*/true);
  6593. }
  6594. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6595. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6596. // Build the input file for -filelist (list of linker input files) in case we
  6597. // need it later
  6598. for (const auto &II : Inputs) {
  6599. if (!II.isFilename()) {
  6600. // This is a linker input argument.
  6601. // We cannot mix input arguments and file names in a -filelist input, thus
  6602. // we prematurely stop our list (remaining files shall be passed as
  6603. // arguments).
  6604. if (InputFileList.size() > 0)
  6605. break;
  6606. continue;
  6607. }
  6608. InputFileList.push_back(II.getFilename());
  6609. }
  6610. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
  6611. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  6612. if (isObjCRuntimeLinked(Args) &&
  6613. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6614. // We use arclite library for both ARC and subscripting support.
  6615. getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
  6616. CmdArgs.push_back("-framework");
  6617. CmdArgs.push_back("Foundation");
  6618. // Link libobj.
  6619. CmdArgs.push_back("-lobjc");
  6620. }
  6621. if (LinkingOutput) {
  6622. CmdArgs.push_back("-arch_multiple");
  6623. CmdArgs.push_back("-final_output");
  6624. CmdArgs.push_back(LinkingOutput);
  6625. }
  6626. if (Args.hasArg(options::OPT_fnested_functions))
  6627. CmdArgs.push_back("-allow_stack_execute");
  6628. getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
  6629. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6630. if (getToolChain().getDriver().CCCIsCXX())
  6631. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6632. // link_ssp spec is empty.
  6633. // Let the tool chain choose which runtime library to link.
  6634. getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
  6635. }
  6636. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6637. // endfile_spec is empty.
  6638. }
  6639. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  6640. Args.AddAllArgs(CmdArgs, options::OPT_F);
  6641. // -iframework should be forwarded as -F.
  6642. for (const Arg *A : Args.filtered(options::OPT_iframework))
  6643. CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
  6644. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6645. if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
  6646. if (A->getValue() == StringRef("Accelerate")) {
  6647. CmdArgs.push_back("-framework");
  6648. CmdArgs.push_back("Accelerate");
  6649. }
  6650. }
  6651. }
  6652. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6653. std::unique_ptr<Command> Cmd =
  6654. llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
  6655. Cmd->setInputFileList(std::move(InputFileList));
  6656. C.addCommand(std::move(Cmd));
  6657. }
  6658. void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
  6659. const InputInfo &Output,
  6660. const InputInfoList &Inputs,
  6661. const ArgList &Args,
  6662. const char *LinkingOutput) const {
  6663. ArgStringList CmdArgs;
  6664. CmdArgs.push_back("-create");
  6665. assert(Output.isFilename() && "Unexpected lipo output.");
  6666. CmdArgs.push_back("-output");
  6667. CmdArgs.push_back(Output.getFilename());
  6668. for (const auto &II : Inputs) {
  6669. assert(II.isFilename() && "Unexpected lipo input.");
  6670. CmdArgs.push_back(II.getFilename());
  6671. }
  6672. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
  6673. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6674. }
  6675. void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
  6676. const InputInfo &Output,
  6677. const InputInfoList &Inputs,
  6678. const ArgList &Args,
  6679. const char *LinkingOutput) const {
  6680. ArgStringList CmdArgs;
  6681. CmdArgs.push_back("-o");
  6682. CmdArgs.push_back(Output.getFilename());
  6683. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6684. const InputInfo &Input = Inputs[0];
  6685. assert(Input.isFilename() && "Unexpected dsymutil input.");
  6686. CmdArgs.push_back(Input.getFilename());
  6687. const char *Exec =
  6688. Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
  6689. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6690. }
  6691. void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
  6692. const InputInfo &Output,
  6693. const InputInfoList &Inputs,
  6694. const ArgList &Args,
  6695. const char *LinkingOutput) const {
  6696. ArgStringList CmdArgs;
  6697. CmdArgs.push_back("--verify");
  6698. CmdArgs.push_back("--debug-info");
  6699. CmdArgs.push_back("--eh-frame");
  6700. CmdArgs.push_back("--quiet");
  6701. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6702. const InputInfo &Input = Inputs[0];
  6703. assert(Input.isFilename() && "Unexpected verify input");
  6704. // Grabbing the output of the earlier dsymutil run.
  6705. CmdArgs.push_back(Input.getFilename());
  6706. const char *Exec =
  6707. Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
  6708. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6709. }
  6710. void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6711. const InputInfo &Output,
  6712. const InputInfoList &Inputs,
  6713. const ArgList &Args,
  6714. const char *LinkingOutput) const {
  6715. claimNoWarnArgs(Args);
  6716. ArgStringList CmdArgs;
  6717. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6718. CmdArgs.push_back("-o");
  6719. CmdArgs.push_back(Output.getFilename());
  6720. for (const auto &II : Inputs)
  6721. CmdArgs.push_back(II.getFilename());
  6722. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6723. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6724. }
  6725. void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6726. const InputInfo &Output,
  6727. const InputInfoList &Inputs,
  6728. const ArgList &Args,
  6729. const char *LinkingOutput) const {
  6730. ArgStringList CmdArgs;
  6731. // Demangle C++ names in errors
  6732. CmdArgs.push_back("-C");
  6733. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6734. CmdArgs.push_back("-e");
  6735. CmdArgs.push_back("_start");
  6736. }
  6737. if (Args.hasArg(options::OPT_static)) {
  6738. CmdArgs.push_back("-Bstatic");
  6739. CmdArgs.push_back("-dn");
  6740. } else {
  6741. CmdArgs.push_back("-Bdynamic");
  6742. if (Args.hasArg(options::OPT_shared)) {
  6743. CmdArgs.push_back("-shared");
  6744. } else {
  6745. CmdArgs.push_back("--dynamic-linker");
  6746. CmdArgs.push_back(
  6747. Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
  6748. }
  6749. }
  6750. if (Output.isFilename()) {
  6751. CmdArgs.push_back("-o");
  6752. CmdArgs.push_back(Output.getFilename());
  6753. } else {
  6754. assert(Output.isNothing() && "Invalid output.");
  6755. }
  6756. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6757. if (!Args.hasArg(options::OPT_shared))
  6758. CmdArgs.push_back(
  6759. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  6760. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  6761. CmdArgs.push_back(
  6762. Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
  6763. CmdArgs.push_back(
  6764. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6765. }
  6766. getToolChain().AddFilePathLibArgs(Args, CmdArgs);
  6767. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  6768. options::OPT_e, options::OPT_r});
  6769. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6770. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6771. if (getToolChain().getDriver().CCCIsCXX())
  6772. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6773. CmdArgs.push_back("-lgcc_s");
  6774. CmdArgs.push_back("-lc");
  6775. if (!Args.hasArg(options::OPT_shared)) {
  6776. CmdArgs.push_back("-lgcc");
  6777. CmdArgs.push_back("-lm");
  6778. }
  6779. }
  6780. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6781. CmdArgs.push_back(
  6782. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6783. }
  6784. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  6785. getToolChain().addProfileRTLibs(Args, CmdArgs);
  6786. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6787. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6788. }
  6789. void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6790. const InputInfo &Output,
  6791. const InputInfoList &Inputs,
  6792. const ArgList &Args,
  6793. const char *LinkingOutput) const {
  6794. claimNoWarnArgs(Args);
  6795. ArgStringList CmdArgs;
  6796. switch (getToolChain().getArch()) {
  6797. case llvm::Triple::x86:
  6798. // When building 32-bit code on OpenBSD/amd64, we have to explicitly
  6799. // instruct as in the base system to assemble 32-bit code.
  6800. CmdArgs.push_back("--32");
  6801. break;
  6802. case llvm::Triple::ppc:
  6803. CmdArgs.push_back("-mppc");
  6804. CmdArgs.push_back("-many");
  6805. break;
  6806. case llvm::Triple::sparc:
  6807. case llvm::Triple::sparcel: {
  6808. CmdArgs.push_back("-32");
  6809. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6810. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6811. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6812. break;
  6813. }
  6814. case llvm::Triple::sparcv9: {
  6815. CmdArgs.push_back("-64");
  6816. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6817. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6818. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6819. break;
  6820. }
  6821. case llvm::Triple::mips64:
  6822. case llvm::Triple::mips64el: {
  6823. StringRef CPUName;
  6824. StringRef ABIName;
  6825. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6826. CmdArgs.push_back("-mabi");
  6827. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6828. if (getToolChain().getArch() == llvm::Triple::mips64)
  6829. CmdArgs.push_back("-EB");
  6830. else
  6831. CmdArgs.push_back("-EL");
  6832. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6833. break;
  6834. }
  6835. default:
  6836. break;
  6837. }
  6838. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6839. CmdArgs.push_back("-o");
  6840. CmdArgs.push_back(Output.getFilename());
  6841. for (const auto &II : Inputs)
  6842. CmdArgs.push_back(II.getFilename());
  6843. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6844. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6845. }
  6846. void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6847. const InputInfo &Output,
  6848. const InputInfoList &Inputs,
  6849. const ArgList &Args,
  6850. const char *LinkingOutput) const {
  6851. const Driver &D = getToolChain().getDriver();
  6852. ArgStringList CmdArgs;
  6853. // Silence warning for "clang -g foo.o -o foo"
  6854. Args.ClaimAllArgs(options::OPT_g_Group);
  6855. // and "clang -emit-llvm foo.o -o foo"
  6856. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6857. // and for "clang -w foo.o -o foo". Other warning options are already
  6858. // handled somewhere else.
  6859. Args.ClaimAllArgs(options::OPT_w);
  6860. if (getToolChain().getArch() == llvm::Triple::mips64)
  6861. CmdArgs.push_back("-EB");
  6862. else if (getToolChain().getArch() == llvm::Triple::mips64el)
  6863. CmdArgs.push_back("-EL");
  6864. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6865. CmdArgs.push_back("-e");
  6866. CmdArgs.push_back("__start");
  6867. }
  6868. if (Args.hasArg(options::OPT_static)) {
  6869. CmdArgs.push_back("-Bstatic");
  6870. } else {
  6871. if (Args.hasArg(options::OPT_rdynamic))
  6872. CmdArgs.push_back("-export-dynamic");
  6873. CmdArgs.push_back("--eh-frame-hdr");
  6874. CmdArgs.push_back("-Bdynamic");
  6875. if (Args.hasArg(options::OPT_shared)) {
  6876. CmdArgs.push_back("-shared");
  6877. } else {
  6878. CmdArgs.push_back("-dynamic-linker");
  6879. CmdArgs.push_back("/usr/libexec/ld.so");
  6880. }
  6881. }
  6882. if (Args.hasArg(options::OPT_nopie))
  6883. CmdArgs.push_back("-nopie");
  6884. if (Output.isFilename()) {
  6885. CmdArgs.push_back("-o");
  6886. CmdArgs.push_back(Output.getFilename());
  6887. } else {
  6888. assert(Output.isNothing() && "Invalid output.");
  6889. }
  6890. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6891. if (!Args.hasArg(options::OPT_shared)) {
  6892. if (Args.hasArg(options::OPT_pg))
  6893. CmdArgs.push_back(
  6894. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  6895. else
  6896. CmdArgs.push_back(
  6897. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  6898. CmdArgs.push_back(
  6899. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6900. } else {
  6901. CmdArgs.push_back(
  6902. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  6903. }
  6904. }
  6905. std::string Triple = getToolChain().getTripleString();
  6906. if (Triple.substr(0, 6) == "x86_64")
  6907. Triple.replace(0, 6, "amd64");
  6908. CmdArgs.push_back(
  6909. Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
  6910. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  6911. options::OPT_e, options::OPT_s, options::OPT_t,
  6912. options::OPT_Z_Flag, options::OPT_r});
  6913. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6914. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6915. if (D.CCCIsCXX()) {
  6916. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6917. if (Args.hasArg(options::OPT_pg))
  6918. CmdArgs.push_back("-lm_p");
  6919. else
  6920. CmdArgs.push_back("-lm");
  6921. }
  6922. // FIXME: For some reason GCC passes -lgcc before adding
  6923. // the default system libraries. Just mimic this for now.
  6924. CmdArgs.push_back("-lgcc");
  6925. if (Args.hasArg(options::OPT_pthread)) {
  6926. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  6927. CmdArgs.push_back("-lpthread_p");
  6928. else
  6929. CmdArgs.push_back("-lpthread");
  6930. }
  6931. if (!Args.hasArg(options::OPT_shared)) {
  6932. if (Args.hasArg(options::OPT_pg))
  6933. CmdArgs.push_back("-lc_p");
  6934. else
  6935. CmdArgs.push_back("-lc");
  6936. }
  6937. CmdArgs.push_back("-lgcc");
  6938. }
  6939. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6940. if (!Args.hasArg(options::OPT_shared))
  6941. CmdArgs.push_back(
  6942. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6943. else
  6944. CmdArgs.push_back(
  6945. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  6946. }
  6947. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6948. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6949. }
  6950. void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6951. const InputInfo &Output,
  6952. const InputInfoList &Inputs,
  6953. const ArgList &Args,
  6954. const char *LinkingOutput) const {
  6955. claimNoWarnArgs(Args);
  6956. ArgStringList CmdArgs;
  6957. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6958. CmdArgs.push_back("-o");
  6959. CmdArgs.push_back(Output.getFilename());
  6960. for (const auto &II : Inputs)
  6961. CmdArgs.push_back(II.getFilename());
  6962. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6963. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6964. }
  6965. void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6966. const InputInfo &Output,
  6967. const InputInfoList &Inputs,
  6968. const ArgList &Args,
  6969. const char *LinkingOutput) const {
  6970. const Driver &D = getToolChain().getDriver();
  6971. ArgStringList CmdArgs;
  6972. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6973. CmdArgs.push_back("-e");
  6974. CmdArgs.push_back("__start");
  6975. }
  6976. if (Args.hasArg(options::OPT_static)) {
  6977. CmdArgs.push_back("-Bstatic");
  6978. } else {
  6979. if (Args.hasArg(options::OPT_rdynamic))
  6980. CmdArgs.push_back("-export-dynamic");
  6981. CmdArgs.push_back("--eh-frame-hdr");
  6982. CmdArgs.push_back("-Bdynamic");
  6983. if (Args.hasArg(options::OPT_shared)) {
  6984. CmdArgs.push_back("-shared");
  6985. } else {
  6986. CmdArgs.push_back("-dynamic-linker");
  6987. CmdArgs.push_back("/usr/libexec/ld.so");
  6988. }
  6989. }
  6990. if (Output.isFilename()) {
  6991. CmdArgs.push_back("-o");
  6992. CmdArgs.push_back(Output.getFilename());
  6993. } else {
  6994. assert(Output.isNothing() && "Invalid output.");
  6995. }
  6996. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6997. if (!Args.hasArg(options::OPT_shared)) {
  6998. if (Args.hasArg(options::OPT_pg))
  6999. CmdArgs.push_back(
  7000. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  7001. else
  7002. CmdArgs.push_back(
  7003. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  7004. CmdArgs.push_back(
  7005. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7006. } else {
  7007. CmdArgs.push_back(
  7008. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7009. }
  7010. }
  7011. Args.AddAllArgs(CmdArgs,
  7012. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  7013. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7014. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7015. if (D.CCCIsCXX()) {
  7016. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7017. if (Args.hasArg(options::OPT_pg))
  7018. CmdArgs.push_back("-lm_p");
  7019. else
  7020. CmdArgs.push_back("-lm");
  7021. }
  7022. if (Args.hasArg(options::OPT_pthread)) {
  7023. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  7024. CmdArgs.push_back("-lpthread_p");
  7025. else
  7026. CmdArgs.push_back("-lpthread");
  7027. }
  7028. if (!Args.hasArg(options::OPT_shared)) {
  7029. if (Args.hasArg(options::OPT_pg))
  7030. CmdArgs.push_back("-lc_p");
  7031. else
  7032. CmdArgs.push_back("-lc");
  7033. }
  7034. StringRef MyArch;
  7035. switch (getToolChain().getArch()) {
  7036. case llvm::Triple::arm:
  7037. MyArch = "arm";
  7038. break;
  7039. case llvm::Triple::x86:
  7040. MyArch = "i386";
  7041. break;
  7042. case llvm::Triple::x86_64:
  7043. MyArch = "amd64";
  7044. break;
  7045. default:
  7046. llvm_unreachable("Unsupported architecture");
  7047. }
  7048. CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
  7049. }
  7050. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7051. if (!Args.hasArg(options::OPT_shared))
  7052. CmdArgs.push_back(
  7053. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7054. else
  7055. CmdArgs.push_back(
  7056. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7057. }
  7058. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7059. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7060. }
  7061. void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7062. const InputInfo &Output,
  7063. const InputInfoList &Inputs,
  7064. const ArgList &Args,
  7065. const char *LinkingOutput) const {
  7066. claimNoWarnArgs(Args);
  7067. ArgStringList CmdArgs;
  7068. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  7069. // instruct as in the base system to assemble 32-bit code.
  7070. switch (getToolChain().getArch()) {
  7071. default:
  7072. break;
  7073. case llvm::Triple::x86:
  7074. CmdArgs.push_back("--32");
  7075. break;
  7076. case llvm::Triple::ppc:
  7077. CmdArgs.push_back("-a32");
  7078. break;
  7079. case llvm::Triple::mips:
  7080. case llvm::Triple::mipsel:
  7081. case llvm::Triple::mips64:
  7082. case llvm::Triple::mips64el: {
  7083. StringRef CPUName;
  7084. StringRef ABIName;
  7085. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7086. CmdArgs.push_back("-march");
  7087. CmdArgs.push_back(CPUName.data());
  7088. CmdArgs.push_back("-mabi");
  7089. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  7090. if (getToolChain().getArch() == llvm::Triple::mips ||
  7091. getToolChain().getArch() == llvm::Triple::mips64)
  7092. CmdArgs.push_back("-EB");
  7093. else
  7094. CmdArgs.push_back("-EL");
  7095. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  7096. StringRef v = A->getValue();
  7097. CmdArgs.push_back(Args.MakeArgString("-G" + v));
  7098. A->claim();
  7099. }
  7100. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7101. break;
  7102. }
  7103. case llvm::Triple::arm:
  7104. case llvm::Triple::armeb:
  7105. case llvm::Triple::thumb:
  7106. case llvm::Triple::thumbeb: {
  7107. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  7108. if (ABI == arm::FloatABI::Hard)
  7109. CmdArgs.push_back("-mfpu=vfp");
  7110. else
  7111. CmdArgs.push_back("-mfpu=softvfp");
  7112. switch (getToolChain().getTriple().getEnvironment()) {
  7113. case llvm::Triple::GNUEABIHF:
  7114. case llvm::Triple::GNUEABI:
  7115. case llvm::Triple::EABI:
  7116. CmdArgs.push_back("-meabi=5");
  7117. break;
  7118. default:
  7119. CmdArgs.push_back("-matpcs");
  7120. }
  7121. break;
  7122. }
  7123. case llvm::Triple::sparc:
  7124. case llvm::Triple::sparcel:
  7125. case llvm::Triple::sparcv9: {
  7126. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7127. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7128. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7129. break;
  7130. }
  7131. }
  7132. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7133. CmdArgs.push_back("-o");
  7134. CmdArgs.push_back(Output.getFilename());
  7135. for (const auto &II : Inputs)
  7136. CmdArgs.push_back(II.getFilename());
  7137. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7138. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7139. }
  7140. void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7141. const InputInfo &Output,
  7142. const InputInfoList &Inputs,
  7143. const ArgList &Args,
  7144. const char *LinkingOutput) const {
  7145. const toolchains::FreeBSD &ToolChain =
  7146. static_cast<const toolchains::FreeBSD &>(getToolChain());
  7147. const Driver &D = ToolChain.getDriver();
  7148. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7149. const bool IsPIE =
  7150. !Args.hasArg(options::OPT_shared) &&
  7151. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  7152. ArgStringList CmdArgs;
  7153. // Silence warning for "clang -g foo.o -o foo"
  7154. Args.ClaimAllArgs(options::OPT_g_Group);
  7155. // and "clang -emit-llvm foo.o -o foo"
  7156. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7157. // and for "clang -w foo.o -o foo". Other warning options are already
  7158. // handled somewhere else.
  7159. Args.ClaimAllArgs(options::OPT_w);
  7160. if (!D.SysRoot.empty())
  7161. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7162. if (IsPIE)
  7163. CmdArgs.push_back("-pie");
  7164. CmdArgs.push_back("--eh-frame-hdr");
  7165. if (Args.hasArg(options::OPT_static)) {
  7166. CmdArgs.push_back("-Bstatic");
  7167. } else {
  7168. if (Args.hasArg(options::OPT_rdynamic))
  7169. CmdArgs.push_back("-export-dynamic");
  7170. if (Args.hasArg(options::OPT_shared)) {
  7171. CmdArgs.push_back("-Bshareable");
  7172. } else {
  7173. CmdArgs.push_back("-dynamic-linker");
  7174. CmdArgs.push_back("/libexec/ld-elf.so.1");
  7175. }
  7176. if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
  7177. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
  7178. Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
  7179. CmdArgs.push_back("--hash-style=both");
  7180. }
  7181. }
  7182. CmdArgs.push_back("--enable-new-dtags");
  7183. }
  7184. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  7185. // instruct ld in the base system to link 32-bit code.
  7186. if (Arch == llvm::Triple::x86) {
  7187. CmdArgs.push_back("-m");
  7188. CmdArgs.push_back("elf_i386_fbsd");
  7189. }
  7190. if (Arch == llvm::Triple::ppc) {
  7191. CmdArgs.push_back("-m");
  7192. CmdArgs.push_back("elf32ppc_fbsd");
  7193. }
  7194. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  7195. if (ToolChain.getArch() == llvm::Triple::mips ||
  7196. ToolChain.getArch() == llvm::Triple::mipsel ||
  7197. ToolChain.getArch() == llvm::Triple::mips64 ||
  7198. ToolChain.getArch() == llvm::Triple::mips64el) {
  7199. StringRef v = A->getValue();
  7200. CmdArgs.push_back(Args.MakeArgString("-G" + v));
  7201. A->claim();
  7202. }
  7203. }
  7204. if (Output.isFilename()) {
  7205. CmdArgs.push_back("-o");
  7206. CmdArgs.push_back(Output.getFilename());
  7207. } else {
  7208. assert(Output.isNothing() && "Invalid output.");
  7209. }
  7210. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7211. const char *crt1 = nullptr;
  7212. if (!Args.hasArg(options::OPT_shared)) {
  7213. if (Args.hasArg(options::OPT_pg))
  7214. crt1 = "gcrt1.o";
  7215. else if (IsPIE)
  7216. crt1 = "Scrt1.o";
  7217. else
  7218. crt1 = "crt1.o";
  7219. }
  7220. if (crt1)
  7221. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  7222. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  7223. const char *crtbegin = nullptr;
  7224. if (Args.hasArg(options::OPT_static))
  7225. crtbegin = "crtbeginT.o";
  7226. else if (Args.hasArg(options::OPT_shared) || IsPIE)
  7227. crtbegin = "crtbeginS.o";
  7228. else
  7229. crtbegin = "crtbegin.o";
  7230. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  7231. }
  7232. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7233. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  7234. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  7235. Args.AddAllArgs(CmdArgs, options::OPT_e);
  7236. Args.AddAllArgs(CmdArgs, options::OPT_s);
  7237. Args.AddAllArgs(CmdArgs, options::OPT_t);
  7238. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  7239. Args.AddAllArgs(CmdArgs, options::OPT_r);
  7240. if (D.isUsingLTO())
  7241. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  7242. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  7243. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  7244. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7245. addOpenMPRuntime(CmdArgs, ToolChain, Args);
  7246. if (D.CCCIsCXX()) {
  7247. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7248. if (Args.hasArg(options::OPT_pg))
  7249. CmdArgs.push_back("-lm_p");
  7250. else
  7251. CmdArgs.push_back("-lm");
  7252. }
  7253. if (NeedsSanitizerDeps)
  7254. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  7255. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  7256. // the default system libraries. Just mimic this for now.
  7257. if (Args.hasArg(options::OPT_pg))
  7258. CmdArgs.push_back("-lgcc_p");
  7259. else
  7260. CmdArgs.push_back("-lgcc");
  7261. if (Args.hasArg(options::OPT_static)) {
  7262. CmdArgs.push_back("-lgcc_eh");
  7263. } else if (Args.hasArg(options::OPT_pg)) {
  7264. CmdArgs.push_back("-lgcc_eh_p");
  7265. } else {
  7266. CmdArgs.push_back("--as-needed");
  7267. CmdArgs.push_back("-lgcc_s");
  7268. CmdArgs.push_back("--no-as-needed");
  7269. }
  7270. if (Args.hasArg(options::OPT_pthread)) {
  7271. if (Args.hasArg(options::OPT_pg))
  7272. CmdArgs.push_back("-lpthread_p");
  7273. else
  7274. CmdArgs.push_back("-lpthread");
  7275. }
  7276. if (Args.hasArg(options::OPT_pg)) {
  7277. if (Args.hasArg(options::OPT_shared))
  7278. CmdArgs.push_back("-lc");
  7279. else
  7280. CmdArgs.push_back("-lc_p");
  7281. CmdArgs.push_back("-lgcc_p");
  7282. } else {
  7283. CmdArgs.push_back("-lc");
  7284. CmdArgs.push_back("-lgcc");
  7285. }
  7286. if (Args.hasArg(options::OPT_static)) {
  7287. CmdArgs.push_back("-lgcc_eh");
  7288. } else if (Args.hasArg(options::OPT_pg)) {
  7289. CmdArgs.push_back("-lgcc_eh_p");
  7290. } else {
  7291. CmdArgs.push_back("--as-needed");
  7292. CmdArgs.push_back("-lgcc_s");
  7293. CmdArgs.push_back("--no-as-needed");
  7294. }
  7295. }
  7296. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7297. if (Args.hasArg(options::OPT_shared) || IsPIE)
  7298. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  7299. else
  7300. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  7301. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  7302. }
  7303. ToolChain.addProfileRTLibs(Args, CmdArgs);
  7304. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7305. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7306. }
  7307. void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7308. const InputInfo &Output,
  7309. const InputInfoList &Inputs,
  7310. const ArgList &Args,
  7311. const char *LinkingOutput) const {
  7312. claimNoWarnArgs(Args);
  7313. ArgStringList CmdArgs;
  7314. // GNU as needs different flags for creating the correct output format
  7315. // on architectures with different ABIs or optional feature sets.
  7316. switch (getToolChain().getArch()) {
  7317. case llvm::Triple::x86:
  7318. CmdArgs.push_back("--32");
  7319. break;
  7320. case llvm::Triple::arm:
  7321. case llvm::Triple::armeb:
  7322. case llvm::Triple::thumb:
  7323. case llvm::Triple::thumbeb: {
  7324. StringRef MArch, MCPU;
  7325. getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
  7326. std::string Arch =
  7327. arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
  7328. CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
  7329. break;
  7330. }
  7331. case llvm::Triple::mips:
  7332. case llvm::Triple::mipsel:
  7333. case llvm::Triple::mips64:
  7334. case llvm::Triple::mips64el: {
  7335. StringRef CPUName;
  7336. StringRef ABIName;
  7337. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7338. CmdArgs.push_back("-march");
  7339. CmdArgs.push_back(CPUName.data());
  7340. CmdArgs.push_back("-mabi");
  7341. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  7342. if (getToolChain().getArch() == llvm::Triple::mips ||
  7343. getToolChain().getArch() == llvm::Triple::mips64)
  7344. CmdArgs.push_back("-EB");
  7345. else
  7346. CmdArgs.push_back("-EL");
  7347. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7348. break;
  7349. }
  7350. case llvm::Triple::sparc:
  7351. case llvm::Triple::sparcel: {
  7352. CmdArgs.push_back("-32");
  7353. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7354. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7355. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7356. break;
  7357. }
  7358. case llvm::Triple::sparcv9: {
  7359. CmdArgs.push_back("-64");
  7360. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7361. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7362. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7363. break;
  7364. }
  7365. default:
  7366. break;
  7367. }
  7368. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7369. CmdArgs.push_back("-o");
  7370. CmdArgs.push_back(Output.getFilename());
  7371. for (const auto &II : Inputs)
  7372. CmdArgs.push_back(II.getFilename());
  7373. const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
  7374. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7375. }
  7376. void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7377. const InputInfo &Output,
  7378. const InputInfoList &Inputs,
  7379. const ArgList &Args,
  7380. const char *LinkingOutput) const {
  7381. const Driver &D = getToolChain().getDriver();
  7382. ArgStringList CmdArgs;
  7383. if (!D.SysRoot.empty())
  7384. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7385. CmdArgs.push_back("--eh-frame-hdr");
  7386. if (Args.hasArg(options::OPT_static)) {
  7387. CmdArgs.push_back("-Bstatic");
  7388. } else {
  7389. if (Args.hasArg(options::OPT_rdynamic))
  7390. CmdArgs.push_back("-export-dynamic");
  7391. if (Args.hasArg(options::OPT_shared)) {
  7392. CmdArgs.push_back("-Bshareable");
  7393. } else {
  7394. CmdArgs.push_back("-dynamic-linker");
  7395. CmdArgs.push_back("/libexec/ld.elf_so");
  7396. }
  7397. }
  7398. // Many NetBSD architectures support more than one ABI.
  7399. // Determine the correct emulation for ld.
  7400. switch (getToolChain().getArch()) {
  7401. case llvm::Triple::x86:
  7402. CmdArgs.push_back("-m");
  7403. CmdArgs.push_back("elf_i386");
  7404. break;
  7405. case llvm::Triple::arm:
  7406. case llvm::Triple::thumb:
  7407. CmdArgs.push_back("-m");
  7408. switch (getToolChain().getTriple().getEnvironment()) {
  7409. case llvm::Triple::EABI:
  7410. case llvm::Triple::GNUEABI:
  7411. CmdArgs.push_back("armelf_nbsd_eabi");
  7412. break;
  7413. case llvm::Triple::EABIHF:
  7414. case llvm::Triple::GNUEABIHF:
  7415. CmdArgs.push_back("armelf_nbsd_eabihf");
  7416. break;
  7417. default:
  7418. CmdArgs.push_back("armelf_nbsd");
  7419. break;
  7420. }
  7421. break;
  7422. case llvm::Triple::armeb:
  7423. case llvm::Triple::thumbeb:
  7424. arm::appendEBLinkFlags(
  7425. Args, CmdArgs,
  7426. llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
  7427. CmdArgs.push_back("-m");
  7428. switch (getToolChain().getTriple().getEnvironment()) {
  7429. case llvm::Triple::EABI:
  7430. case llvm::Triple::GNUEABI:
  7431. CmdArgs.push_back("armelfb_nbsd_eabi");
  7432. break;
  7433. case llvm::Triple::EABIHF:
  7434. case llvm::Triple::GNUEABIHF:
  7435. CmdArgs.push_back("armelfb_nbsd_eabihf");
  7436. break;
  7437. default:
  7438. CmdArgs.push_back("armelfb_nbsd");
  7439. break;
  7440. }
  7441. break;
  7442. case llvm::Triple::mips64:
  7443. case llvm::Triple::mips64el:
  7444. if (mips::hasMipsAbiArg(Args, "32")) {
  7445. CmdArgs.push_back("-m");
  7446. if (getToolChain().getArch() == llvm::Triple::mips64)
  7447. CmdArgs.push_back("elf32btsmip");
  7448. else
  7449. CmdArgs.push_back("elf32ltsmip");
  7450. } else if (mips::hasMipsAbiArg(Args, "64")) {
  7451. CmdArgs.push_back("-m");
  7452. if (getToolChain().getArch() == llvm::Triple::mips64)
  7453. CmdArgs.push_back("elf64btsmip");
  7454. else
  7455. CmdArgs.push_back("elf64ltsmip");
  7456. }
  7457. break;
  7458. case llvm::Triple::ppc:
  7459. CmdArgs.push_back("-m");
  7460. CmdArgs.push_back("elf32ppc_nbsd");
  7461. break;
  7462. case llvm::Triple::ppc64:
  7463. case llvm::Triple::ppc64le:
  7464. CmdArgs.push_back("-m");
  7465. CmdArgs.push_back("elf64ppc");
  7466. break;
  7467. case llvm::Triple::sparc:
  7468. CmdArgs.push_back("-m");
  7469. CmdArgs.push_back("elf32_sparc");
  7470. break;
  7471. case llvm::Triple::sparcv9:
  7472. CmdArgs.push_back("-m");
  7473. CmdArgs.push_back("elf64_sparc");
  7474. break;
  7475. default:
  7476. break;
  7477. }
  7478. if (Output.isFilename()) {
  7479. CmdArgs.push_back("-o");
  7480. CmdArgs.push_back(Output.getFilename());
  7481. } else {
  7482. assert(Output.isNothing() && "Invalid output.");
  7483. }
  7484. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7485. if (!Args.hasArg(options::OPT_shared)) {
  7486. CmdArgs.push_back(
  7487. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  7488. CmdArgs.push_back(
  7489. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7490. CmdArgs.push_back(
  7491. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7492. } else {
  7493. CmdArgs.push_back(
  7494. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7495. CmdArgs.push_back(
  7496. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7497. }
  7498. }
  7499. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7500. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  7501. Args.AddAllArgs(CmdArgs, options::OPT_e);
  7502. Args.AddAllArgs(CmdArgs, options::OPT_s);
  7503. Args.AddAllArgs(CmdArgs, options::OPT_t);
  7504. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  7505. Args.AddAllArgs(CmdArgs, options::OPT_r);
  7506. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7507. unsigned Major, Minor, Micro;
  7508. getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
  7509. bool useLibgcc = true;
  7510. if (Major >= 7 || Major == 0) {
  7511. switch (getToolChain().getArch()) {
  7512. case llvm::Triple::aarch64:
  7513. case llvm::Triple::arm:
  7514. case llvm::Triple::armeb:
  7515. case llvm::Triple::thumb:
  7516. case llvm::Triple::thumbeb:
  7517. case llvm::Triple::ppc:
  7518. case llvm::Triple::ppc64:
  7519. case llvm::Triple::ppc64le:
  7520. case llvm::Triple::sparc:
  7521. case llvm::Triple::sparcv9:
  7522. case llvm::Triple::x86:
  7523. case llvm::Triple::x86_64:
  7524. useLibgcc = false;
  7525. break;
  7526. default:
  7527. break;
  7528. }
  7529. }
  7530. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7531. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  7532. if (D.CCCIsCXX()) {
  7533. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7534. CmdArgs.push_back("-lm");
  7535. }
  7536. if (Args.hasArg(options::OPT_pthread))
  7537. CmdArgs.push_back("-lpthread");
  7538. CmdArgs.push_back("-lc");
  7539. if (useLibgcc) {
  7540. if (Args.hasArg(options::OPT_static)) {
  7541. // libgcc_eh depends on libc, so resolve as much as possible,
  7542. // pull in any new requirements from libc and then get the rest
  7543. // of libgcc.
  7544. CmdArgs.push_back("-lgcc_eh");
  7545. CmdArgs.push_back("-lc");
  7546. CmdArgs.push_back("-lgcc");
  7547. } else {
  7548. CmdArgs.push_back("-lgcc");
  7549. CmdArgs.push_back("--as-needed");
  7550. CmdArgs.push_back("-lgcc_s");
  7551. CmdArgs.push_back("--no-as-needed");
  7552. }
  7553. }
  7554. }
  7555. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7556. if (!Args.hasArg(options::OPT_shared))
  7557. CmdArgs.push_back(
  7558. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7559. else
  7560. CmdArgs.push_back(
  7561. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7562. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  7563. }
  7564. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7565. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7566. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7567. }
  7568. void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7569. const InputInfo &Output,
  7570. const InputInfoList &Inputs,
  7571. const ArgList &Args,
  7572. const char *LinkingOutput) const {
  7573. claimNoWarnArgs(Args);
  7574. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  7575. llvm::Triple Triple = llvm::Triple(TripleStr);
  7576. ArgStringList CmdArgs;
  7577. llvm::Reloc::Model RelocationModel;
  7578. unsigned PICLevel;
  7579. bool IsPIE;
  7580. std::tie(RelocationModel, PICLevel, IsPIE) =
  7581. ParsePICArgs(getToolChain(), Triple, Args);
  7582. switch (getToolChain().getArch()) {
  7583. default:
  7584. break;
  7585. // Add --32/--64 to make sure we get the format we want.
  7586. // This is incomplete
  7587. case llvm::Triple::x86:
  7588. CmdArgs.push_back("--32");
  7589. break;
  7590. case llvm::Triple::x86_64:
  7591. if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
  7592. CmdArgs.push_back("--x32");
  7593. else
  7594. CmdArgs.push_back("--64");
  7595. break;
  7596. case llvm::Triple::ppc:
  7597. CmdArgs.push_back("-a32");
  7598. CmdArgs.push_back("-mppc");
  7599. CmdArgs.push_back("-many");
  7600. break;
  7601. case llvm::Triple::ppc64:
  7602. CmdArgs.push_back("-a64");
  7603. CmdArgs.push_back("-mppc64");
  7604. CmdArgs.push_back("-many");
  7605. break;
  7606. case llvm::Triple::ppc64le:
  7607. CmdArgs.push_back("-a64");
  7608. CmdArgs.push_back("-mppc64");
  7609. CmdArgs.push_back("-many");
  7610. CmdArgs.push_back("-mlittle-endian");
  7611. break;
  7612. case llvm::Triple::sparc:
  7613. case llvm::Triple::sparcel: {
  7614. CmdArgs.push_back("-32");
  7615. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7616. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7617. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7618. break;
  7619. }
  7620. case llvm::Triple::sparcv9: {
  7621. CmdArgs.push_back("-64");
  7622. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7623. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7624. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7625. break;
  7626. }
  7627. case llvm::Triple::arm:
  7628. case llvm::Triple::armeb:
  7629. case llvm::Triple::thumb:
  7630. case llvm::Triple::thumbeb: {
  7631. const llvm::Triple &Triple2 = getToolChain().getTriple();
  7632. switch (Triple2.getSubArch()) {
  7633. case llvm::Triple::ARMSubArch_v7:
  7634. CmdArgs.push_back("-mfpu=neon");
  7635. break;
  7636. case llvm::Triple::ARMSubArch_v8:
  7637. CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
  7638. break;
  7639. default:
  7640. break;
  7641. }
  7642. switch (arm::getARMFloatABI(getToolChain(), Args)) {
  7643. case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
  7644. case arm::FloatABI::Soft:
  7645. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
  7646. break;
  7647. case arm::FloatABI::SoftFP:
  7648. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
  7649. break;
  7650. case arm::FloatABI::Hard:
  7651. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
  7652. break;
  7653. }
  7654. Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
  7655. // FIXME: remove krait check when GNU tools support krait cpu
  7656. // for now replace it with -mcpu=cortex-a15 to avoid a lower
  7657. // march from being picked in the absence of a cpu flag.
  7658. Arg *A;
  7659. if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
  7660. StringRef(A->getValue()).lower() == "krait")
  7661. CmdArgs.push_back("-mcpu=cortex-a15");
  7662. else
  7663. Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
  7664. Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
  7665. break;
  7666. }
  7667. case llvm::Triple::mips:
  7668. case llvm::Triple::mipsel:
  7669. case llvm::Triple::mips64:
  7670. case llvm::Triple::mips64el: {
  7671. StringRef CPUName;
  7672. StringRef ABIName;
  7673. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7674. ABIName = getGnuCompatibleMipsABIName(ABIName);
  7675. CmdArgs.push_back("-march");
  7676. CmdArgs.push_back(CPUName.data());
  7677. CmdArgs.push_back("-mabi");
  7678. CmdArgs.push_back(ABIName.data());
  7679. // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
  7680. // or -mshared (not implemented) is in effect.
  7681. if (RelocationModel == llvm::Reloc::Static)
  7682. CmdArgs.push_back("-mno-shared");
  7683. // LLVM doesn't support -mplt yet and acts as if it is always given.
  7684. // However, -mplt has no effect with the N64 ABI.
  7685. CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
  7686. if (getToolChain().getArch() == llvm::Triple::mips ||
  7687. getToolChain().getArch() == llvm::Triple::mips64)
  7688. CmdArgs.push_back("-EB");
  7689. else
  7690. CmdArgs.push_back("-EL");
  7691. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  7692. if (StringRef(A->getValue()) == "2008")
  7693. CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
  7694. }
  7695. // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
  7696. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  7697. options::OPT_mfp64)) {
  7698. A->claim();
  7699. A->render(Args, CmdArgs);
  7700. } else if (mips::shouldUseFPXX(
  7701. Args, getToolChain().getTriple(), CPUName, ABIName,
  7702. getMipsFloatABI(getToolChain().getDriver(), Args)))
  7703. CmdArgs.push_back("-mfpxx");
  7704. // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
  7705. // -mno-mips16 is actually -no-mips16.
  7706. if (Arg *A =
  7707. Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
  7708. if (A->getOption().matches(options::OPT_mips16)) {
  7709. A->claim();
  7710. A->render(Args, CmdArgs);
  7711. } else {
  7712. A->claim();
  7713. CmdArgs.push_back("-no-mips16");
  7714. }
  7715. }
  7716. Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
  7717. options::OPT_mno_micromips);
  7718. Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
  7719. Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
  7720. if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
  7721. // Do not use AddLastArg because not all versions of MIPS assembler
  7722. // support -mmsa / -mno-msa options.
  7723. if (A->getOption().matches(options::OPT_mmsa))
  7724. CmdArgs.push_back(Args.MakeArgString("-mmsa"));
  7725. }
  7726. Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
  7727. options::OPT_msoft_float);
  7728. Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
  7729. options::OPT_msingle_float);
  7730. Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
  7731. options::OPT_mno_odd_spreg);
  7732. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7733. break;
  7734. }
  7735. case llvm::Triple::systemz: {
  7736. // Always pass an -march option, since our default of z10 is later
  7737. // than the GNU assembler's default.
  7738. StringRef CPUName = getSystemZTargetCPU(Args);
  7739. CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
  7740. break;
  7741. }
  7742. }
  7743. Args.AddAllArgs(CmdArgs, options::OPT_I);
  7744. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7745. CmdArgs.push_back("-o");
  7746. CmdArgs.push_back(Output.getFilename());
  7747. for (const auto &II : Inputs)
  7748. CmdArgs.push_back(II.getFilename());
  7749. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7750. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7751. // Handle the debug info splitting at object creation time if we're
  7752. // creating an object.
  7753. // TODO: Currently only works on linux with newer objcopy.
  7754. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  7755. getToolChain().getTriple().isOSLinux())
  7756. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  7757. SplitDebugName(Args, Inputs[0]));
  7758. }
  7759. static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
  7760. ArgStringList &CmdArgs, const ArgList &Args) {
  7761. bool isAndroid = Triple.isAndroid();
  7762. bool isCygMing = Triple.isOSCygMing();
  7763. bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
  7764. Args.hasArg(options::OPT_static);
  7765. if (!D.CCCIsCXX())
  7766. CmdArgs.push_back("-lgcc");
  7767. if (StaticLibgcc || isAndroid) {
  7768. if (D.CCCIsCXX())
  7769. CmdArgs.push_back("-lgcc");
  7770. } else {
  7771. if (!D.CCCIsCXX() && !isCygMing)
  7772. CmdArgs.push_back("--as-needed");
  7773. CmdArgs.push_back("-lgcc_s");
  7774. if (!D.CCCIsCXX() && !isCygMing)
  7775. CmdArgs.push_back("--no-as-needed");
  7776. }
  7777. if (StaticLibgcc && !isAndroid)
  7778. CmdArgs.push_back("-lgcc_eh");
  7779. else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
  7780. CmdArgs.push_back("-lgcc");
  7781. // According to Android ABI, we have to link with libdl if we are
  7782. // linking with non-static libgcc.
  7783. //
  7784. // NOTE: This fixes a link error on Android MIPS as well. The non-static
  7785. // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
  7786. if (isAndroid && !StaticLibgcc)
  7787. CmdArgs.push_back("-ldl");
  7788. }
  7789. static std::string getLinuxDynamicLinker(const ArgList &Args,
  7790. const toolchains::Linux &ToolChain) {
  7791. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7792. if (ToolChain.getTriple().isAndroid()) {
  7793. if (ToolChain.getTriple().isArch64Bit())
  7794. return "/system/bin/linker64";
  7795. else
  7796. return "/system/bin/linker";
  7797. } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
  7798. Arch == llvm::Triple::sparcel)
  7799. return "/lib/ld-linux.so.2";
  7800. else if (Arch == llvm::Triple::aarch64)
  7801. return "/lib/ld-linux-aarch64.so.1";
  7802. else if (Arch == llvm::Triple::aarch64_be)
  7803. return "/lib/ld-linux-aarch64_be.so.1";
  7804. else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
  7805. if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
  7806. arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
  7807. return "/lib/ld-linux-armhf.so.3";
  7808. else
  7809. return "/lib/ld-linux.so.3";
  7810. } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
  7811. // TODO: check which dynamic linker name.
  7812. if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
  7813. arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
  7814. return "/lib/ld-linux-armhf.so.3";
  7815. else
  7816. return "/lib/ld-linux.so.3";
  7817. } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
  7818. Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
  7819. std::string LibDir =
  7820. "/lib" + mips::getMipsABILibSuffix(Args, ToolChain.getTriple());
  7821. StringRef LibName;
  7822. bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
  7823. if (mips::isUCLibc(Args))
  7824. LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
  7825. else if (!ToolChain.getTriple().hasEnvironment()) {
  7826. bool LE = (ToolChain.getTriple().getArch() == llvm::Triple::mipsel) ||
  7827. (ToolChain.getTriple().getArch() == llvm::Triple::mips64el);
  7828. LibName = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
  7829. } else
  7830. LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
  7831. return (LibDir + "/" + LibName).str();
  7832. } else if (Arch == llvm::Triple::ppc)
  7833. return "/lib/ld.so.1";
  7834. else if (Arch == llvm::Triple::ppc64) {
  7835. if (ppc::hasPPCAbiArg(Args, "elfv2"))
  7836. return "/lib64/ld64.so.2";
  7837. return "/lib64/ld64.so.1";
  7838. } else if (Arch == llvm::Triple::ppc64le) {
  7839. if (ppc::hasPPCAbiArg(Args, "elfv1"))
  7840. return "/lib64/ld64.so.1";
  7841. return "/lib64/ld64.so.2";
  7842. } else if (Arch == llvm::Triple::systemz)
  7843. return "/lib/ld64.so.1";
  7844. else if (Arch == llvm::Triple::sparcv9)
  7845. return "/lib64/ld-linux.so.2";
  7846. else if (Arch == llvm::Triple::x86_64 &&
  7847. ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
  7848. return "/libx32/ld-linux-x32.so.2";
  7849. else
  7850. return "/lib64/ld-linux-x86-64.so.2";
  7851. }
  7852. static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
  7853. ArgStringList &CmdArgs, const ArgList &Args) {
  7854. // Make use of compiler-rt if --rtlib option is used
  7855. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
  7856. switch (RLT) {
  7857. case ToolChain::RLT_CompilerRT:
  7858. switch (TC.getTriple().getOS()) {
  7859. default:
  7860. llvm_unreachable("unsupported OS");
  7861. case llvm::Triple::Win32:
  7862. case llvm::Triple::Linux:
  7863. addClangRT(TC, Args, CmdArgs);
  7864. break;
  7865. }
  7866. break;
  7867. case ToolChain::RLT_Libgcc:
  7868. // Make sure libgcc is not used under MSVC environment by default
  7869. if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
  7870. // Issue error diagnostic if libgcc is explicitly specified
  7871. // through command line as --rtlib option argument.
  7872. if (Args.hasArg(options::OPT_rtlib_EQ)) {
  7873. TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
  7874. << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
  7875. }
  7876. } else
  7877. AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
  7878. break;
  7879. }
  7880. }
  7881. static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
  7882. switch (T.getArch()) {
  7883. case llvm::Triple::x86:
  7884. return "elf_i386";
  7885. case llvm::Triple::aarch64:
  7886. return "aarch64linux";
  7887. case llvm::Triple::aarch64_be:
  7888. return "aarch64_be_linux";
  7889. case llvm::Triple::arm:
  7890. case llvm::Triple::thumb:
  7891. return "armelf_linux_eabi";
  7892. case llvm::Triple::armeb:
  7893. case llvm::Triple::thumbeb:
  7894. return "armebelf_linux_eabi"; /* TODO: check which NAME. */
  7895. case llvm::Triple::ppc:
  7896. return "elf32ppclinux";
  7897. case llvm::Triple::ppc64:
  7898. return "elf64ppc";
  7899. case llvm::Triple::ppc64le:
  7900. return "elf64lppc";
  7901. case llvm::Triple::sparc:
  7902. case llvm::Triple::sparcel:
  7903. return "elf32_sparc";
  7904. case llvm::Triple::sparcv9:
  7905. return "elf64_sparc";
  7906. case llvm::Triple::mips:
  7907. return "elf32btsmip";
  7908. case llvm::Triple::mipsel:
  7909. return "elf32ltsmip";
  7910. case llvm::Triple::mips64:
  7911. if (mips::hasMipsAbiArg(Args, "n32"))
  7912. return "elf32btsmipn32";
  7913. return "elf64btsmip";
  7914. case llvm::Triple::mips64el:
  7915. if (mips::hasMipsAbiArg(Args, "n32"))
  7916. return "elf32ltsmipn32";
  7917. return "elf64ltsmip";
  7918. case llvm::Triple::systemz:
  7919. return "elf64_s390";
  7920. case llvm::Triple::x86_64:
  7921. if (T.getEnvironment() == llvm::Triple::GNUX32)
  7922. return "elf32_x86_64";
  7923. return "elf_x86_64";
  7924. default:
  7925. llvm_unreachable("Unexpected arch");
  7926. }
  7927. }
  7928. void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7929. const InputInfo &Output,
  7930. const InputInfoList &Inputs,
  7931. const ArgList &Args,
  7932. const char *LinkingOutput) const {
  7933. const toolchains::Linux &ToolChain =
  7934. static_cast<const toolchains::Linux &>(getToolChain());
  7935. const Driver &D = ToolChain.getDriver();
  7936. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  7937. llvm::Triple Triple = llvm::Triple(TripleStr);
  7938. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7939. const bool isAndroid = ToolChain.getTriple().isAndroid();
  7940. const bool IsPIE =
  7941. !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
  7942. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  7943. const bool HasCRTBeginEndFiles =
  7944. ToolChain.getTriple().hasEnvironment() ||
  7945. (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
  7946. ArgStringList CmdArgs;
  7947. // Silence warning for "clang -g foo.o -o foo"
  7948. Args.ClaimAllArgs(options::OPT_g_Group);
  7949. // and "clang -emit-llvm foo.o -o foo"
  7950. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7951. // and for "clang -w foo.o -o foo". Other warning options are already
  7952. // handled somewhere else.
  7953. Args.ClaimAllArgs(options::OPT_w);
  7954. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  7955. if (llvm::sys::path::filename(Exec) == "lld") {
  7956. CmdArgs.push_back("-flavor");
  7957. CmdArgs.push_back("old-gnu");
  7958. CmdArgs.push_back("-target");
  7959. CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
  7960. }
  7961. if (!D.SysRoot.empty())
  7962. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7963. if (IsPIE)
  7964. CmdArgs.push_back("-pie");
  7965. if (Args.hasArg(options::OPT_rdynamic))
  7966. CmdArgs.push_back("-export-dynamic");
  7967. if (Args.hasArg(options::OPT_s))
  7968. CmdArgs.push_back("-s");
  7969. if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
  7970. arm::appendEBLinkFlags(Args, CmdArgs, Triple);
  7971. for (const auto &Opt : ToolChain.ExtraOpts)
  7972. CmdArgs.push_back(Opt.c_str());
  7973. if (!Args.hasArg(options::OPT_static)) {
  7974. CmdArgs.push_back("--eh-frame-hdr");
  7975. }
  7976. CmdArgs.push_back("-m");
  7977. CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
  7978. if (Args.hasArg(options::OPT_static)) {
  7979. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  7980. Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
  7981. CmdArgs.push_back("-Bstatic");
  7982. else
  7983. CmdArgs.push_back("-static");
  7984. } else if (Args.hasArg(options::OPT_shared)) {
  7985. CmdArgs.push_back("-shared");
  7986. }
  7987. if (!Args.hasArg(options::OPT_static)) {
  7988. if (Args.hasArg(options::OPT_rdynamic))
  7989. CmdArgs.push_back("-export-dynamic");
  7990. if (!Args.hasArg(options::OPT_shared)) {
  7991. const std::string Loader =
  7992. D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain);
  7993. CmdArgs.push_back("-dynamic-linker");
  7994. CmdArgs.push_back(Args.MakeArgString(Loader));
  7995. }
  7996. }
  7997. CmdArgs.push_back("-o");
  7998. CmdArgs.push_back(Output.getFilename());
  7999. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8000. if (!isAndroid) {
  8001. const char *crt1 = nullptr;
  8002. if (!Args.hasArg(options::OPT_shared)) {
  8003. if (Args.hasArg(options::OPT_pg))
  8004. crt1 = "gcrt1.o";
  8005. else if (IsPIE)
  8006. crt1 = "Scrt1.o";
  8007. else
  8008. crt1 = "crt1.o";
  8009. }
  8010. if (crt1)
  8011. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  8012. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  8013. }
  8014. const char *crtbegin;
  8015. if (Args.hasArg(options::OPT_static))
  8016. crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
  8017. else if (Args.hasArg(options::OPT_shared))
  8018. crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
  8019. else if (IsPIE)
  8020. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
  8021. else
  8022. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
  8023. if (HasCRTBeginEndFiles)
  8024. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  8025. // Add crtfastmath.o if available and fast math is enabled.
  8026. ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  8027. }
  8028. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8029. Args.AddAllArgs(CmdArgs, options::OPT_u);
  8030. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  8031. if (D.isUsingLTO())
  8032. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  8033. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  8034. CmdArgs.push_back("--no-demangle");
  8035. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  8036. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  8037. // The profile runtime also needs access to system libraries.
  8038. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8039. if (D.CCCIsCXX() &&
  8040. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8041. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  8042. !Args.hasArg(options::OPT_static);
  8043. if (OnlyLibstdcxxStatic)
  8044. CmdArgs.push_back("-Bstatic");
  8045. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  8046. if (OnlyLibstdcxxStatic)
  8047. CmdArgs.push_back("-Bdynamic");
  8048. CmdArgs.push_back("-lm");
  8049. }
  8050. // Silence warnings when linking C code with a C++ '-stdlib' argument.
  8051. Args.ClaimAllArgs(options::OPT_stdlib_EQ);
  8052. if (!Args.hasArg(options::OPT_nostdlib)) {
  8053. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8054. if (Args.hasArg(options::OPT_static))
  8055. CmdArgs.push_back("--start-group");
  8056. if (NeedsSanitizerDeps)
  8057. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  8058. bool WantPthread = Args.hasArg(options::OPT_pthread) ||
  8059. Args.hasArg(options::OPT_pthreads);
  8060. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  8061. options::OPT_fno_openmp, false)) {
  8062. // OpenMP runtimes implies pthreads when using the GNU toolchain.
  8063. // FIXME: Does this really make sense for all GNU toolchains?
  8064. WantPthread = true;
  8065. // Also link the particular OpenMP runtimes.
  8066. switch (getOpenMPRuntime(ToolChain, Args)) {
  8067. case OMPRT_OMP:
  8068. CmdArgs.push_back("-lomp");
  8069. break;
  8070. case OMPRT_GOMP:
  8071. CmdArgs.push_back("-lgomp");
  8072. // FIXME: Exclude this for platforms with libgomp that don't require
  8073. // librt. Most modern Linux platforms require it, but some may not.
  8074. CmdArgs.push_back("-lrt");
  8075. break;
  8076. case OMPRT_IOMP5:
  8077. CmdArgs.push_back("-liomp5");
  8078. break;
  8079. case OMPRT_Unknown:
  8080. // Already diagnosed.
  8081. break;
  8082. }
  8083. }
  8084. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  8085. if (WantPthread && !isAndroid)
  8086. CmdArgs.push_back("-lpthread");
  8087. if (Args.hasArg(options::OPT_fsplit_stack))
  8088. CmdArgs.push_back("--wrap=pthread_create");
  8089. CmdArgs.push_back("-lc");
  8090. if (Args.hasArg(options::OPT_static))
  8091. CmdArgs.push_back("--end-group");
  8092. else
  8093. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  8094. }
  8095. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8096. const char *crtend;
  8097. if (Args.hasArg(options::OPT_shared))
  8098. crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
  8099. else if (IsPIE)
  8100. crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
  8101. else
  8102. crtend = isAndroid ? "crtend_android.o" : "crtend.o";
  8103. if (HasCRTBeginEndFiles)
  8104. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  8105. if (!isAndroid)
  8106. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  8107. }
  8108. }
  8109. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8110. }
  8111. // NaCl ARM assembly (inline or standalone) can be written with a set of macros
  8112. // for the various SFI requirements like register masking. The assembly tool
  8113. // inserts the file containing the macros as an input into all the assembly
  8114. // jobs.
  8115. void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
  8116. const InputInfo &Output,
  8117. const InputInfoList &Inputs,
  8118. const ArgList &Args,
  8119. const char *LinkingOutput) const {
  8120. const toolchains::NaClToolChain &ToolChain =
  8121. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  8122. InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
  8123. "nacl-arm-macros.s");
  8124. InputInfoList NewInputs;
  8125. NewInputs.push_back(NaClMacros);
  8126. NewInputs.append(Inputs.begin(), Inputs.end());
  8127. gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
  8128. LinkingOutput);
  8129. }
  8130. // This is quite similar to gnutools::Linker::ConstructJob with changes that
  8131. // we use static by default, do not yet support sanitizers or LTO, and a few
  8132. // others. Eventually we can support more of that and hopefully migrate back
  8133. // to gnutools::Linker.
  8134. void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8135. const InputInfo &Output,
  8136. const InputInfoList &Inputs,
  8137. const ArgList &Args,
  8138. const char *LinkingOutput) const {
  8139. const toolchains::NaClToolChain &ToolChain =
  8140. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  8141. const Driver &D = ToolChain.getDriver();
  8142. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  8143. const bool IsStatic =
  8144. !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
  8145. ArgStringList CmdArgs;
  8146. // Silence warning for "clang -g foo.o -o foo"
  8147. Args.ClaimAllArgs(options::OPT_g_Group);
  8148. // and "clang -emit-llvm foo.o -o foo"
  8149. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8150. // and for "clang -w foo.o -o foo". Other warning options are already
  8151. // handled somewhere else.
  8152. Args.ClaimAllArgs(options::OPT_w);
  8153. if (!D.SysRoot.empty())
  8154. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8155. if (Args.hasArg(options::OPT_rdynamic))
  8156. CmdArgs.push_back("-export-dynamic");
  8157. if (Args.hasArg(options::OPT_s))
  8158. CmdArgs.push_back("-s");
  8159. // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
  8160. // from there is --build-id, which we do want.
  8161. CmdArgs.push_back("--build-id");
  8162. if (!IsStatic)
  8163. CmdArgs.push_back("--eh-frame-hdr");
  8164. CmdArgs.push_back("-m");
  8165. if (Arch == llvm::Triple::x86)
  8166. CmdArgs.push_back("elf_i386_nacl");
  8167. else if (Arch == llvm::Triple::arm)
  8168. CmdArgs.push_back("armelf_nacl");
  8169. else if (Arch == llvm::Triple::x86_64)
  8170. CmdArgs.push_back("elf_x86_64_nacl");
  8171. else if (Arch == llvm::Triple::mipsel)
  8172. CmdArgs.push_back("mipselelf_nacl");
  8173. else
  8174. D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
  8175. << "Native Client";
  8176. if (IsStatic)
  8177. CmdArgs.push_back("-static");
  8178. else if (Args.hasArg(options::OPT_shared))
  8179. CmdArgs.push_back("-shared");
  8180. CmdArgs.push_back("-o");
  8181. CmdArgs.push_back(Output.getFilename());
  8182. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8183. if (!Args.hasArg(options::OPT_shared))
  8184. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  8185. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  8186. const char *crtbegin;
  8187. if (IsStatic)
  8188. crtbegin = "crtbeginT.o";
  8189. else if (Args.hasArg(options::OPT_shared))
  8190. crtbegin = "crtbeginS.o";
  8191. else
  8192. crtbegin = "crtbegin.o";
  8193. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  8194. }
  8195. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8196. Args.AddAllArgs(CmdArgs, options::OPT_u);
  8197. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  8198. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  8199. CmdArgs.push_back("--no-demangle");
  8200. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  8201. if (D.CCCIsCXX() &&
  8202. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8203. bool OnlyLibstdcxxStatic =
  8204. Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
  8205. if (OnlyLibstdcxxStatic)
  8206. CmdArgs.push_back("-Bstatic");
  8207. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  8208. if (OnlyLibstdcxxStatic)
  8209. CmdArgs.push_back("-Bdynamic");
  8210. CmdArgs.push_back("-lm");
  8211. }
  8212. if (!Args.hasArg(options::OPT_nostdlib)) {
  8213. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8214. // Always use groups, since it has no effect on dynamic libraries.
  8215. CmdArgs.push_back("--start-group");
  8216. CmdArgs.push_back("-lc");
  8217. // NaCl's libc++ currently requires libpthread, so just always include it
  8218. // in the group for C++.
  8219. if (Args.hasArg(options::OPT_pthread) ||
  8220. Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
  8221. // Gold, used by Mips, handles nested groups differently than ld, and
  8222. // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
  8223. // which is not a desired behaviour here.
  8224. // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
  8225. if (getToolChain().getArch() == llvm::Triple::mipsel)
  8226. CmdArgs.push_back("-lnacl");
  8227. CmdArgs.push_back("-lpthread");
  8228. }
  8229. CmdArgs.push_back("-lgcc");
  8230. CmdArgs.push_back("--as-needed");
  8231. if (IsStatic)
  8232. CmdArgs.push_back("-lgcc_eh");
  8233. else
  8234. CmdArgs.push_back("-lgcc_s");
  8235. CmdArgs.push_back("--no-as-needed");
  8236. // Mips needs to create and use pnacl_legacy library that contains
  8237. // definitions from bitcode/pnaclmm.c and definitions for
  8238. // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
  8239. if (getToolChain().getArch() == llvm::Triple::mipsel)
  8240. CmdArgs.push_back("-lpnacl_legacy");
  8241. CmdArgs.push_back("--end-group");
  8242. }
  8243. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8244. const char *crtend;
  8245. if (Args.hasArg(options::OPT_shared))
  8246. crtend = "crtendS.o";
  8247. else
  8248. crtend = "crtend.o";
  8249. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  8250. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  8251. }
  8252. }
  8253. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  8254. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8255. }
  8256. void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8257. const InputInfo &Output,
  8258. const InputInfoList &Inputs,
  8259. const ArgList &Args,
  8260. const char *LinkingOutput) const {
  8261. claimNoWarnArgs(Args);
  8262. ArgStringList CmdArgs;
  8263. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8264. CmdArgs.push_back("-o");
  8265. CmdArgs.push_back(Output.getFilename());
  8266. for (const auto &II : Inputs)
  8267. CmdArgs.push_back(II.getFilename());
  8268. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8269. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8270. }
  8271. void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8272. const InputInfo &Output,
  8273. const InputInfoList &Inputs,
  8274. const ArgList &Args,
  8275. const char *LinkingOutput) const {
  8276. const Driver &D = getToolChain().getDriver();
  8277. ArgStringList CmdArgs;
  8278. if (Output.isFilename()) {
  8279. CmdArgs.push_back("-o");
  8280. CmdArgs.push_back(Output.getFilename());
  8281. } else {
  8282. assert(Output.isNothing() && "Invalid output.");
  8283. }
  8284. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8285. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  8286. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  8287. CmdArgs.push_back(
  8288. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  8289. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  8290. }
  8291. Args.AddAllArgs(CmdArgs,
  8292. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  8293. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8294. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8295. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8296. if (D.CCCIsCXX()) {
  8297. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  8298. CmdArgs.push_back("-lm");
  8299. }
  8300. }
  8301. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8302. if (Args.hasArg(options::OPT_pthread))
  8303. CmdArgs.push_back("-lpthread");
  8304. CmdArgs.push_back("-lc");
  8305. CmdArgs.push_back("-lCompilerRT-Generic");
  8306. CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
  8307. CmdArgs.push_back(
  8308. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  8309. }
  8310. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8311. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8312. }
  8313. /// DragonFly Tools
  8314. // For now, DragonFly Assemble does just about the same as for
  8315. // FreeBSD, but this may change soon.
  8316. void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8317. const InputInfo &Output,
  8318. const InputInfoList &Inputs,
  8319. const ArgList &Args,
  8320. const char *LinkingOutput) const {
  8321. claimNoWarnArgs(Args);
  8322. ArgStringList CmdArgs;
  8323. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  8324. // instruct as in the base system to assemble 32-bit code.
  8325. if (getToolChain().getArch() == llvm::Triple::x86)
  8326. CmdArgs.push_back("--32");
  8327. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8328. CmdArgs.push_back("-o");
  8329. CmdArgs.push_back(Output.getFilename());
  8330. for (const auto &II : Inputs)
  8331. CmdArgs.push_back(II.getFilename());
  8332. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8333. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8334. }
  8335. void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8336. const InputInfo &Output,
  8337. const InputInfoList &Inputs,
  8338. const ArgList &Args,
  8339. const char *LinkingOutput) const {
  8340. const Driver &D = getToolChain().getDriver();
  8341. ArgStringList CmdArgs;
  8342. if (!D.SysRoot.empty())
  8343. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8344. CmdArgs.push_back("--eh-frame-hdr");
  8345. if (Args.hasArg(options::OPT_static)) {
  8346. CmdArgs.push_back("-Bstatic");
  8347. } else {
  8348. if (Args.hasArg(options::OPT_rdynamic))
  8349. CmdArgs.push_back("-export-dynamic");
  8350. if (Args.hasArg(options::OPT_shared))
  8351. CmdArgs.push_back("-Bshareable");
  8352. else {
  8353. CmdArgs.push_back("-dynamic-linker");
  8354. CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
  8355. }
  8356. CmdArgs.push_back("--hash-style=gnu");
  8357. CmdArgs.push_back("--enable-new-dtags");
  8358. }
  8359. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  8360. // instruct ld in the base system to link 32-bit code.
  8361. if (getToolChain().getArch() == llvm::Triple::x86) {
  8362. CmdArgs.push_back("-m");
  8363. CmdArgs.push_back("elf_i386");
  8364. }
  8365. if (Output.isFilename()) {
  8366. CmdArgs.push_back("-o");
  8367. CmdArgs.push_back(Output.getFilename());
  8368. } else {
  8369. assert(Output.isNothing() && "Invalid output.");
  8370. }
  8371. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8372. if (!Args.hasArg(options::OPT_shared)) {
  8373. if (Args.hasArg(options::OPT_pg))
  8374. CmdArgs.push_back(
  8375. Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
  8376. else {
  8377. if (Args.hasArg(options::OPT_pie))
  8378. CmdArgs.push_back(
  8379. Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
  8380. else
  8381. CmdArgs.push_back(
  8382. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  8383. }
  8384. }
  8385. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  8386. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8387. CmdArgs.push_back(
  8388. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  8389. else
  8390. CmdArgs.push_back(
  8391. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  8392. }
  8393. Args.AddAllArgs(CmdArgs,
  8394. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  8395. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8396. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8397. CmdArgs.push_back("-L/usr/lib/gcc50");
  8398. if (!Args.hasArg(options::OPT_static)) {
  8399. CmdArgs.push_back("-rpath");
  8400. CmdArgs.push_back("/usr/lib/gcc50");
  8401. }
  8402. if (D.CCCIsCXX()) {
  8403. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  8404. CmdArgs.push_back("-lm");
  8405. }
  8406. if (Args.hasArg(options::OPT_pthread))
  8407. CmdArgs.push_back("-lpthread");
  8408. if (!Args.hasArg(options::OPT_nolibc)) {
  8409. CmdArgs.push_back("-lc");
  8410. }
  8411. if (Args.hasArg(options::OPT_static) ||
  8412. Args.hasArg(options::OPT_static_libgcc)) {
  8413. CmdArgs.push_back("-lgcc");
  8414. CmdArgs.push_back("-lgcc_eh");
  8415. } else {
  8416. if (Args.hasArg(options::OPT_shared_libgcc)) {
  8417. CmdArgs.push_back("-lgcc_pic");
  8418. if (!Args.hasArg(options::OPT_shared))
  8419. CmdArgs.push_back("-lgcc");
  8420. } else {
  8421. CmdArgs.push_back("-lgcc");
  8422. CmdArgs.push_back("--as-needed");
  8423. CmdArgs.push_back("-lgcc_pic");
  8424. CmdArgs.push_back("--no-as-needed");
  8425. }
  8426. }
  8427. }
  8428. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8429. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8430. CmdArgs.push_back(
  8431. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  8432. else
  8433. CmdArgs.push_back(
  8434. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  8435. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  8436. }
  8437. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8438. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8439. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8440. }
  8441. // Try to find Exe from a Visual Studio distribution. This first tries to find
  8442. // an installed copy of Visual Studio and, failing that, looks in the PATH,
  8443. // making sure that whatever executable that's found is not a same-named exe
  8444. // from clang itself to prevent clang from falling back to itself.
  8445. static std::string FindVisualStudioExecutable(const ToolChain &TC,
  8446. const char *Exe,
  8447. const char *ClangProgramPath) {
  8448. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  8449. std::string visualStudioBinDir;
  8450. if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
  8451. visualStudioBinDir)) {
  8452. SmallString<128> FilePath(visualStudioBinDir);
  8453. llvm::sys::path::append(FilePath, Exe);
  8454. if (llvm::sys::fs::can_execute(FilePath.c_str()))
  8455. return FilePath.str();
  8456. }
  8457. return Exe;
  8458. }
  8459. void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8460. const InputInfo &Output,
  8461. const InputInfoList &Inputs,
  8462. const ArgList &Args,
  8463. const char *LinkingOutput) const {
  8464. ArgStringList CmdArgs;
  8465. const ToolChain &TC = getToolChain();
  8466. assert((Output.isFilename() || Output.isNothing()) && "invalid output");
  8467. if (Output.isFilename())
  8468. CmdArgs.push_back(
  8469. Args.MakeArgString(std::string("-out:") + Output.getFilename()));
  8470. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
  8471. !C.getDriver().IsCLMode())
  8472. CmdArgs.push_back("-defaultlib:libcmt");
  8473. if (!llvm::sys::Process::GetEnv("LIB")) {
  8474. // If the VC environment hasn't been configured (perhaps because the user
  8475. // did not run vcvarsall), try to build a consistent link environment. If
  8476. // the environment variable is set however, assume the user knows what
  8477. // they're doing.
  8478. std::string VisualStudioDir;
  8479. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  8480. if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
  8481. SmallString<128> LibDir(VisualStudioDir);
  8482. llvm::sys::path::append(LibDir, "VC", "lib");
  8483. switch (MSVC.getArch()) {
  8484. case llvm::Triple::x86:
  8485. // x86 just puts the libraries directly in lib
  8486. break;
  8487. case llvm::Triple::x86_64:
  8488. llvm::sys::path::append(LibDir, "amd64");
  8489. break;
  8490. case llvm::Triple::arm:
  8491. llvm::sys::path::append(LibDir, "arm");
  8492. break;
  8493. default:
  8494. break;
  8495. }
  8496. CmdArgs.push_back(
  8497. Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
  8498. if (MSVC.useUniversalCRT(VisualStudioDir)) {
  8499. std::string UniversalCRTLibPath;
  8500. if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
  8501. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8502. UniversalCRTLibPath.c_str()));
  8503. }
  8504. }
  8505. std::string WindowsSdkLibPath;
  8506. if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
  8507. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8508. WindowsSdkLibPath.c_str()));
  8509. }
  8510. CmdArgs.push_back("-nologo");
  8511. if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
  8512. CmdArgs.push_back("-debug");
  8513. bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
  8514. options::OPT_shared);
  8515. if (DLL) {
  8516. CmdArgs.push_back(Args.MakeArgString("-dll"));
  8517. SmallString<128> ImplibName(Output.getFilename());
  8518. llvm::sys::path::replace_extension(ImplibName, "lib");
  8519. CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
  8520. }
  8521. if (TC.getSanitizerArgs().needsAsanRt()) {
  8522. CmdArgs.push_back(Args.MakeArgString("-debug"));
  8523. CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
  8524. if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
  8525. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  8526. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  8527. // Make sure the dynamic runtime thunk is not optimized out at link time
  8528. // to ensure proper SEH handling.
  8529. CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
  8530. } else if (DLL) {
  8531. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  8532. } else {
  8533. for (const auto &Lib : {"asan", "asan_cxx"})
  8534. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  8535. }
  8536. }
  8537. Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
  8538. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  8539. options::OPT_fno_openmp, false)) {
  8540. CmdArgs.push_back("-nodefaultlib:vcomp.lib");
  8541. CmdArgs.push_back("-nodefaultlib:vcompd.lib");
  8542. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8543. TC.getDriver().Dir + "/../lib"));
  8544. switch (getOpenMPRuntime(getToolChain(), Args)) {
  8545. case OMPRT_OMP:
  8546. CmdArgs.push_back("-defaultlib:libomp.lib");
  8547. break;
  8548. case OMPRT_IOMP5:
  8549. CmdArgs.push_back("-defaultlib:libiomp5md.lib");
  8550. break;
  8551. case OMPRT_GOMP:
  8552. break;
  8553. case OMPRT_Unknown:
  8554. // Already diagnosed.
  8555. break;
  8556. }
  8557. }
  8558. // Add compiler-rt lib in case if it was explicitly
  8559. // specified as an argument for --rtlib option.
  8560. if (!Args.hasArg(options::OPT_nostdlib)) {
  8561. AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
  8562. }
  8563. // Add filenames, libraries, and other linker inputs.
  8564. for (const auto &Input : Inputs) {
  8565. if (Input.isFilename()) {
  8566. CmdArgs.push_back(Input.getFilename());
  8567. continue;
  8568. }
  8569. const Arg &A = Input.getInputArg();
  8570. // Render -l options differently for the MSVC linker.
  8571. if (A.getOption().matches(options::OPT_l)) {
  8572. StringRef Lib = A.getValue();
  8573. const char *LinkLibArg;
  8574. if (Lib.endswith(".lib"))
  8575. LinkLibArg = Args.MakeArgString(Lib);
  8576. else
  8577. LinkLibArg = Args.MakeArgString(Lib + ".lib");
  8578. CmdArgs.push_back(LinkLibArg);
  8579. continue;
  8580. }
  8581. // Otherwise, this is some other kind of linker input option like -Wl, -z,
  8582. // or -L. Render it, even if MSVC doesn't understand it.
  8583. A.renderAsInput(Args, CmdArgs);
  8584. }
  8585. TC.addProfileRTLibs(Args, CmdArgs);
  8586. // We need to special case some linker paths. In the case of lld, we need to
  8587. // translate 'lld' into 'lld-link', and in the case of the regular msvc
  8588. // linker, we need to use a special search algorithm.
  8589. llvm::SmallString<128> linkPath;
  8590. StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
  8591. if (Linker.equals_lower("lld"))
  8592. Linker = "lld-link";
  8593. if (Linker.equals_lower("link")) {
  8594. // If we're using the MSVC linker, it's not sufficient to just use link
  8595. // from the program PATH, because other environments like GnuWin32 install
  8596. // their own link.exe which may come first.
  8597. linkPath = FindVisualStudioExecutable(TC, "link.exe",
  8598. C.getDriver().getClangProgramPath());
  8599. } else {
  8600. linkPath = Linker;
  8601. llvm::sys::path::replace_extension(linkPath, "exe");
  8602. linkPath = TC.GetProgramPath(linkPath.c_str());
  8603. }
  8604. const char *Exec = Args.MakeArgString(linkPath);
  8605. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8606. }
  8607. void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  8608. const InputInfo &Output,
  8609. const InputInfoList &Inputs,
  8610. const ArgList &Args,
  8611. const char *LinkingOutput) const {
  8612. C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
  8613. }
  8614. std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
  8615. Compilation &C, const JobAction &JA, const InputInfo &Output,
  8616. const InputInfoList &Inputs, const ArgList &Args,
  8617. const char *LinkingOutput) const {
  8618. ArgStringList CmdArgs;
  8619. CmdArgs.push_back("/nologo");
  8620. CmdArgs.push_back("/c"); // Compile only.
  8621. CmdArgs.push_back("/W0"); // No warnings.
  8622. // The goal is to be able to invoke this tool correctly based on
  8623. // any flag accepted by clang-cl.
  8624. // These are spelled the same way in clang and cl.exe,.
  8625. Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
  8626. // Optimization level.
  8627. if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
  8628. CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
  8629. : "/Oi-");
  8630. if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
  8631. if (A->getOption().getID() == options::OPT_O0) {
  8632. CmdArgs.push_back("/Od");
  8633. } else {
  8634. CmdArgs.push_back("/Og");
  8635. StringRef OptLevel = A->getValue();
  8636. if (OptLevel == "s" || OptLevel == "z")
  8637. CmdArgs.push_back("/Os");
  8638. else
  8639. CmdArgs.push_back("/Ot");
  8640. CmdArgs.push_back("/Ob2");
  8641. }
  8642. }
  8643. if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
  8644. options::OPT_fno_omit_frame_pointer))
  8645. CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
  8646. ? "/Oy"
  8647. : "/Oy-");
  8648. if (!Args.hasArg(options::OPT_fwritable_strings))
  8649. CmdArgs.push_back("/GF");
  8650. // Flags for which clang-cl has an alias.
  8651. // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
  8652. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  8653. /*default=*/false))
  8654. CmdArgs.push_back("/GR-");
  8655. if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
  8656. options::OPT_fno_function_sections))
  8657. CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
  8658. ? "/Gy"
  8659. : "/Gy-");
  8660. if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
  8661. options::OPT_fno_data_sections))
  8662. CmdArgs.push_back(
  8663. A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
  8664. if (Args.hasArg(options::OPT_fsyntax_only))
  8665. CmdArgs.push_back("/Zs");
  8666. if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
  8667. options::OPT__SLASH_Z7))
  8668. CmdArgs.push_back("/Z7");
  8669. std::vector<std::string> Includes =
  8670. Args.getAllArgValues(options::OPT_include);
  8671. for (const auto &Include : Includes)
  8672. CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
  8673. // Flags that can simply be passed through.
  8674. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
  8675. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
  8676. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
  8677. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
  8678. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
  8679. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
  8680. // The order of these flags is relevant, so pick the last one.
  8681. if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
  8682. options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
  8683. A->render(Args, CmdArgs);
  8684. // Pass through all unknown arguments so that the fallback command can see
  8685. // them too.
  8686. Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
  8687. // Input filename.
  8688. assert(Inputs.size() == 1);
  8689. const InputInfo &II = Inputs[0];
  8690. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
  8691. CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
  8692. if (II.isFilename())
  8693. CmdArgs.push_back(II.getFilename());
  8694. else
  8695. II.getInputArg().renderAsInput(Args, CmdArgs);
  8696. // Output filename.
  8697. assert(Output.getType() == types::TY_Object);
  8698. const char *Fo =
  8699. Args.MakeArgString(std::string("/Fo") + Output.getFilename());
  8700. CmdArgs.push_back(Fo);
  8701. const Driver &D = getToolChain().getDriver();
  8702. std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
  8703. D.getClangProgramPath());
  8704. return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8705. CmdArgs, Inputs);
  8706. }
  8707. /// MinGW Tools
  8708. void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8709. const InputInfo &Output,
  8710. const InputInfoList &Inputs,
  8711. const ArgList &Args,
  8712. const char *LinkingOutput) const {
  8713. claimNoWarnArgs(Args);
  8714. ArgStringList CmdArgs;
  8715. if (getToolChain().getArch() == llvm::Triple::x86) {
  8716. CmdArgs.push_back("--32");
  8717. } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
  8718. CmdArgs.push_back("--64");
  8719. }
  8720. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8721. CmdArgs.push_back("-o");
  8722. CmdArgs.push_back(Output.getFilename());
  8723. for (const auto &II : Inputs)
  8724. CmdArgs.push_back(II.getFilename());
  8725. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8726. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8727. if (Args.hasArg(options::OPT_gsplit_dwarf))
  8728. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  8729. SplitDebugName(Args, Inputs[0]));
  8730. }
  8731. void MinGW::Linker::AddLibGCC(const ArgList &Args,
  8732. ArgStringList &CmdArgs) const {
  8733. if (Args.hasArg(options::OPT_mthreads))
  8734. CmdArgs.push_back("-lmingwthrd");
  8735. CmdArgs.push_back("-lmingw32");
  8736. // Make use of compiler-rt if --rtlib option is used
  8737. ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
  8738. if (RLT == ToolChain::RLT_Libgcc) {
  8739. bool Static = Args.hasArg(options::OPT_static_libgcc) ||
  8740. Args.hasArg(options::OPT_static);
  8741. bool Shared = Args.hasArg(options::OPT_shared);
  8742. bool CXX = getToolChain().getDriver().CCCIsCXX();
  8743. if (Static || (!CXX && !Shared)) {
  8744. CmdArgs.push_back("-lgcc");
  8745. CmdArgs.push_back("-lgcc_eh");
  8746. } else {
  8747. CmdArgs.push_back("-lgcc_s");
  8748. CmdArgs.push_back("-lgcc");
  8749. }
  8750. } else {
  8751. AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
  8752. }
  8753. CmdArgs.push_back("-lmoldname");
  8754. CmdArgs.push_back("-lmingwex");
  8755. CmdArgs.push_back("-lmsvcrt");
  8756. }
  8757. void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8758. const InputInfo &Output,
  8759. const InputInfoList &Inputs,
  8760. const ArgList &Args,
  8761. const char *LinkingOutput) const {
  8762. const ToolChain &TC = getToolChain();
  8763. const Driver &D = TC.getDriver();
  8764. // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
  8765. ArgStringList CmdArgs;
  8766. // Silence warning for "clang -g foo.o -o foo"
  8767. Args.ClaimAllArgs(options::OPT_g_Group);
  8768. // and "clang -emit-llvm foo.o -o foo"
  8769. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8770. // and for "clang -w foo.o -o foo". Other warning options are already
  8771. // handled somewhere else.
  8772. Args.ClaimAllArgs(options::OPT_w);
  8773. StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
  8774. if (LinkerName.equals_lower("lld")) {
  8775. CmdArgs.push_back("-flavor");
  8776. CmdArgs.push_back("gnu");
  8777. } else if (!LinkerName.equals_lower("ld")) {
  8778. D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
  8779. }
  8780. if (!D.SysRoot.empty())
  8781. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8782. if (Args.hasArg(options::OPT_s))
  8783. CmdArgs.push_back("-s");
  8784. CmdArgs.push_back("-m");
  8785. if (TC.getArch() == llvm::Triple::x86)
  8786. CmdArgs.push_back("i386pe");
  8787. if (TC.getArch() == llvm::Triple::x86_64)
  8788. CmdArgs.push_back("i386pep");
  8789. if (TC.getArch() == llvm::Triple::arm)
  8790. CmdArgs.push_back("thumb2pe");
  8791. if (Args.hasArg(options::OPT_mwindows)) {
  8792. CmdArgs.push_back("--subsystem");
  8793. CmdArgs.push_back("windows");
  8794. } else if (Args.hasArg(options::OPT_mconsole)) {
  8795. CmdArgs.push_back("--subsystem");
  8796. CmdArgs.push_back("console");
  8797. }
  8798. if (Args.hasArg(options::OPT_static))
  8799. CmdArgs.push_back("-Bstatic");
  8800. else {
  8801. if (Args.hasArg(options::OPT_mdll))
  8802. CmdArgs.push_back("--dll");
  8803. else if (Args.hasArg(options::OPT_shared))
  8804. CmdArgs.push_back("--shared");
  8805. CmdArgs.push_back("-Bdynamic");
  8806. if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
  8807. CmdArgs.push_back("-e");
  8808. if (TC.getArch() == llvm::Triple::x86)
  8809. CmdArgs.push_back("_DllMainCRTStartup@12");
  8810. else
  8811. CmdArgs.push_back("DllMainCRTStartup");
  8812. CmdArgs.push_back("--enable-auto-image-base");
  8813. }
  8814. }
  8815. CmdArgs.push_back("-o");
  8816. CmdArgs.push_back(Output.getFilename());
  8817. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8818. // FIXME: add -N, -n flags
  8819. Args.AddLastArg(CmdArgs, options::OPT_r);
  8820. Args.AddLastArg(CmdArgs, options::OPT_s);
  8821. Args.AddLastArg(CmdArgs, options::OPT_t);
  8822. Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
  8823. Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
  8824. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8825. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
  8826. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
  8827. } else {
  8828. if (Args.hasArg(options::OPT_municode))
  8829. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
  8830. else
  8831. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
  8832. }
  8833. if (Args.hasArg(options::OPT_pg))
  8834. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
  8835. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  8836. }
  8837. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8838. TC.AddFilePathLibArgs(Args, CmdArgs);
  8839. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  8840. // TODO: Add ASan stuff here
  8841. // TODO: Add profile stuff here
  8842. if (D.CCCIsCXX() &&
  8843. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8844. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  8845. !Args.hasArg(options::OPT_static);
  8846. if (OnlyLibstdcxxStatic)
  8847. CmdArgs.push_back("-Bstatic");
  8848. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  8849. if (OnlyLibstdcxxStatic)
  8850. CmdArgs.push_back("-Bdynamic");
  8851. }
  8852. if (!Args.hasArg(options::OPT_nostdlib)) {
  8853. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8854. if (Args.hasArg(options::OPT_static))
  8855. CmdArgs.push_back("--start-group");
  8856. if (Args.hasArg(options::OPT_fstack_protector) ||
  8857. Args.hasArg(options::OPT_fstack_protector_strong) ||
  8858. Args.hasArg(options::OPT_fstack_protector_all)) {
  8859. CmdArgs.push_back("-lssp_nonshared");
  8860. CmdArgs.push_back("-lssp");
  8861. }
  8862. if (Args.hasArg(options::OPT_fopenmp))
  8863. CmdArgs.push_back("-lgomp");
  8864. AddLibGCC(Args, CmdArgs);
  8865. if (Args.hasArg(options::OPT_pg))
  8866. CmdArgs.push_back("-lgmon");
  8867. if (Args.hasArg(options::OPT_pthread))
  8868. CmdArgs.push_back("-lpthread");
  8869. // add system libraries
  8870. if (Args.hasArg(options::OPT_mwindows)) {
  8871. CmdArgs.push_back("-lgdi32");
  8872. CmdArgs.push_back("-lcomdlg32");
  8873. }
  8874. CmdArgs.push_back("-ladvapi32");
  8875. CmdArgs.push_back("-lshell32");
  8876. CmdArgs.push_back("-luser32");
  8877. CmdArgs.push_back("-lkernel32");
  8878. if (Args.hasArg(options::OPT_static))
  8879. CmdArgs.push_back("--end-group");
  8880. else if (!LinkerName.equals_lower("lld"))
  8881. AddLibGCC(Args, CmdArgs);
  8882. }
  8883. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8884. // Add crtfastmath.o if available and fast math is enabled.
  8885. TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  8886. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  8887. }
  8888. }
  8889. const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
  8890. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8891. }
  8892. /// XCore Tools
  8893. // We pass assemble and link construction to the xcc tool.
  8894. void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8895. const InputInfo &Output,
  8896. const InputInfoList &Inputs,
  8897. const ArgList &Args,
  8898. const char *LinkingOutput) const {
  8899. claimNoWarnArgs(Args);
  8900. ArgStringList CmdArgs;
  8901. CmdArgs.push_back("-o");
  8902. CmdArgs.push_back(Output.getFilename());
  8903. CmdArgs.push_back("-c");
  8904. if (Args.hasArg(options::OPT_v))
  8905. CmdArgs.push_back("-v");
  8906. if (Arg *A = Args.getLastArg(options::OPT_g_Group))
  8907. if (!A->getOption().matches(options::OPT_g0))
  8908. CmdArgs.push_back("-g");
  8909. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  8910. false))
  8911. CmdArgs.push_back("-fverbose-asm");
  8912. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8913. for (const auto &II : Inputs)
  8914. CmdArgs.push_back(II.getFilename());
  8915. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8916. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8917. }
  8918. void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8919. const InputInfo &Output,
  8920. const InputInfoList &Inputs,
  8921. const ArgList &Args,
  8922. const char *LinkingOutput) const {
  8923. ArgStringList CmdArgs;
  8924. if (Output.isFilename()) {
  8925. CmdArgs.push_back("-o");
  8926. CmdArgs.push_back(Output.getFilename());
  8927. } else {
  8928. assert(Output.isNothing() && "Invalid output.");
  8929. }
  8930. if (Args.hasArg(options::OPT_v))
  8931. CmdArgs.push_back("-v");
  8932. // Pass -fexceptions through to the linker if it was present.
  8933. if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  8934. false))
  8935. CmdArgs.push_back("-fexceptions");
  8936. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8937. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8938. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8939. }
  8940. void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8941. const InputInfo &Output,
  8942. const InputInfoList &Inputs,
  8943. const ArgList &Args,
  8944. const char *LinkingOutput) const {
  8945. claimNoWarnArgs(Args);
  8946. const auto &TC =
  8947. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  8948. ArgStringList CmdArgs;
  8949. const char *Exec;
  8950. switch (TC.getArch()) {
  8951. default:
  8952. llvm_unreachable("unsupported architecture");
  8953. case llvm::Triple::arm:
  8954. case llvm::Triple::thumb:
  8955. break;
  8956. case llvm::Triple::x86:
  8957. CmdArgs.push_back("--32");
  8958. break;
  8959. case llvm::Triple::x86_64:
  8960. CmdArgs.push_back("--64");
  8961. break;
  8962. }
  8963. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8964. CmdArgs.push_back("-o");
  8965. CmdArgs.push_back(Output.getFilename());
  8966. for (const auto &Input : Inputs)
  8967. CmdArgs.push_back(Input.getFilename());
  8968. const std::string Assembler = TC.GetProgramPath("as");
  8969. Exec = Args.MakeArgString(Assembler);
  8970. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8971. }
  8972. void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8973. const InputInfo &Output,
  8974. const InputInfoList &Inputs,
  8975. const ArgList &Args,
  8976. const char *LinkingOutput) const {
  8977. const auto &TC =
  8978. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  8979. const llvm::Triple &T = TC.getTriple();
  8980. const Driver &D = TC.getDriver();
  8981. SmallString<128> EntryPoint;
  8982. ArgStringList CmdArgs;
  8983. const char *Exec;
  8984. // Silence warning for "clang -g foo.o -o foo"
  8985. Args.ClaimAllArgs(options::OPT_g_Group);
  8986. // and "clang -emit-llvm foo.o -o foo"
  8987. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8988. // and for "clang -w foo.o -o foo"
  8989. Args.ClaimAllArgs(options::OPT_w);
  8990. // Other warning options are already handled somewhere else.
  8991. if (!D.SysRoot.empty())
  8992. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8993. if (Args.hasArg(options::OPT_pie))
  8994. CmdArgs.push_back("-pie");
  8995. if (Args.hasArg(options::OPT_rdynamic))
  8996. CmdArgs.push_back("-export-dynamic");
  8997. if (Args.hasArg(options::OPT_s))
  8998. CmdArgs.push_back("--strip-all");
  8999. CmdArgs.push_back("-m");
  9000. switch (TC.getArch()) {
  9001. default:
  9002. llvm_unreachable("unsupported architecture");
  9003. case llvm::Triple::arm:
  9004. case llvm::Triple::thumb:
  9005. // FIXME: this is incorrect for WinCE
  9006. CmdArgs.push_back("thumb2pe");
  9007. break;
  9008. case llvm::Triple::x86:
  9009. CmdArgs.push_back("i386pe");
  9010. EntryPoint.append("_");
  9011. break;
  9012. case llvm::Triple::x86_64:
  9013. CmdArgs.push_back("i386pep");
  9014. break;
  9015. }
  9016. if (Args.hasArg(options::OPT_shared)) {
  9017. switch (T.getArch()) {
  9018. default:
  9019. llvm_unreachable("unsupported architecture");
  9020. case llvm::Triple::arm:
  9021. case llvm::Triple::thumb:
  9022. case llvm::Triple::x86_64:
  9023. EntryPoint.append("_DllMainCRTStartup");
  9024. break;
  9025. case llvm::Triple::x86:
  9026. EntryPoint.append("_DllMainCRTStartup@12");
  9027. break;
  9028. }
  9029. CmdArgs.push_back("-shared");
  9030. CmdArgs.push_back("-Bdynamic");
  9031. CmdArgs.push_back("--enable-auto-image-base");
  9032. CmdArgs.push_back("--entry");
  9033. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  9034. } else {
  9035. EntryPoint.append("mainCRTStartup");
  9036. CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
  9037. : "-Bdynamic");
  9038. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9039. CmdArgs.push_back("--entry");
  9040. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  9041. }
  9042. // FIXME: handle subsystem
  9043. }
  9044. // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
  9045. CmdArgs.push_back("--allow-multiple-definition");
  9046. CmdArgs.push_back("-o");
  9047. CmdArgs.push_back(Output.getFilename());
  9048. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
  9049. SmallString<261> ImpLib(Output.getFilename());
  9050. llvm::sys::path::replace_extension(ImpLib, ".lib");
  9051. CmdArgs.push_back("--out-implib");
  9052. CmdArgs.push_back(Args.MakeArgString(ImpLib));
  9053. }
  9054. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9055. const std::string CRTPath(D.SysRoot + "/usr/lib/");
  9056. const char *CRTBegin;
  9057. CRTBegin =
  9058. Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
  9059. CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
  9060. }
  9061. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9062. TC.AddFilePathLibArgs(Args, CmdArgs);
  9063. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  9064. if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
  9065. !Args.hasArg(options::OPT_nodefaultlibs)) {
  9066. bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
  9067. !Args.hasArg(options::OPT_static);
  9068. if (StaticCXX)
  9069. CmdArgs.push_back("-Bstatic");
  9070. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  9071. if (StaticCXX)
  9072. CmdArgs.push_back("-Bdynamic");
  9073. }
  9074. if (!Args.hasArg(options::OPT_nostdlib)) {
  9075. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  9076. // TODO handle /MT[d] /MD[d]
  9077. CmdArgs.push_back("-lmsvcrt");
  9078. AddRunTimeLibs(TC, D, CmdArgs, Args);
  9079. }
  9080. }
  9081. if (TC.getSanitizerArgs().needsAsanRt()) {
  9082. // TODO handle /MT[d] /MD[d]
  9083. if (Args.hasArg(options::OPT_shared)) {
  9084. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  9085. } else {
  9086. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  9087. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  9088. // Make sure the dynamic runtime thunk is not optimized out at link time
  9089. // to ensure proper SEH handling.
  9090. CmdArgs.push_back(Args.MakeArgString("--undefined"));
  9091. CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
  9092. ? "___asan_seh_interceptor"
  9093. : "__asan_seh_interceptor"));
  9094. }
  9095. }
  9096. Exec = Args.MakeArgString(TC.GetLinkerPath());
  9097. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9098. }
  9099. void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  9100. const InputInfo &Output,
  9101. const InputInfoList &Inputs,
  9102. const ArgList &Args,
  9103. const char *LinkingOutput) const {
  9104. ArgStringList CmdArgs;
  9105. assert(Inputs.size() == 1);
  9106. const InputInfo &II = Inputs[0];
  9107. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
  9108. II.getType() == types::TY_PP_CXX);
  9109. if (JA.getKind() == Action::PreprocessJobClass) {
  9110. Args.ClaimAllArgs();
  9111. CmdArgs.push_back("-E");
  9112. } else {
  9113. assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
  9114. CmdArgs.push_back("-S");
  9115. CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
  9116. }
  9117. CmdArgs.push_back("-DMYRIAD2");
  9118. // Append all -I, -iquote, -isystem paths, defines/undefines,
  9119. // 'f' flags, optimize flags, and warning options.
  9120. // These are spelled the same way in clang and moviCompile.
  9121. Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
  9122. options::OPT_std_EQ, options::OPT_D, options::OPT_U,
  9123. options::OPT_f_Group, options::OPT_f_clang_Group,
  9124. options::OPT_g_Group, options::OPT_M_Group,
  9125. options::OPT_O_Group, options::OPT_W_Group,
  9126. options::OPT_mcpu_EQ});
  9127. // If we're producing a dependency file, and assembly is the final action,
  9128. // then the name of the target in the dependency file should be the '.o'
  9129. // file, not the '.s' file produced by this step. For example, instead of
  9130. // /tmp/mumble.s: mumble.c .../someheader.h
  9131. // the filename on the lefthand side should be "mumble.o"
  9132. if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
  9133. C.getActions().size() == 1 &&
  9134. C.getActions()[0]->getKind() == Action::AssembleJobClass) {
  9135. Arg *A = Args.getLastArg(options::OPT_o);
  9136. if (A) {
  9137. CmdArgs.push_back("-MT");
  9138. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  9139. }
  9140. }
  9141. CmdArgs.push_back(II.getFilename());
  9142. CmdArgs.push_back("-o");
  9143. CmdArgs.push_back(Output.getFilename());
  9144. std::string Exec =
  9145. Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
  9146. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9147. CmdArgs, Inputs));
  9148. }
  9149. void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9150. const InputInfo &Output,
  9151. const InputInfoList &Inputs,
  9152. const ArgList &Args,
  9153. const char *LinkingOutput) const {
  9154. ArgStringList CmdArgs;
  9155. assert(Inputs.size() == 1);
  9156. const InputInfo &II = Inputs[0];
  9157. assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
  9158. assert(Output.getType() == types::TY_Object);
  9159. CmdArgs.push_back("-no6thSlotCompression");
  9160. const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  9161. if (CPUArg)
  9162. CmdArgs.push_back(
  9163. Args.MakeArgString("-cv:" + StringRef(CPUArg->getValue())));
  9164. CmdArgs.push_back("-noSPrefixing");
  9165. CmdArgs.push_back("-a"); // Mystery option.
  9166. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9167. for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
  9168. A->claim();
  9169. CmdArgs.push_back(
  9170. Args.MakeArgString(std::string("-i:") + A->getValue(0)));
  9171. }
  9172. CmdArgs.push_back("-elf"); // Output format.
  9173. CmdArgs.push_back(II.getFilename());
  9174. CmdArgs.push_back(
  9175. Args.MakeArgString(std::string("-o:") + Output.getFilename()));
  9176. std::string Exec =
  9177. Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
  9178. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9179. CmdArgs, Inputs));
  9180. }
  9181. void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9182. const InputInfo &Output,
  9183. const InputInfoList &Inputs,
  9184. const ArgList &Args,
  9185. const char *LinkingOutput) const {
  9186. const auto &TC =
  9187. static_cast<const toolchains::MyriadToolChain &>(getToolChain());
  9188. const llvm::Triple &T = TC.getTriple();
  9189. ArgStringList CmdArgs;
  9190. bool UseStartfiles =
  9191. !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
  9192. bool UseDefaultLibs =
  9193. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
  9194. if (T.getArch() == llvm::Triple::sparc)
  9195. CmdArgs.push_back("-EB");
  9196. else // SHAVE assumes little-endian, and sparcel is expressly so.
  9197. CmdArgs.push_back("-EL");
  9198. // The remaining logic is mostly like gnutools::Linker::ConstructJob,
  9199. // but we never pass through a --sysroot option and various other bits.
  9200. // For example, there are no sanitizers (yet) nor gold linker.
  9201. // Eat some arguments that may be present but have no effect.
  9202. Args.ClaimAllArgs(options::OPT_g_Group);
  9203. Args.ClaimAllArgs(options::OPT_w);
  9204. Args.ClaimAllArgs(options::OPT_static_libgcc);
  9205. if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
  9206. CmdArgs.push_back("-s");
  9207. CmdArgs.push_back("-o");
  9208. CmdArgs.push_back(Output.getFilename());
  9209. if (UseStartfiles) {
  9210. // If you want startfiles, it means you want the builtin crti and crtbegin,
  9211. // but not crt0. Myriad link commands provide their own crt0.o as needed.
  9212. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
  9213. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  9214. }
  9215. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  9216. options::OPT_e, options::OPT_s, options::OPT_t,
  9217. options::OPT_Z_Flag, options::OPT_r});
  9218. TC.AddFilePathLibArgs(Args, CmdArgs);
  9219. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  9220. if (UseDefaultLibs) {
  9221. if (C.getDriver().CCCIsCXX())
  9222. CmdArgs.push_back("-lstdc++");
  9223. if (T.getOS() == llvm::Triple::RTEMS) {
  9224. CmdArgs.push_back("--start-group");
  9225. CmdArgs.push_back("-lc");
  9226. // You must provide your own "-L" option to enable finding these.
  9227. CmdArgs.push_back("-lrtemscpu");
  9228. CmdArgs.push_back("-lrtemsbsp");
  9229. CmdArgs.push_back("--end-group");
  9230. } else {
  9231. CmdArgs.push_back("-lc");
  9232. }
  9233. CmdArgs.push_back("-lgcc");
  9234. }
  9235. if (UseStartfiles) {
  9236. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  9237. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
  9238. }
  9239. std::string Exec =
  9240. Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
  9241. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9242. CmdArgs, Inputs));
  9243. }
  9244. void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
  9245. const InputInfo &Output,
  9246. const InputInfoList &Inputs,
  9247. const ArgList &Args,
  9248. const char *LinkingOutput) const {
  9249. claimNoWarnArgs(Args);
  9250. ArgStringList CmdArgs;
  9251. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9252. CmdArgs.push_back("-o");
  9253. CmdArgs.push_back(Output.getFilename());
  9254. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  9255. const InputInfo &Input = Inputs[0];
  9256. assert(Input.isFilename() && "Invalid input.");
  9257. CmdArgs.push_back(Input.getFilename());
  9258. const char *Exec =
  9259. Args.MakeArgString(getToolChain().GetProgramPath("ps4-as"));
  9260. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9261. }
  9262. static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
  9263. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  9264. if (SanArgs.needsUbsanRt()) {
  9265. CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
  9266. }
  9267. if (SanArgs.needsAsanRt()) {
  9268. CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
  9269. }
  9270. }
  9271. static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
  9272. const JobAction &JA, const InputInfo &Output,
  9273. const InputInfoList &Inputs,
  9274. const ArgList &Args,
  9275. const char *LinkingOutput) {
  9276. const toolchains::FreeBSD &ToolChain =
  9277. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  9278. const Driver &D = ToolChain.getDriver();
  9279. ArgStringList CmdArgs;
  9280. // Silence warning for "clang -g foo.o -o foo"
  9281. Args.ClaimAllArgs(options::OPT_g_Group);
  9282. // and "clang -emit-llvm foo.o -o foo"
  9283. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9284. // and for "clang -w foo.o -o foo". Other warning options are already
  9285. // handled somewhere else.
  9286. Args.ClaimAllArgs(options::OPT_w);
  9287. if (!D.SysRoot.empty())
  9288. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9289. if (Args.hasArg(options::OPT_pie))
  9290. CmdArgs.push_back("-pie");
  9291. if (Args.hasArg(options::OPT_rdynamic))
  9292. CmdArgs.push_back("-export-dynamic");
  9293. if (Args.hasArg(options::OPT_shared))
  9294. CmdArgs.push_back("--oformat=so");
  9295. if (Output.isFilename()) {
  9296. CmdArgs.push_back("-o");
  9297. CmdArgs.push_back(Output.getFilename());
  9298. } else {
  9299. assert(Output.isNothing() && "Invalid output.");
  9300. }
  9301. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  9302. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9303. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  9304. Args.AddAllArgs(CmdArgs, options::OPT_e);
  9305. Args.AddAllArgs(CmdArgs, options::OPT_s);
  9306. Args.AddAllArgs(CmdArgs, options::OPT_t);
  9307. Args.AddAllArgs(CmdArgs, options::OPT_r);
  9308. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  9309. CmdArgs.push_back("--no-demangle");
  9310. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  9311. if (Args.hasArg(options::OPT_pthread)) {
  9312. CmdArgs.push_back("-lpthread");
  9313. }
  9314. const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
  9315. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  9316. }
  9317. static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
  9318. const JobAction &JA, const InputInfo &Output,
  9319. const InputInfoList &Inputs,
  9320. const ArgList &Args,
  9321. const char *LinkingOutput) {
  9322. const toolchains::FreeBSD &ToolChain =
  9323. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  9324. const Driver &D = ToolChain.getDriver();
  9325. ArgStringList CmdArgs;
  9326. // Silence warning for "clang -g foo.o -o foo"
  9327. Args.ClaimAllArgs(options::OPT_g_Group);
  9328. // and "clang -emit-llvm foo.o -o foo"
  9329. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9330. // and for "clang -w foo.o -o foo". Other warning options are already
  9331. // handled somewhere else.
  9332. Args.ClaimAllArgs(options::OPT_w);
  9333. if (!D.SysRoot.empty())
  9334. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9335. if (Args.hasArg(options::OPT_pie))
  9336. CmdArgs.push_back("-pie");
  9337. if (Args.hasArg(options::OPT_static)) {
  9338. CmdArgs.push_back("-Bstatic");
  9339. } else {
  9340. if (Args.hasArg(options::OPT_rdynamic))
  9341. CmdArgs.push_back("-export-dynamic");
  9342. CmdArgs.push_back("--eh-frame-hdr");
  9343. if (Args.hasArg(options::OPT_shared)) {
  9344. CmdArgs.push_back("-Bshareable");
  9345. } else {
  9346. CmdArgs.push_back("-dynamic-linker");
  9347. CmdArgs.push_back("/libexec/ld-elf.so.1");
  9348. }
  9349. CmdArgs.push_back("--enable-new-dtags");
  9350. }
  9351. if (Output.isFilename()) {
  9352. CmdArgs.push_back("-o");
  9353. CmdArgs.push_back(Output.getFilename());
  9354. } else {
  9355. assert(Output.isNothing() && "Invalid output.");
  9356. }
  9357. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  9358. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9359. const char *crt1 = nullptr;
  9360. if (!Args.hasArg(options::OPT_shared)) {
  9361. if (Args.hasArg(options::OPT_pg))
  9362. crt1 = "gcrt1.o";
  9363. else if (Args.hasArg(options::OPT_pie))
  9364. crt1 = "Scrt1.o";
  9365. else
  9366. crt1 = "crt1.o";
  9367. }
  9368. if (crt1)
  9369. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  9370. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  9371. const char *crtbegin = nullptr;
  9372. if (Args.hasArg(options::OPT_static))
  9373. crtbegin = "crtbeginT.o";
  9374. else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  9375. crtbegin = "crtbeginS.o";
  9376. else
  9377. crtbegin = "crtbegin.o";
  9378. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  9379. }
  9380. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9381. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  9382. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  9383. Args.AddAllArgs(CmdArgs, options::OPT_e);
  9384. Args.AddAllArgs(CmdArgs, options::OPT_s);
  9385. Args.AddAllArgs(CmdArgs, options::OPT_t);
  9386. Args.AddAllArgs(CmdArgs, options::OPT_r);
  9387. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  9388. CmdArgs.push_back("--no-demangle");
  9389. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  9390. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  9391. // For PS4, we always want to pass libm, libstdc++ and libkernel
  9392. // libraries for both C and C++ compilations.
  9393. CmdArgs.push_back("-lkernel");
  9394. if (D.CCCIsCXX()) {
  9395. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  9396. if (Args.hasArg(options::OPT_pg))
  9397. CmdArgs.push_back("-lm_p");
  9398. else
  9399. CmdArgs.push_back("-lm");
  9400. }
  9401. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  9402. // the default system libraries. Just mimic this for now.
  9403. if (Args.hasArg(options::OPT_pg))
  9404. CmdArgs.push_back("-lgcc_p");
  9405. else
  9406. CmdArgs.push_back("-lcompiler_rt");
  9407. if (Args.hasArg(options::OPT_static)) {
  9408. CmdArgs.push_back("-lstdc++");
  9409. } else if (Args.hasArg(options::OPT_pg)) {
  9410. CmdArgs.push_back("-lgcc_eh_p");
  9411. } else {
  9412. CmdArgs.push_back("--as-needed");
  9413. CmdArgs.push_back("-lstdc++");
  9414. CmdArgs.push_back("--no-as-needed");
  9415. }
  9416. if (Args.hasArg(options::OPT_pthread)) {
  9417. if (Args.hasArg(options::OPT_pg))
  9418. CmdArgs.push_back("-lpthread_p");
  9419. else
  9420. CmdArgs.push_back("-lpthread");
  9421. }
  9422. if (Args.hasArg(options::OPT_pg)) {
  9423. if (Args.hasArg(options::OPT_shared))
  9424. CmdArgs.push_back("-lc");
  9425. else {
  9426. if (Args.hasArg(options::OPT_static)) {
  9427. CmdArgs.push_back("--start-group");
  9428. CmdArgs.push_back("-lc_p");
  9429. CmdArgs.push_back("-lpthread_p");
  9430. CmdArgs.push_back("--end-group");
  9431. } else {
  9432. CmdArgs.push_back("-lc_p");
  9433. }
  9434. }
  9435. CmdArgs.push_back("-lgcc_p");
  9436. } else {
  9437. if (Args.hasArg(options::OPT_static)) {
  9438. CmdArgs.push_back("--start-group");
  9439. CmdArgs.push_back("-lc");
  9440. CmdArgs.push_back("-lpthread");
  9441. CmdArgs.push_back("--end-group");
  9442. } else {
  9443. CmdArgs.push_back("-lc");
  9444. }
  9445. CmdArgs.push_back("-lcompiler_rt");
  9446. }
  9447. if (Args.hasArg(options::OPT_static)) {
  9448. CmdArgs.push_back("-lstdc++");
  9449. } else if (Args.hasArg(options::OPT_pg)) {
  9450. CmdArgs.push_back("-lgcc_eh_p");
  9451. } else {
  9452. CmdArgs.push_back("--as-needed");
  9453. CmdArgs.push_back("-lstdc++");
  9454. CmdArgs.push_back("--no-as-needed");
  9455. }
  9456. }
  9457. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9458. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  9459. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  9460. else
  9461. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  9462. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  9463. }
  9464. const char *Exec =
  9465. #ifdef LLVM_ON_WIN32
  9466. Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld.gold"));
  9467. #else
  9468. Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
  9469. #endif
  9470. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  9471. }
  9472. void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
  9473. const InputInfo &Output,
  9474. const InputInfoList &Inputs,
  9475. const ArgList &Args,
  9476. const char *LinkingOutput) const {
  9477. const toolchains::FreeBSD &ToolChain =
  9478. static_cast<const toolchains::FreeBSD &>(getToolChain());
  9479. const Driver &D = ToolChain.getDriver();
  9480. bool PS4Linker;
  9481. StringRef LinkerOptName;
  9482. if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
  9483. LinkerOptName = A->getValue();
  9484. if (LinkerOptName != "ps4" && LinkerOptName != "gold")
  9485. D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
  9486. }
  9487. if (LinkerOptName == "gold")
  9488. PS4Linker = false;
  9489. else if (LinkerOptName == "ps4")
  9490. PS4Linker = true;
  9491. else
  9492. PS4Linker = !Args.hasArg(options::OPT_shared);
  9493. if (PS4Linker)
  9494. ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  9495. else
  9496. ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  9497. }
  9498. void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9499. const InputInfo &Output,
  9500. const InputInfoList &Inputs,
  9501. const ArgList &Args,
  9502. const char *LinkingOutput) const {
  9503. const auto &TC =
  9504. static_cast<const toolchains::CudaToolChain &>(getToolChain());
  9505. assert(TC.getTriple().isNVPTX() && "Wrong platform");
  9506. std::vector<std::string> gpu_archs =
  9507. Args.getAllArgValues(options::OPT_march_EQ);
  9508. assert(gpu_archs.size() == 1 && "Exactly one GPU Arch required for ptxas.");
  9509. const std::string& gpu_arch = gpu_archs[0];
  9510. ArgStringList CmdArgs;
  9511. CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
  9512. if (Args.hasFlag(options::OPT_cuda_noopt_device_debug,
  9513. options::OPT_no_cuda_noopt_device_debug, false)) {
  9514. // ptxas does not accept -g option if optimization is enabled, so
  9515. // we ignore the compiler's -O* options if we want debug info.
  9516. CmdArgs.push_back("-g");
  9517. CmdArgs.push_back("--dont-merge-basicblocks");
  9518. CmdArgs.push_back("--return-at-end");
  9519. } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  9520. // Map the -O we received to -O{0,1,2,3}.
  9521. //
  9522. // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
  9523. // default, so it may correspond more closely to the spirit of clang -O2.
  9524. // -O3 seems like the least-bad option when -Osomething is specified to
  9525. // clang but it isn't handled below.
  9526. StringRef OOpt = "3";
  9527. if (A->getOption().matches(options::OPT_O4) ||
  9528. A->getOption().matches(options::OPT_Ofast))
  9529. OOpt = "3";
  9530. else if (A->getOption().matches(options::OPT_O0))
  9531. OOpt = "0";
  9532. else if (A->getOption().matches(options::OPT_O)) {
  9533. // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
  9534. OOpt = llvm::StringSwitch<const char *>(A->getValue())
  9535. .Case("1", "1")
  9536. .Case("2", "2")
  9537. .Case("3", "3")
  9538. .Case("s", "2")
  9539. .Case("z", "2")
  9540. .Default("2");
  9541. }
  9542. CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
  9543. } else {
  9544. // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
  9545. // to no optimizations, but ptxas's default is -O3.
  9546. CmdArgs.push_back("-O0");
  9547. }
  9548. CmdArgs.push_back("--gpu-name");
  9549. CmdArgs.push_back(Args.MakeArgString(gpu_arch));
  9550. CmdArgs.push_back("--output-file");
  9551. CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
  9552. for (const auto& II : Inputs)
  9553. CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
  9554. for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
  9555. CmdArgs.push_back(Args.MakeArgString(A));
  9556. const char *Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
  9557. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9558. }
  9559. // All inputs to this linker must be from CudaDeviceActions, as we need to look
  9560. // at the Inputs' Actions in order to figure out which GPU architecture they
  9561. // correspond to.
  9562. void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9563. const InputInfo &Output,
  9564. const InputInfoList &Inputs,
  9565. const ArgList &Args,
  9566. const char *LinkingOutput) const {
  9567. const auto &TC =
  9568. static_cast<const toolchains::CudaToolChain &>(getToolChain());
  9569. assert(TC.getTriple().isNVPTX() && "Wrong platform");
  9570. ArgStringList CmdArgs;
  9571. CmdArgs.push_back("--cuda");
  9572. CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
  9573. CmdArgs.push_back(Args.MakeArgString("--create"));
  9574. CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
  9575. for (const auto& II : Inputs) {
  9576. auto* A = cast<const CudaDeviceAction>(II.getAction());
  9577. // We need to pass an Arch of the form "sm_XX" for cubin files and
  9578. // "compute_XX" for ptx.
  9579. const char *Arch = (II.getType() == types::TY_PP_Asm)
  9580. ? A->getComputeArchName()
  9581. : A->getGpuArchName();
  9582. CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
  9583. Arch + ",file=" + II.getFilename()));
  9584. }
  9585. for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
  9586. CmdArgs.push_back(Args.MakeArgString(A));
  9587. const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
  9588. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9589. }