Tools.cpp 359 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920
  1. //===--- Tools.cpp - Tools Implementations --------------------------------===//
  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. /// CheckPreprocessingOptions - Perform some validation of preprocessing
  52. /// arguments that is shared with gcc.
  53. static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
  54. if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
  55. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
  56. !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
  57. D.Diag(diag::err_drv_argument_only_allowed_with)
  58. << A->getBaseArg().getAsString(Args)
  59. << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
  60. }
  61. }
  62. }
  63. /// CheckCodeGenerationOptions - Perform some validation of code generation
  64. /// arguments that is shared with gcc.
  65. static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
  66. // In gcc, only ARM checks this, but it seems reasonable to check universally.
  67. if (Args.hasArg(options::OPT_static))
  68. if (const Arg *A =
  69. Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
  70. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  71. << "-static";
  72. }
  73. // Add backslashes to escape spaces and other backslashes.
  74. // This is used for the space-separated argument list specified with
  75. // the -dwarf-debug-flags option.
  76. static void EscapeSpacesAndBackslashes(const char *Arg,
  77. SmallVectorImpl<char> &Res) {
  78. for (; *Arg; ++Arg) {
  79. switch (*Arg) {
  80. default:
  81. break;
  82. case ' ':
  83. case '\\':
  84. Res.push_back('\\');
  85. break;
  86. }
  87. Res.push_back(*Arg);
  88. }
  89. }
  90. // Quote target names for inclusion in GNU Make dependency files.
  91. // Only the characters '$', '#', ' ', '\t' are quoted.
  92. static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
  93. for (unsigned i = 0, e = Target.size(); i != e; ++i) {
  94. switch (Target[i]) {
  95. case ' ':
  96. case '\t':
  97. // Escape the preceding backslashes
  98. for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
  99. Res.push_back('\\');
  100. // Escape the space/tab
  101. Res.push_back('\\');
  102. break;
  103. case '$':
  104. Res.push_back('$');
  105. break;
  106. case '#':
  107. Res.push_back('\\');
  108. break;
  109. default:
  110. break;
  111. }
  112. Res.push_back(Target[i]);
  113. }
  114. }
  115. static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
  116. const char *ArgName, const char *EnvVar) {
  117. const char *DirList = ::getenv(EnvVar);
  118. bool CombinedArg = false;
  119. if (!DirList)
  120. return; // Nothing to do.
  121. StringRef Name(ArgName);
  122. if (Name.equals("-I") || Name.equals("-L"))
  123. CombinedArg = true;
  124. StringRef Dirs(DirList);
  125. if (Dirs.empty()) // Empty string should not add '.'.
  126. return;
  127. StringRef::size_type Delim;
  128. while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
  129. if (Delim == 0) { // Leading colon.
  130. if (CombinedArg) {
  131. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  132. } else {
  133. CmdArgs.push_back(ArgName);
  134. CmdArgs.push_back(".");
  135. }
  136. } else {
  137. if (CombinedArg) {
  138. CmdArgs.push_back(
  139. Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
  140. } else {
  141. CmdArgs.push_back(ArgName);
  142. CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
  143. }
  144. }
  145. Dirs = Dirs.substr(Delim + 1);
  146. }
  147. if (Dirs.empty()) { // Trailing colon.
  148. if (CombinedArg) {
  149. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  150. } else {
  151. CmdArgs.push_back(ArgName);
  152. CmdArgs.push_back(".");
  153. }
  154. } else { // Add the last path.
  155. if (CombinedArg) {
  156. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
  157. } else {
  158. CmdArgs.push_back(ArgName);
  159. CmdArgs.push_back(Args.MakeArgString(Dirs));
  160. }
  161. }
  162. }
  163. static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
  164. const ArgList &Args, ArgStringList &CmdArgs) {
  165. const Driver &D = TC.getDriver();
  166. // Add extra linker input arguments which are not treated as inputs
  167. // (constructed via -Xarch_).
  168. Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
  169. for (const auto &II : Inputs) {
  170. if (!TC.HasNativeLLVMSupport()) {
  171. // Don't try to pass LLVM inputs unless we have native support.
  172. if (II.getType() == types::TY_LLVM_IR ||
  173. II.getType() == types::TY_LTO_IR ||
  174. II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
  175. D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
  176. }
  177. // Add filenames immediately.
  178. if (II.isFilename()) {
  179. CmdArgs.push_back(II.getFilename());
  180. continue;
  181. }
  182. // Otherwise, this is a linker input argument.
  183. const Arg &A = II.getInputArg();
  184. // Handle reserved library options.
  185. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
  186. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  187. else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
  188. TC.AddCCKextLibArgs(Args, CmdArgs);
  189. else if (A.getOption().matches(options::OPT_z)) {
  190. // Pass -z prefix for gcc linker compatibility.
  191. A.claim();
  192. A.render(Args, CmdArgs);
  193. } else {
  194. A.renderAsInput(Args, CmdArgs);
  195. }
  196. }
  197. // LIBRARY_PATH - included following the user specified library paths.
  198. // and only supported on native toolchains.
  199. if (!TC.isCrossCompiling())
  200. addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
  201. }
  202. /// \brief Determine whether Objective-C automated reference counting is
  203. /// enabled.
  204. static bool isObjCAutoRefCount(const ArgList &Args) {
  205. return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
  206. }
  207. /// \brief Determine whether we are linking the ObjC runtime.
  208. static bool isObjCRuntimeLinked(const ArgList &Args) {
  209. if (isObjCAutoRefCount(Args)) {
  210. Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
  211. return true;
  212. }
  213. return Args.hasArg(options::OPT_fobjc_link_runtime);
  214. }
  215. static bool forwardToGCC(const Option &O) {
  216. // Don't forward inputs from the original command line. They are added from
  217. // InputInfoList.
  218. return O.getKind() != Option::InputClass &&
  219. !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
  220. }
  221. void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
  222. const Driver &D, const ArgList &Args,
  223. ArgStringList &CmdArgs,
  224. const InputInfo &Output,
  225. const InputInfoList &Inputs) const {
  226. Arg *A;
  227. CheckPreprocessingOptions(D, Args);
  228. Args.AddLastArg(CmdArgs, options::OPT_C);
  229. Args.AddLastArg(CmdArgs, options::OPT_CC);
  230. // Handle dependency file generation.
  231. if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
  232. (A = Args.getLastArg(options::OPT_MD)) ||
  233. (A = Args.getLastArg(options::OPT_MMD))) {
  234. // Determine the output location.
  235. const char *DepFile;
  236. if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
  237. DepFile = MF->getValue();
  238. C.addFailureResultFile(DepFile, &JA);
  239. } else if (Output.getType() == types::TY_Dependencies) {
  240. DepFile = Output.getFilename();
  241. } else if (A->getOption().matches(options::OPT_M) ||
  242. A->getOption().matches(options::OPT_MM)) {
  243. DepFile = "-";
  244. } else {
  245. DepFile = getDependencyFileName(Args, Inputs);
  246. C.addFailureResultFile(DepFile, &JA);
  247. }
  248. CmdArgs.push_back("-dependency-file");
  249. CmdArgs.push_back(DepFile);
  250. // Add a default target if one wasn't specified.
  251. if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
  252. const char *DepTarget;
  253. // If user provided -o, that is the dependency target, except
  254. // when we are only generating a dependency file.
  255. Arg *OutputOpt = Args.getLastArg(options::OPT_o);
  256. if (OutputOpt && Output.getType() != types::TY_Dependencies) {
  257. DepTarget = OutputOpt->getValue();
  258. } else {
  259. // Otherwise derive from the base input.
  260. //
  261. // FIXME: This should use the computed output file location.
  262. SmallString<128> P(Inputs[0].getBaseInput());
  263. llvm::sys::path::replace_extension(P, "o");
  264. DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
  265. }
  266. CmdArgs.push_back("-MT");
  267. SmallString<128> Quoted;
  268. QuoteTarget(DepTarget, Quoted);
  269. CmdArgs.push_back(Args.MakeArgString(Quoted));
  270. }
  271. if (A->getOption().matches(options::OPT_M) ||
  272. A->getOption().matches(options::OPT_MD))
  273. CmdArgs.push_back("-sys-header-deps");
  274. if ((isa<PrecompileJobAction>(JA) &&
  275. !Args.hasArg(options::OPT_fno_module_file_deps)) ||
  276. Args.hasArg(options::OPT_fmodule_file_deps))
  277. CmdArgs.push_back("-module-file-deps");
  278. }
  279. if (Args.hasArg(options::OPT_MG)) {
  280. if (!A || A->getOption().matches(options::OPT_MD) ||
  281. A->getOption().matches(options::OPT_MMD))
  282. D.Diag(diag::err_drv_mg_requires_m_or_mm);
  283. CmdArgs.push_back("-MG");
  284. }
  285. Args.AddLastArg(CmdArgs, options::OPT_MP);
  286. Args.AddLastArg(CmdArgs, options::OPT_MV);
  287. // Convert all -MQ <target> args to -MT <quoted target>
  288. for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
  289. A->claim();
  290. if (A->getOption().matches(options::OPT_MQ)) {
  291. CmdArgs.push_back("-MT");
  292. SmallString<128> Quoted;
  293. QuoteTarget(A->getValue(), Quoted);
  294. CmdArgs.push_back(Args.MakeArgString(Quoted));
  295. // -MT flag - no change
  296. } else {
  297. A->render(Args, CmdArgs);
  298. }
  299. }
  300. // Add -i* options, and automatically translate to
  301. // -include-pch/-include-pth for transparent PCH support. It's
  302. // wonky, but we include looking for .gch so we can support seamless
  303. // replacement into a build system already set up to be generating
  304. // .gch files.
  305. bool RenderedImplicitInclude = false;
  306. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  307. if (A->getOption().matches(options::OPT_include)) {
  308. bool IsFirstImplicitInclude = !RenderedImplicitInclude;
  309. RenderedImplicitInclude = true;
  310. // Use PCH if the user requested it.
  311. bool UsePCH = D.CCCUsePCH;
  312. bool FoundPTH = false;
  313. bool FoundPCH = false;
  314. SmallString<128> P(A->getValue());
  315. // We want the files to have a name like foo.h.pch. Add a dummy extension
  316. // so that replace_extension does the right thing.
  317. P += ".dummy";
  318. if (UsePCH) {
  319. llvm::sys::path::replace_extension(P, "pch");
  320. if (llvm::sys::fs::exists(P))
  321. FoundPCH = true;
  322. }
  323. if (!FoundPCH) {
  324. llvm::sys::path::replace_extension(P, "pth");
  325. if (llvm::sys::fs::exists(P))
  326. FoundPTH = true;
  327. }
  328. if (!FoundPCH && !FoundPTH) {
  329. llvm::sys::path::replace_extension(P, "gch");
  330. if (llvm::sys::fs::exists(P)) {
  331. FoundPCH = UsePCH;
  332. FoundPTH = !UsePCH;
  333. }
  334. }
  335. if (FoundPCH || FoundPTH) {
  336. if (IsFirstImplicitInclude) {
  337. A->claim();
  338. if (UsePCH)
  339. CmdArgs.push_back("-include-pch");
  340. else
  341. CmdArgs.push_back("-include-pth");
  342. CmdArgs.push_back(Args.MakeArgString(P));
  343. continue;
  344. } else {
  345. // Ignore the PCH if not first on command line and emit warning.
  346. D.Diag(diag::warn_drv_pch_not_first_include) << P
  347. << A->getAsString(Args);
  348. }
  349. }
  350. }
  351. // Not translated, render as usual.
  352. A->claim();
  353. A->render(Args, CmdArgs);
  354. }
  355. Args.AddAllArgs(CmdArgs,
  356. {options::OPT_D, options::OPT_U, options::OPT_I_Group,
  357. options::OPT_F, options::OPT_index_header_map});
  358. // Add -Wp, and -Xpreprocessor if using the preprocessor.
  359. // FIXME: There is a very unfortunate problem here, some troubled
  360. // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
  361. // really support that we would have to parse and then translate
  362. // those options. :(
  363. Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
  364. options::OPT_Xpreprocessor);
  365. // -I- is a deprecated GCC feature, reject it.
  366. if (Arg *A = Args.getLastArg(options::OPT_I_))
  367. D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
  368. // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
  369. // -isysroot to the CC1 invocation.
  370. StringRef sysroot = C.getSysRoot();
  371. if (sysroot != "") {
  372. if (!Args.hasArg(options::OPT_isysroot)) {
  373. CmdArgs.push_back("-isysroot");
  374. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  375. }
  376. }
  377. // Parse additional include paths from environment variables.
  378. // FIXME: We should probably sink the logic for handling these from the
  379. // frontend into the driver. It will allow deleting 4 otherwise unused flags.
  380. // CPATH - included following the user specified includes (but prior to
  381. // builtin and standard includes).
  382. addDirectoryList(Args, CmdArgs, "-I", "CPATH");
  383. // C_INCLUDE_PATH - system includes enabled when compiling C.
  384. addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
  385. // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
  386. addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
  387. // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
  388. addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
  389. // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
  390. addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
  391. // Add C++ include arguments, if needed.
  392. if (types::isCXX(Inputs[0].getType()))
  393. getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  394. // Add system include arguments.
  395. getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
  396. }
  397. // FIXME: Move to target hook.
  398. static bool isSignedCharDefault(const llvm::Triple &Triple) {
  399. switch (Triple.getArch()) {
  400. default:
  401. return true;
  402. case llvm::Triple::aarch64:
  403. case llvm::Triple::aarch64_be:
  404. case llvm::Triple::arm:
  405. case llvm::Triple::armeb:
  406. case llvm::Triple::thumb:
  407. case llvm::Triple::thumbeb:
  408. if (Triple.isOSDarwin() || Triple.isOSWindows())
  409. return true;
  410. return false;
  411. case llvm::Triple::ppc:
  412. case llvm::Triple::ppc64:
  413. if (Triple.isOSDarwin())
  414. return true;
  415. return false;
  416. case llvm::Triple::hexagon:
  417. case llvm::Triple::ppc64le:
  418. case llvm::Triple::systemz:
  419. case llvm::Triple::xcore:
  420. return false;
  421. }
  422. }
  423. static bool isNoCommonDefault(const llvm::Triple &Triple) {
  424. switch (Triple.getArch()) {
  425. default:
  426. return false;
  427. case llvm::Triple::xcore:
  428. case llvm::Triple::wasm32:
  429. case llvm::Triple::wasm64:
  430. return true;
  431. }
  432. }
  433. // ARM tools start.
  434. // Get SubArch (vN).
  435. static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
  436. llvm::StringRef Arch = Triple.getArchName();
  437. return llvm::ARM::parseArchVersion(Arch);
  438. }
  439. // True if M-profile.
  440. static bool isARMMProfile(const llvm::Triple &Triple) {
  441. llvm::StringRef Arch = Triple.getArchName();
  442. unsigned Profile = llvm::ARM::parseArchProfile(Arch);
  443. return Profile == llvm::ARM::PK_M;
  444. }
  445. // Get Arch/CPU from args.
  446. static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
  447. llvm::StringRef &CPU, bool FromAs = false) {
  448. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  449. CPU = A->getValue();
  450. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  451. Arch = A->getValue();
  452. if (!FromAs)
  453. return;
  454. for (const Arg *A :
  455. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  456. StringRef Value = A->getValue();
  457. if (Value.startswith("-mcpu="))
  458. CPU = Value.substr(6);
  459. if (Value.startswith("-march="))
  460. Arch = Value.substr(7);
  461. }
  462. }
  463. // Handle -mhwdiv=.
  464. // FIXME: Use ARMTargetParser.
  465. static void getARMHWDivFeatures(const Driver &D, const Arg *A,
  466. const ArgList &Args, StringRef HWDiv,
  467. std::vector<const char *> &Features) {
  468. unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
  469. if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
  470. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  471. }
  472. // Handle -mfpu=.
  473. static void getARMFPUFeatures(const Driver &D, const Arg *A,
  474. const ArgList &Args, StringRef FPU,
  475. std::vector<const char *> &Features) {
  476. unsigned FPUID = llvm::ARM::parseFPU(FPU);
  477. if (!llvm::ARM::getFPUFeatures(FPUID, Features))
  478. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  479. }
  480. // Check if -march is valid by checking if it can be canonicalised and parsed.
  481. // getARMArch is used here instead of just checking the -march value in order
  482. // to handle -march=native correctly.
  483. static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
  484. llvm::StringRef ArchName,
  485. const llvm::Triple &Triple) {
  486. std::string MArch = arm::getARMArch(ArchName, Triple);
  487. if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID)
  488. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  489. }
  490. // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
  491. static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
  492. llvm::StringRef CPUName, llvm::StringRef ArchName,
  493. const llvm::Triple &Triple) {
  494. std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
  495. if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty())
  496. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  497. }
  498. static bool useAAPCSForMachO(const llvm::Triple &T) {
  499. // The backend is hardwired to assume AAPCS for M-class processors, ensure
  500. // the frontend matches that.
  501. return T.getEnvironment() == llvm::Triple::EABI ||
  502. T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
  503. }
  504. // Select the float ABI as determined by -msoft-float, -mhard-float, and
  505. // -mfloat-abi=.
  506. arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
  507. const Driver &D = TC.getDriver();
  508. const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
  509. auto SubArch = getARMSubArchVersionNumber(Triple);
  510. arm::FloatABI ABI = FloatABI::Invalid;
  511. if (Arg *A =
  512. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  513. options::OPT_mfloat_abi_EQ)) {
  514. if (A->getOption().matches(options::OPT_msoft_float)) {
  515. ABI = FloatABI::Soft;
  516. } else if (A->getOption().matches(options::OPT_mhard_float)) {
  517. ABI = FloatABI::Hard;
  518. } else {
  519. ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
  520. .Case("soft", FloatABI::Soft)
  521. .Case("softfp", FloatABI::SoftFP)
  522. .Case("hard", FloatABI::Hard)
  523. .Default(FloatABI::Invalid);
  524. if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  525. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  526. ABI = FloatABI::Soft;
  527. }
  528. }
  529. // It is incorrect to select hard float ABI on MachO platforms if the ABI is
  530. // "apcs-gnu".
  531. if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
  532. ABI == FloatABI::Hard) {
  533. D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
  534. << Triple.getArchName();
  535. }
  536. }
  537. // If unspecified, choose the default based on the platform.
  538. if (ABI == FloatABI::Invalid) {
  539. switch (Triple.getOS()) {
  540. case llvm::Triple::Darwin:
  541. case llvm::Triple::MacOSX:
  542. case llvm::Triple::IOS: {
  543. // Darwin defaults to "softfp" for v6 and v7.
  544. ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  545. break;
  546. }
  547. // FIXME: this is invalid for WindowsCE
  548. case llvm::Triple::Win32:
  549. ABI = FloatABI::Hard;
  550. break;
  551. case llvm::Triple::FreeBSD:
  552. switch (Triple.getEnvironment()) {
  553. case llvm::Triple::GNUEABIHF:
  554. ABI = FloatABI::Hard;
  555. break;
  556. default:
  557. // FreeBSD defaults to soft float
  558. ABI = FloatABI::Soft;
  559. break;
  560. }
  561. break;
  562. default:
  563. switch (Triple.getEnvironment()) {
  564. case llvm::Triple::GNUEABIHF:
  565. case llvm::Triple::EABIHF:
  566. ABI = FloatABI::Hard;
  567. break;
  568. case llvm::Triple::GNUEABI:
  569. case llvm::Triple::EABI:
  570. // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
  571. ABI = FloatABI::SoftFP;
  572. break;
  573. case llvm::Triple::Android:
  574. ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  575. break;
  576. default:
  577. // Assume "soft", but warn the user we are guessing.
  578. ABI = FloatABI::Soft;
  579. if (Triple.getOS() != llvm::Triple::UnknownOS ||
  580. !Triple.isOSBinFormatMachO())
  581. D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
  582. break;
  583. }
  584. }
  585. }
  586. assert(ABI != FloatABI::Invalid && "must select an ABI");
  587. return ABI;
  588. }
  589. static void getARMTargetFeatures(const ToolChain &TC,
  590. const llvm::Triple &Triple,
  591. const ArgList &Args,
  592. std::vector<const char *> &Features,
  593. bool ForAS) {
  594. const Driver &D = TC.getDriver();
  595. bool KernelOrKext =
  596. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  597. arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
  598. const Arg *WaCPU = nullptr, *WaFPU = nullptr;
  599. const Arg *WaHDiv = nullptr, *WaArch = nullptr;
  600. if (!ForAS) {
  601. // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
  602. // yet (it uses the -mfloat-abi and -msoft-float options), and it is
  603. // stripped out by the ARM target. We should probably pass this a new
  604. // -target-option, which is handled by the -cc1/-cc1as invocation.
  605. //
  606. // FIXME2: For consistency, it would be ideal if we set up the target
  607. // machine state the same when using the frontend or the assembler. We don't
  608. // currently do that for the assembler, we pass the options directly to the
  609. // backend and never even instantiate the frontend TargetInfo. If we did,
  610. // and used its handleTargetFeatures hook, then we could ensure the
  611. // assembler and the frontend behave the same.
  612. // Use software floating point operations?
  613. if (ABI == arm::FloatABI::Soft)
  614. Features.push_back("+soft-float");
  615. // Use software floating point argument passing?
  616. if (ABI != arm::FloatABI::Hard)
  617. Features.push_back("+soft-float-abi");
  618. } else {
  619. // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
  620. // to the assembler correctly.
  621. for (const Arg *A :
  622. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  623. StringRef Value = A->getValue();
  624. if (Value.startswith("-mfpu=")) {
  625. WaFPU = A;
  626. } else if (Value.startswith("-mcpu=")) {
  627. WaCPU = A;
  628. } else if (Value.startswith("-mhwdiv=")) {
  629. WaHDiv = A;
  630. } else if (Value.startswith("-march=")) {
  631. WaArch = A;
  632. }
  633. }
  634. }
  635. // Check -march. ClangAs gives preference to -Wa,-march=.
  636. const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
  637. StringRef ArchName;
  638. if (WaArch) {
  639. if (ArchArg)
  640. D.Diag(clang::diag::warn_drv_unused_argument)
  641. << ArchArg->getAsString(Args);
  642. ArchName = StringRef(WaArch->getValue()).substr(7);
  643. checkARMArchName(D, WaArch, Args, ArchName, Triple);
  644. // FIXME: Set Arch.
  645. D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
  646. } else if (ArchArg) {
  647. ArchName = ArchArg->getValue();
  648. checkARMArchName(D, ArchArg, Args, ArchName, Triple);
  649. }
  650. // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
  651. const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  652. StringRef CPUName;
  653. if (WaCPU) {
  654. if (CPUArg)
  655. D.Diag(clang::diag::warn_drv_unused_argument)
  656. << CPUArg->getAsString(Args);
  657. CPUName = StringRef(WaCPU->getValue()).substr(6);
  658. checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Triple);
  659. } else if (CPUArg) {
  660. CPUName = CPUArg->getValue();
  661. checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Triple);
  662. }
  663. // Add CPU features for generic CPUs
  664. if (CPUName == "native") {
  665. llvm::StringMap<bool> HostFeatures;
  666. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  667. for (auto &F : HostFeatures)
  668. Features.push_back(
  669. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  670. }
  671. // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
  672. const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
  673. if (WaFPU) {
  674. if (FPUArg)
  675. D.Diag(clang::diag::warn_drv_unused_argument)
  676. << FPUArg->getAsString(Args);
  677. getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
  678. Features);
  679. } else if (FPUArg) {
  680. getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
  681. }
  682. // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
  683. const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
  684. if (WaHDiv) {
  685. if (HDivArg)
  686. D.Diag(clang::diag::warn_drv_unused_argument)
  687. << HDivArg->getAsString(Args);
  688. getARMHWDivFeatures(D, WaHDiv, Args,
  689. StringRef(WaHDiv->getValue()).substr(8), Features);
  690. } else if (HDivArg)
  691. getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
  692. // Setting -msoft-float effectively disables NEON because of the GCC
  693. // implementation, although the same isn't true of VFP or VFP3.
  694. if (ABI == arm::FloatABI::Soft) {
  695. Features.push_back("-neon");
  696. // Also need to explicitly disable features which imply NEON.
  697. Features.push_back("-crypto");
  698. }
  699. // En/disable crc code generation.
  700. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  701. if (A->getOption().matches(options::OPT_mcrc))
  702. Features.push_back("+crc");
  703. else
  704. Features.push_back("-crc");
  705. }
  706. if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
  707. Features.insert(Features.begin(), "+v8.1a");
  708. }
  709. // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
  710. // neither options are specified, see if we are compiling for kernel/kext and
  711. // decide whether to pass "+long-calls" based on the OS and its version.
  712. if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
  713. options::OPT_mno_long_calls)) {
  714. if (A->getOption().matches(options::OPT_mlong_calls))
  715. Features.push_back("+long-calls");
  716. } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6))) {
  717. Features.push_back("+long-calls");
  718. }
  719. // Kernel code has more strict alignment requirements.
  720. if (KernelOrKext)
  721. Features.push_back("+strict-align");
  722. else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  723. options::OPT_munaligned_access)) {
  724. if (A->getOption().matches(options::OPT_munaligned_access)) {
  725. // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
  726. if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  727. D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
  728. } else
  729. Features.push_back("+strict-align");
  730. } else {
  731. // Assume pre-ARMv6 doesn't support unaligned accesses.
  732. //
  733. // ARMv6 may or may not support unaligned accesses depending on the
  734. // SCTLR.U bit, which is architecture-specific. We assume ARMv6
  735. // Darwin and NetBSD targets support unaligned accesses, and others don't.
  736. //
  737. // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
  738. // which raises an alignment fault on unaligned accesses. Linux
  739. // defaults this bit to 0 and handles it as a system-wide (not
  740. // per-process) setting. It is therefore safe to assume that ARMv7+
  741. // Linux targets support unaligned accesses. The same goes for NaCl.
  742. //
  743. // The above behavior is consistent with GCC.
  744. int VersionNum = getARMSubArchVersionNumber(Triple);
  745. if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
  746. if (VersionNum < 6 ||
  747. Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  748. Features.push_back("+strict-align");
  749. } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
  750. if (VersionNum < 7)
  751. Features.push_back("+strict-align");
  752. } else
  753. Features.push_back("+strict-align");
  754. }
  755. // llvm does not support reserving registers in general. There is support
  756. // for reserving r9 on ARM though (defined as a platform-specific register
  757. // in ARM EABI).
  758. if (Args.hasArg(options::OPT_ffixed_r9))
  759. Features.push_back("+reserve-r9");
  760. // The kext linker doesn't know how to deal with movw/movt.
  761. if (KernelOrKext)
  762. Features.push_back("+no-movt");
  763. }
  764. void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
  765. ArgStringList &CmdArgs, bool KernelOrKext) const {
  766. // Select the ABI to use.
  767. // FIXME: Support -meabi.
  768. // FIXME: Parts of this are duplicated in the backend, unify this somehow.
  769. const char *ABIName = nullptr;
  770. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  771. ABIName = A->getValue();
  772. } else if (Triple.isOSBinFormatMachO()) {
  773. if (useAAPCSForMachO(Triple)) {
  774. ABIName = "aapcs";
  775. } else {
  776. ABIName = "apcs-gnu";
  777. }
  778. } else if (Triple.isOSWindows()) {
  779. // FIXME: this is invalid for WindowsCE
  780. ABIName = "aapcs";
  781. } else {
  782. // Select the default based on the platform.
  783. switch (Triple.getEnvironment()) {
  784. case llvm::Triple::Android:
  785. case llvm::Triple::GNUEABI:
  786. case llvm::Triple::GNUEABIHF:
  787. ABIName = "aapcs-linux";
  788. break;
  789. case llvm::Triple::EABIHF:
  790. case llvm::Triple::EABI:
  791. ABIName = "aapcs";
  792. break;
  793. default:
  794. if (Triple.getOS() == llvm::Triple::NetBSD)
  795. ABIName = "apcs-gnu";
  796. else
  797. ABIName = "aapcs";
  798. break;
  799. }
  800. }
  801. CmdArgs.push_back("-target-abi");
  802. CmdArgs.push_back(ABIName);
  803. // Determine floating point ABI from the options & target defaults.
  804. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  805. if (ABI == arm::FloatABI::Soft) {
  806. // Floating point operations and argument passing are soft.
  807. // FIXME: This changes CPP defines, we need -target-soft-float.
  808. CmdArgs.push_back("-msoft-float");
  809. CmdArgs.push_back("-mfloat-abi");
  810. CmdArgs.push_back("soft");
  811. } else if (ABI == arm::FloatABI::SoftFP) {
  812. // Floating point operations are hard, but argument passing is soft.
  813. CmdArgs.push_back("-mfloat-abi");
  814. CmdArgs.push_back("soft");
  815. } else {
  816. // Floating point operations and argument passing are hard.
  817. assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
  818. CmdArgs.push_back("-mfloat-abi");
  819. CmdArgs.push_back("hard");
  820. }
  821. // Forward the -mglobal-merge option for explicit control over the pass.
  822. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  823. options::OPT_mno_global_merge)) {
  824. CmdArgs.push_back("-backend-option");
  825. if (A->getOption().matches(options::OPT_mno_global_merge))
  826. CmdArgs.push_back("-arm-global-merge=false");
  827. else
  828. CmdArgs.push_back("-arm-global-merge=true");
  829. }
  830. if (!Args.hasFlag(options::OPT_mimplicit_float,
  831. options::OPT_mno_implicit_float, true))
  832. CmdArgs.push_back("-no-implicit-float");
  833. }
  834. // ARM tools end.
  835. /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
  836. /// targeting.
  837. static std::string getAArch64TargetCPU(const ArgList &Args) {
  838. Arg *A;
  839. std::string CPU;
  840. // If we have -mtune or -mcpu, use that.
  841. if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
  842. CPU = StringRef(A->getValue()).lower();
  843. } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
  844. StringRef Mcpu = A->getValue();
  845. CPU = Mcpu.split("+").first.lower();
  846. }
  847. // Handle CPU name is 'native'.
  848. if (CPU == "native")
  849. return llvm::sys::getHostCPUName();
  850. else if (CPU.size())
  851. return CPU;
  852. // Make sure we pick "cyclone" if -arch is used.
  853. // FIXME: Should this be picked by checking the target triple instead?
  854. if (Args.getLastArg(options::OPT_arch))
  855. return "cyclone";
  856. return "generic";
  857. }
  858. void Clang::AddAArch64TargetArgs(const ArgList &Args,
  859. ArgStringList &CmdArgs) const {
  860. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  861. llvm::Triple Triple(TripleStr);
  862. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  863. Args.hasArg(options::OPT_mkernel) ||
  864. Args.hasArg(options::OPT_fapple_kext))
  865. CmdArgs.push_back("-disable-red-zone");
  866. if (!Args.hasFlag(options::OPT_mimplicit_float,
  867. options::OPT_mno_implicit_float, true))
  868. CmdArgs.push_back("-no-implicit-float");
  869. const char *ABIName = nullptr;
  870. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  871. ABIName = A->getValue();
  872. else if (Triple.isOSDarwin())
  873. ABIName = "darwinpcs";
  874. else
  875. ABIName = "aapcs";
  876. CmdArgs.push_back("-target-abi");
  877. CmdArgs.push_back(ABIName);
  878. if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
  879. options::OPT_mno_fix_cortex_a53_835769)) {
  880. CmdArgs.push_back("-backend-option");
  881. if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
  882. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  883. else
  884. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
  885. } else if (Triple.isAndroid()) {
  886. // Enabled A53 errata (835769) workaround by default on android
  887. CmdArgs.push_back("-backend-option");
  888. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  889. }
  890. // Forward the -mglobal-merge option for explicit control over the pass.
  891. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  892. options::OPT_mno_global_merge)) {
  893. CmdArgs.push_back("-backend-option");
  894. if (A->getOption().matches(options::OPT_mno_global_merge))
  895. CmdArgs.push_back("-aarch64-global-merge=false");
  896. else
  897. CmdArgs.push_back("-aarch64-global-merge=true");
  898. }
  899. }
  900. // Get CPU and ABI names. They are not independent
  901. // so we have to calculate them together.
  902. void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
  903. StringRef &CPUName, StringRef &ABIName) {
  904. const char *DefMips32CPU = "mips32r2";
  905. const char *DefMips64CPU = "mips64r2";
  906. // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
  907. // default for mips64(el)?-img-linux-gnu.
  908. if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
  909. Triple.getEnvironment() == llvm::Triple::GNU) {
  910. DefMips32CPU = "mips32r6";
  911. DefMips64CPU = "mips64r6";
  912. }
  913. // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
  914. if (Triple.isAndroid())
  915. DefMips64CPU = "mips64r6";
  916. // MIPS3 is the default for mips64*-unknown-openbsd.
  917. if (Triple.getOS() == llvm::Triple::OpenBSD)
  918. DefMips64CPU = "mips3";
  919. if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
  920. CPUName = A->getValue();
  921. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  922. ABIName = A->getValue();
  923. // Convert a GNU style Mips ABI name to the name
  924. // accepted by LLVM Mips backend.
  925. ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
  926. .Case("32", "o32")
  927. .Case("64", "n64")
  928. .Default(ABIName);
  929. }
  930. // Setup default CPU and ABI names.
  931. if (CPUName.empty() && ABIName.empty()) {
  932. switch (Triple.getArch()) {
  933. default:
  934. llvm_unreachable("Unexpected triple arch name");
  935. case llvm::Triple::mips:
  936. case llvm::Triple::mipsel:
  937. CPUName = DefMips32CPU;
  938. break;
  939. case llvm::Triple::mips64:
  940. case llvm::Triple::mips64el:
  941. CPUName = DefMips64CPU;
  942. break;
  943. }
  944. }
  945. if (ABIName.empty()) {
  946. // Deduce ABI name from the target triple.
  947. if (Triple.getArch() == llvm::Triple::mips ||
  948. Triple.getArch() == llvm::Triple::mipsel)
  949. ABIName = "o32";
  950. else
  951. ABIName = "n64";
  952. }
  953. if (CPUName.empty()) {
  954. // Deduce CPU name from ABI name.
  955. CPUName = llvm::StringSwitch<const char *>(ABIName)
  956. .Cases("o32", "eabi", DefMips32CPU)
  957. .Cases("n32", "n64", DefMips64CPU)
  958. .Default("");
  959. }
  960. // FIXME: Warn on inconsistent use of -march and -mabi.
  961. }
  962. // Convert ABI name to the GNU tools acceptable variant.
  963. static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
  964. return llvm::StringSwitch<llvm::StringRef>(ABI)
  965. .Case("o32", "32")
  966. .Case("n64", "64")
  967. .Default(ABI);
  968. }
  969. // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
  970. // and -mfloat-abi=.
  971. static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
  972. mips::FloatABI ABI = mips::FloatABI::Invalid;
  973. if (Arg *A =
  974. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  975. options::OPT_mfloat_abi_EQ)) {
  976. if (A->getOption().matches(options::OPT_msoft_float))
  977. ABI = mips::FloatABI::Soft;
  978. else if (A->getOption().matches(options::OPT_mhard_float))
  979. ABI = mips::FloatABI::Hard;
  980. else {
  981. ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
  982. .Case("soft", mips::FloatABI::Soft)
  983. .Case("hard", mips::FloatABI::Hard)
  984. .Default(mips::FloatABI::Invalid);
  985. if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  986. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  987. ABI = mips::FloatABI::Hard;
  988. }
  989. }
  990. }
  991. // If unspecified, choose the default based on the platform.
  992. if (ABI == mips::FloatABI::Invalid) {
  993. // Assume "hard", because it's a default value used by gcc.
  994. // When we start to recognize specific target MIPS processors,
  995. // we will be able to select the default more correctly.
  996. ABI = mips::FloatABI::Hard;
  997. }
  998. assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
  999. return ABI;
  1000. }
  1001. static void AddTargetFeature(const ArgList &Args,
  1002. std::vector<const char *> &Features,
  1003. OptSpecifier OnOpt, OptSpecifier OffOpt,
  1004. StringRef FeatureName) {
  1005. if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
  1006. if (A->getOption().matches(OnOpt))
  1007. Features.push_back(Args.MakeArgString("+" + FeatureName));
  1008. else
  1009. Features.push_back(Args.MakeArgString("-" + FeatureName));
  1010. }
  1011. }
  1012. static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1013. const ArgList &Args,
  1014. std::vector<const char *> &Features) {
  1015. StringRef CPUName;
  1016. StringRef ABIName;
  1017. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1018. ABIName = getGnuCompatibleMipsABIName(ABIName);
  1019. AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
  1020. options::OPT_mabicalls, "noabicalls");
  1021. mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
  1022. if (FloatABI == mips::FloatABI::Soft) {
  1023. // FIXME: Note, this is a hack. We need to pass the selected float
  1024. // mode to the MipsTargetInfoBase to define appropriate macros there.
  1025. // Now it is the only method.
  1026. Features.push_back("+soft-float");
  1027. }
  1028. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  1029. StringRef Val = StringRef(A->getValue());
  1030. if (Val == "2008") {
  1031. if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
  1032. Features.push_back("+nan2008");
  1033. else {
  1034. Features.push_back("-nan2008");
  1035. D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
  1036. }
  1037. } else if (Val == "legacy") {
  1038. if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
  1039. Features.push_back("-nan2008");
  1040. else {
  1041. Features.push_back("+nan2008");
  1042. D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
  1043. }
  1044. } else
  1045. D.Diag(diag::err_drv_unsupported_option_argument)
  1046. << A->getOption().getName() << Val;
  1047. }
  1048. AddTargetFeature(Args, Features, options::OPT_msingle_float,
  1049. options::OPT_mdouble_float, "single-float");
  1050. AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
  1051. "mips16");
  1052. AddTargetFeature(Args, Features, options::OPT_mmicromips,
  1053. options::OPT_mno_micromips, "micromips");
  1054. AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
  1055. "dsp");
  1056. AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
  1057. "dspr2");
  1058. AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
  1059. "msa");
  1060. // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
  1061. // pass -mfpxx
  1062. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  1063. options::OPT_mfp64)) {
  1064. if (A->getOption().matches(options::OPT_mfp32))
  1065. Features.push_back(Args.MakeArgString("-fp64"));
  1066. else if (A->getOption().matches(options::OPT_mfpxx)) {
  1067. Features.push_back(Args.MakeArgString("+fpxx"));
  1068. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1069. } else
  1070. Features.push_back(Args.MakeArgString("+fp64"));
  1071. } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
  1072. Features.push_back(Args.MakeArgString("+fpxx"));
  1073. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1074. }
  1075. AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
  1076. options::OPT_modd_spreg, "nooddspreg");
  1077. }
  1078. void Clang::AddMIPSTargetArgs(const ArgList &Args,
  1079. ArgStringList &CmdArgs) const {
  1080. const Driver &D = getToolChain().getDriver();
  1081. StringRef CPUName;
  1082. StringRef ABIName;
  1083. const llvm::Triple &Triple = getToolChain().getTriple();
  1084. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1085. CmdArgs.push_back("-target-abi");
  1086. CmdArgs.push_back(ABIName.data());
  1087. mips::FloatABI ABI = getMipsFloatABI(D, Args);
  1088. if (ABI == mips::FloatABI::Soft) {
  1089. // Floating point operations and argument passing are soft.
  1090. CmdArgs.push_back("-msoft-float");
  1091. CmdArgs.push_back("-mfloat-abi");
  1092. CmdArgs.push_back("soft");
  1093. } else {
  1094. // Floating point operations and argument passing are hard.
  1095. assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
  1096. CmdArgs.push_back("-mfloat-abi");
  1097. CmdArgs.push_back("hard");
  1098. }
  1099. if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
  1100. if (A->getOption().matches(options::OPT_mxgot)) {
  1101. CmdArgs.push_back("-mllvm");
  1102. CmdArgs.push_back("-mxgot");
  1103. }
  1104. }
  1105. if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
  1106. options::OPT_mno_ldc1_sdc1)) {
  1107. if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
  1108. CmdArgs.push_back("-mllvm");
  1109. CmdArgs.push_back("-mno-ldc1-sdc1");
  1110. }
  1111. }
  1112. if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
  1113. options::OPT_mno_check_zero_division)) {
  1114. if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
  1115. CmdArgs.push_back("-mllvm");
  1116. CmdArgs.push_back("-mno-check-zero-division");
  1117. }
  1118. }
  1119. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  1120. StringRef v = A->getValue();
  1121. CmdArgs.push_back("-mllvm");
  1122. CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
  1123. A->claim();
  1124. }
  1125. }
  1126. /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
  1127. static std::string getPPCTargetCPU(const ArgList &Args) {
  1128. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1129. StringRef CPUName = A->getValue();
  1130. if (CPUName == "native") {
  1131. std::string CPU = llvm::sys::getHostCPUName();
  1132. if (!CPU.empty() && CPU != "generic")
  1133. return CPU;
  1134. else
  1135. return "";
  1136. }
  1137. return llvm::StringSwitch<const char *>(CPUName)
  1138. .Case("common", "generic")
  1139. .Case("440", "440")
  1140. .Case("440fp", "440")
  1141. .Case("450", "450")
  1142. .Case("601", "601")
  1143. .Case("602", "602")
  1144. .Case("603", "603")
  1145. .Case("603e", "603e")
  1146. .Case("603ev", "603ev")
  1147. .Case("604", "604")
  1148. .Case("604e", "604e")
  1149. .Case("620", "620")
  1150. .Case("630", "pwr3")
  1151. .Case("G3", "g3")
  1152. .Case("7400", "7400")
  1153. .Case("G4", "g4")
  1154. .Case("7450", "7450")
  1155. .Case("G4+", "g4+")
  1156. .Case("750", "750")
  1157. .Case("970", "970")
  1158. .Case("G5", "g5")
  1159. .Case("a2", "a2")
  1160. .Case("a2q", "a2q")
  1161. .Case("e500mc", "e500mc")
  1162. .Case("e5500", "e5500")
  1163. .Case("power3", "pwr3")
  1164. .Case("power4", "pwr4")
  1165. .Case("power5", "pwr5")
  1166. .Case("power5x", "pwr5x")
  1167. .Case("power6", "pwr6")
  1168. .Case("power6x", "pwr6x")
  1169. .Case("power7", "pwr7")
  1170. .Case("power8", "pwr8")
  1171. .Case("pwr3", "pwr3")
  1172. .Case("pwr4", "pwr4")
  1173. .Case("pwr5", "pwr5")
  1174. .Case("pwr5x", "pwr5x")
  1175. .Case("pwr6", "pwr6")
  1176. .Case("pwr6x", "pwr6x")
  1177. .Case("pwr7", "pwr7")
  1178. .Case("pwr8", "pwr8")
  1179. .Case("powerpc", "ppc")
  1180. .Case("powerpc64", "ppc64")
  1181. .Case("powerpc64le", "ppc64le")
  1182. .Default("");
  1183. }
  1184. return "";
  1185. }
  1186. static void getPPCTargetFeatures(const ArgList &Args,
  1187. std::vector<const char *> &Features) {
  1188. for (const Arg *A : Args.filtered(options::OPT_m_ppc_Features_Group)) {
  1189. StringRef Name = A->getOption().getName();
  1190. A->claim();
  1191. // Skip over "-m".
  1192. assert(Name.startswith("m") && "Invalid feature name.");
  1193. Name = Name.substr(1);
  1194. bool IsNegative = Name.startswith("no-");
  1195. if (IsNegative)
  1196. Name = Name.substr(3);
  1197. // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
  1198. // pass the correct option to the backend while calling the frontend
  1199. // option the same.
  1200. // TODO: Change the LLVM backend option maybe?
  1201. if (Name == "mfcrf")
  1202. Name = "mfocrf";
  1203. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  1204. }
  1205. // Altivec is a bit weird, allow overriding of the Altivec feature here.
  1206. AddTargetFeature(Args, Features, options::OPT_faltivec,
  1207. options::OPT_fno_altivec, "altivec");
  1208. }
  1209. void Clang::AddPPCTargetArgs(const ArgList &Args,
  1210. ArgStringList &CmdArgs) const {
  1211. // Select the ABI to use.
  1212. const char *ABIName = nullptr;
  1213. if (getToolChain().getTriple().isOSLinux())
  1214. switch (getToolChain().getArch()) {
  1215. case llvm::Triple::ppc64: {
  1216. // When targeting a processor that supports QPX, or if QPX is
  1217. // specifically enabled, default to using the ABI that supports QPX (so
  1218. // long as it is not specifically disabled).
  1219. bool HasQPX = false;
  1220. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1221. HasQPX = A->getValue() == StringRef("a2q");
  1222. HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
  1223. if (HasQPX) {
  1224. ABIName = "elfv1-qpx";
  1225. break;
  1226. }
  1227. ABIName = "elfv1";
  1228. break;
  1229. }
  1230. case llvm::Triple::ppc64le:
  1231. ABIName = "elfv2";
  1232. break;
  1233. default:
  1234. break;
  1235. }
  1236. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1237. // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
  1238. // the option if given as we don't have backend support for any targets
  1239. // that don't use the altivec abi.
  1240. if (StringRef(A->getValue()) != "altivec")
  1241. ABIName = A->getValue();
  1242. if (ABIName) {
  1243. CmdArgs.push_back("-target-abi");
  1244. CmdArgs.push_back(ABIName);
  1245. }
  1246. }
  1247. bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
  1248. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  1249. return A && (A->getValue() == StringRef(Value));
  1250. }
  1251. /// Get the (LLVM) name of the R600 gpu we are targeting.
  1252. static std::string getR600TargetGPU(const ArgList &Args) {
  1253. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1254. const char *GPUName = A->getValue();
  1255. return llvm::StringSwitch<const char *>(GPUName)
  1256. .Cases("rv630", "rv635", "r600")
  1257. .Cases("rv610", "rv620", "rs780", "rs880")
  1258. .Case("rv740", "rv770")
  1259. .Case("palm", "cedar")
  1260. .Cases("sumo", "sumo2", "sumo")
  1261. .Case("hemlock", "cypress")
  1262. .Case("aruba", "cayman")
  1263. .Default(GPUName);
  1264. }
  1265. return "";
  1266. }
  1267. void Clang::AddSparcTargetArgs(const ArgList &Args,
  1268. ArgStringList &CmdArgs) const {
  1269. const Driver &D = getToolChain().getDriver();
  1270. std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
  1271. bool SoftFloatABI = false;
  1272. if (Arg *A =
  1273. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
  1274. if (A->getOption().matches(options::OPT_msoft_float))
  1275. SoftFloatABI = true;
  1276. }
  1277. // Only the hard-float ABI on Sparc is standardized, and it is the
  1278. // default. GCC also supports a nonstandard soft-float ABI mode, and
  1279. // perhaps LLVM should implement that, too. However, since llvm
  1280. // currently does not support Sparc soft-float, at all, display an
  1281. // error if it's requested.
  1282. if (SoftFloatABI) {
  1283. D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
  1284. << Triple;
  1285. }
  1286. }
  1287. static const char *getSystemZTargetCPU(const ArgList &Args) {
  1288. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1289. return A->getValue();
  1290. return "z10";
  1291. }
  1292. static void getSystemZTargetFeatures(const ArgList &Args,
  1293. std::vector<const char *> &Features) {
  1294. // -m(no-)htm overrides use of the transactional-execution facility.
  1295. if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
  1296. if (A->getOption().matches(options::OPT_mhtm))
  1297. Features.push_back("+transactional-execution");
  1298. else
  1299. Features.push_back("-transactional-execution");
  1300. }
  1301. // -m(no-)vx overrides use of the vector facility.
  1302. if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
  1303. if (A->getOption().matches(options::OPT_mvx))
  1304. Features.push_back("+vector");
  1305. else
  1306. Features.push_back("-vector");
  1307. }
  1308. }
  1309. static const char *getX86TargetCPU(const ArgList &Args,
  1310. const llvm::Triple &Triple) {
  1311. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1312. if (StringRef(A->getValue()) != "native") {
  1313. if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
  1314. return "core-avx2";
  1315. return A->getValue();
  1316. }
  1317. // FIXME: Reject attempts to use -march=native unless the target matches
  1318. // the host.
  1319. //
  1320. // FIXME: We should also incorporate the detected target features for use
  1321. // with -native.
  1322. std::string CPU = llvm::sys::getHostCPUName();
  1323. if (!CPU.empty() && CPU != "generic")
  1324. return Args.MakeArgString(CPU);
  1325. }
  1326. if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1327. // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
  1328. StringRef Arch = A->getValue();
  1329. const char *CPU;
  1330. if (Triple.getArch() == llvm::Triple::x86) {
  1331. CPU = llvm::StringSwitch<const char *>(Arch)
  1332. .Case("IA32", "i386")
  1333. .Case("SSE", "pentium3")
  1334. .Case("SSE2", "pentium4")
  1335. .Case("AVX", "sandybridge")
  1336. .Case("AVX2", "haswell")
  1337. .Default(nullptr);
  1338. } else {
  1339. CPU = llvm::StringSwitch<const char *>(Arch)
  1340. .Case("AVX", "sandybridge")
  1341. .Case("AVX2", "haswell")
  1342. .Default(nullptr);
  1343. }
  1344. if (CPU)
  1345. return CPU;
  1346. }
  1347. // Select the default CPU if none was given (or detection failed).
  1348. if (Triple.getArch() != llvm::Triple::x86_64 &&
  1349. Triple.getArch() != llvm::Triple::x86)
  1350. return nullptr; // This routine is only handling x86 targets.
  1351. bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
  1352. // FIXME: Need target hooks.
  1353. if (Triple.isOSDarwin()) {
  1354. if (Triple.getArchName() == "x86_64h")
  1355. return "core-avx2";
  1356. return Is64Bit ? "core2" : "yonah";
  1357. }
  1358. // Set up default CPU name for PS4 compilers.
  1359. if (Triple.isPS4CPU())
  1360. return "btver2";
  1361. // On Android use targets compatible with gcc
  1362. if (Triple.isAndroid())
  1363. return Is64Bit ? "x86-64" : "i686";
  1364. // Everything else goes to x86-64 in 64-bit mode.
  1365. if (Is64Bit)
  1366. return "x86-64";
  1367. switch (Triple.getOS()) {
  1368. case llvm::Triple::FreeBSD:
  1369. case llvm::Triple::NetBSD:
  1370. case llvm::Triple::OpenBSD:
  1371. return "i486";
  1372. case llvm::Triple::Haiku:
  1373. return "i586";
  1374. case llvm::Triple::Bitrig:
  1375. return "i686";
  1376. default:
  1377. // Fallback to p4.
  1378. return "pentium4";
  1379. }
  1380. }
  1381. /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
  1382. static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
  1383. // If we have -mcpu=, use that.
  1384. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1385. StringRef CPU = A->getValue();
  1386. #ifdef __wasm__
  1387. // Handle "native" by examining the host. "native" isn't meaningful when
  1388. // cross compiling, so only support this when the host is also WebAssembly.
  1389. if (CPU == "native")
  1390. return llvm::sys::getHostCPUName();
  1391. #endif
  1392. return CPU;
  1393. }
  1394. return "generic";
  1395. }
  1396. static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
  1397. bool FromAs = false) {
  1398. switch (T.getArch()) {
  1399. default:
  1400. return "";
  1401. case llvm::Triple::aarch64:
  1402. case llvm::Triple::aarch64_be:
  1403. return getAArch64TargetCPU(Args);
  1404. case llvm::Triple::arm:
  1405. case llvm::Triple::armeb:
  1406. case llvm::Triple::thumb:
  1407. case llvm::Triple::thumbeb: {
  1408. StringRef MArch, MCPU;
  1409. getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
  1410. return arm::getARMTargetCPU(MCPU, MArch, T);
  1411. }
  1412. case llvm::Triple::mips:
  1413. case llvm::Triple::mipsel:
  1414. case llvm::Triple::mips64:
  1415. case llvm::Triple::mips64el: {
  1416. StringRef CPUName;
  1417. StringRef ABIName;
  1418. mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
  1419. return CPUName;
  1420. }
  1421. case llvm::Triple::nvptx:
  1422. case llvm::Triple::nvptx64:
  1423. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1424. return A->getValue();
  1425. return "";
  1426. case llvm::Triple::ppc:
  1427. case llvm::Triple::ppc64:
  1428. case llvm::Triple::ppc64le: {
  1429. std::string TargetCPUName = getPPCTargetCPU(Args);
  1430. // LLVM may default to generating code for the native CPU,
  1431. // but, like gcc, we default to a more generic option for
  1432. // each architecture. (except on Darwin)
  1433. if (TargetCPUName.empty() && !T.isOSDarwin()) {
  1434. if (T.getArch() == llvm::Triple::ppc64)
  1435. TargetCPUName = "ppc64";
  1436. else if (T.getArch() == llvm::Triple::ppc64le)
  1437. TargetCPUName = "ppc64le";
  1438. else
  1439. TargetCPUName = "ppc";
  1440. }
  1441. return TargetCPUName;
  1442. }
  1443. case llvm::Triple::sparc:
  1444. case llvm::Triple::sparcel:
  1445. case llvm::Triple::sparcv9:
  1446. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1447. return A->getValue();
  1448. return "";
  1449. case llvm::Triple::x86:
  1450. case llvm::Triple::x86_64:
  1451. return getX86TargetCPU(Args, T);
  1452. case llvm::Triple::hexagon:
  1453. return "hexagon" + toolchains::HexagonToolChain::GetTargetCPU(Args).str();
  1454. case llvm::Triple::systemz:
  1455. return getSystemZTargetCPU(Args);
  1456. case llvm::Triple::r600:
  1457. case llvm::Triple::amdgcn:
  1458. return getR600TargetGPU(Args);
  1459. case llvm::Triple::wasm32:
  1460. case llvm::Triple::wasm64:
  1461. return getWebAssemblyTargetCPU(Args);
  1462. }
  1463. }
  1464. static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
  1465. ArgStringList &CmdArgs) {
  1466. // Tell the linker to load the plugin. This has to come before AddLinkerInputs
  1467. // as gold requires -plugin to come before any -plugin-opt that -Wl might
  1468. // forward.
  1469. CmdArgs.push_back("-plugin");
  1470. std::string Plugin =
  1471. ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
  1472. CmdArgs.push_back(Args.MakeArgString(Plugin));
  1473. // Try to pass driver level flags relevant to LTO code generation down to
  1474. // the plugin.
  1475. // Handle flags for selecting CPU variants.
  1476. std::string CPU = getCPUName(Args, ToolChain.getTriple());
  1477. if (!CPU.empty())
  1478. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
  1479. }
  1480. /// This is a helper function for validating the optional refinement step
  1481. /// parameter in reciprocal argument strings. Return false if there is an error
  1482. /// parsing the refinement step. Otherwise, return true and set the Position
  1483. /// of the refinement step in the input string.
  1484. static bool getRefinementStep(StringRef In, const Driver &D,
  1485. const Arg &A, size_t &Position) {
  1486. const char RefinementStepToken = ':';
  1487. Position = In.find(RefinementStepToken);
  1488. if (Position != StringRef::npos) {
  1489. StringRef Option = A.getOption().getName();
  1490. StringRef RefStep = In.substr(Position + 1);
  1491. // Allow exactly one numeric character for the additional refinement
  1492. // step parameter. This is reasonable for all currently-supported
  1493. // operations and architectures because we would expect that a larger value
  1494. // of refinement steps would cause the estimate "optimization" to
  1495. // under-perform the native operation. Also, if the estimate does not
  1496. // converge quickly, it probably will not ever converge, so further
  1497. // refinement steps will not produce a better answer.
  1498. if (RefStep.size() != 1) {
  1499. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1500. return false;
  1501. }
  1502. char RefStepChar = RefStep[0];
  1503. if (RefStepChar < '0' || RefStepChar > '9') {
  1504. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1505. return false;
  1506. }
  1507. }
  1508. return true;
  1509. }
  1510. /// The -mrecip flag requires processing of many optional parameters.
  1511. static void ParseMRecip(const Driver &D, const ArgList &Args,
  1512. ArgStringList &OutStrings) {
  1513. StringRef DisabledPrefixIn = "!";
  1514. StringRef DisabledPrefixOut = "!";
  1515. StringRef EnabledPrefixOut = "";
  1516. StringRef Out = "-mrecip=";
  1517. Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
  1518. if (!A)
  1519. return;
  1520. unsigned NumOptions = A->getNumValues();
  1521. if (NumOptions == 0) {
  1522. // No option is the same as "all".
  1523. OutStrings.push_back(Args.MakeArgString(Out + "all"));
  1524. return;
  1525. }
  1526. // Pass through "all", "none", or "default" with an optional refinement step.
  1527. if (NumOptions == 1) {
  1528. StringRef Val = A->getValue(0);
  1529. size_t RefStepLoc;
  1530. if (!getRefinementStep(Val, D, *A, RefStepLoc))
  1531. return;
  1532. StringRef ValBase = Val.slice(0, RefStepLoc);
  1533. if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
  1534. OutStrings.push_back(Args.MakeArgString(Out + Val));
  1535. return;
  1536. }
  1537. }
  1538. // Each reciprocal type may be enabled or disabled individually.
  1539. // Check each input value for validity, concatenate them all back together,
  1540. // and pass through.
  1541. llvm::StringMap<bool> OptionStrings;
  1542. OptionStrings.insert(std::make_pair("divd", false));
  1543. OptionStrings.insert(std::make_pair("divf", false));
  1544. OptionStrings.insert(std::make_pair("vec-divd", false));
  1545. OptionStrings.insert(std::make_pair("vec-divf", false));
  1546. OptionStrings.insert(std::make_pair("sqrtd", false));
  1547. OptionStrings.insert(std::make_pair("sqrtf", false));
  1548. OptionStrings.insert(std::make_pair("vec-sqrtd", false));
  1549. OptionStrings.insert(std::make_pair("vec-sqrtf", false));
  1550. for (unsigned i = 0; i != NumOptions; ++i) {
  1551. StringRef Val = A->getValue(i);
  1552. bool IsDisabled = Val.startswith(DisabledPrefixIn);
  1553. // Ignore the disablement token for string matching.
  1554. if (IsDisabled)
  1555. Val = Val.substr(1);
  1556. size_t RefStep;
  1557. if (!getRefinementStep(Val, D, *A, RefStep))
  1558. return;
  1559. StringRef ValBase = Val.slice(0, RefStep);
  1560. llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
  1561. if (OptionIter == OptionStrings.end()) {
  1562. // Try again specifying float suffix.
  1563. OptionIter = OptionStrings.find(ValBase.str() + 'f');
  1564. if (OptionIter == OptionStrings.end()) {
  1565. // The input name did not match any known option string.
  1566. D.Diag(diag::err_drv_unknown_argument) << Val;
  1567. return;
  1568. }
  1569. // The option was specified without a float or double suffix.
  1570. // Make sure that the double entry was not already specified.
  1571. // The float entry will be checked below.
  1572. if (OptionStrings[ValBase.str() + 'd']) {
  1573. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1574. return;
  1575. }
  1576. }
  1577. if (OptionIter->second == true) {
  1578. // Duplicate option specified.
  1579. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1580. return;
  1581. }
  1582. // Mark the matched option as found. Do not allow duplicate specifiers.
  1583. OptionIter->second = true;
  1584. // If the precision was not specified, also mark the double entry as found.
  1585. if (ValBase.back() != 'f' && ValBase.back() != 'd')
  1586. OptionStrings[ValBase.str() + 'd'] = true;
  1587. // Build the output string.
  1588. StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
  1589. Out = Args.MakeArgString(Out + Prefix + Val);
  1590. if (i != NumOptions - 1)
  1591. Out = Args.MakeArgString(Out + ",");
  1592. }
  1593. OutStrings.push_back(Args.MakeArgString(Out));
  1594. }
  1595. static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1596. const ArgList &Args,
  1597. std::vector<const char *> &Features) {
  1598. // If -march=native, autodetect the feature list.
  1599. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1600. if (StringRef(A->getValue()) == "native") {
  1601. llvm::StringMap<bool> HostFeatures;
  1602. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  1603. for (auto &F : HostFeatures)
  1604. Features.push_back(
  1605. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  1606. }
  1607. }
  1608. if (Triple.getArchName() == "x86_64h") {
  1609. // x86_64h implies quite a few of the more modern subtarget features
  1610. // for Haswell class CPUs, but not all of them. Opt-out of a few.
  1611. Features.push_back("-rdrnd");
  1612. Features.push_back("-aes");
  1613. Features.push_back("-pclmul");
  1614. Features.push_back("-rtm");
  1615. Features.push_back("-hle");
  1616. Features.push_back("-fsgsbase");
  1617. }
  1618. const llvm::Triple::ArchType ArchType = Triple.getArch();
  1619. // Add features to be compatible with gcc for Android.
  1620. if (Triple.isAndroid()) {
  1621. if (ArchType == llvm::Triple::x86_64) {
  1622. Features.push_back("+sse4.2");
  1623. Features.push_back("+popcnt");
  1624. } else
  1625. Features.push_back("+ssse3");
  1626. }
  1627. // Set features according to the -arch flag on MSVC.
  1628. if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1629. StringRef Arch = A->getValue();
  1630. bool ArchUsed = false;
  1631. // First, look for flags that are shared in x86 and x86-64.
  1632. if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
  1633. if (Arch == "AVX" || Arch == "AVX2") {
  1634. ArchUsed = true;
  1635. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1636. }
  1637. }
  1638. // Then, look for x86-specific flags.
  1639. if (ArchType == llvm::Triple::x86) {
  1640. if (Arch == "IA32") {
  1641. ArchUsed = true;
  1642. } else if (Arch == "SSE" || Arch == "SSE2") {
  1643. ArchUsed = true;
  1644. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1645. }
  1646. }
  1647. if (!ArchUsed)
  1648. D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
  1649. }
  1650. // Now add any that the user explicitly requested on the command line,
  1651. // which may override the defaults.
  1652. for (const Arg *A : Args.filtered(options::OPT_m_x86_Features_Group)) {
  1653. StringRef Name = A->getOption().getName();
  1654. A->claim();
  1655. // Skip over "-m".
  1656. assert(Name.startswith("m") && "Invalid feature name.");
  1657. Name = Name.substr(1);
  1658. bool IsNegative = Name.startswith("no-");
  1659. if (IsNegative)
  1660. Name = Name.substr(3);
  1661. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  1662. }
  1663. }
  1664. void Clang::AddX86TargetArgs(const ArgList &Args,
  1665. ArgStringList &CmdArgs) const {
  1666. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1667. Args.hasArg(options::OPT_mkernel) ||
  1668. Args.hasArg(options::OPT_fapple_kext))
  1669. CmdArgs.push_back("-disable-red-zone");
  1670. // Default to avoid implicit floating-point for kernel/kext code, but allow
  1671. // that to be overridden with -mno-soft-float.
  1672. bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
  1673. Args.hasArg(options::OPT_fapple_kext));
  1674. if (Arg *A = Args.getLastArg(
  1675. options::OPT_msoft_float, options::OPT_mno_soft_float,
  1676. options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
  1677. const Option &O = A->getOption();
  1678. NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
  1679. O.matches(options::OPT_msoft_float));
  1680. }
  1681. if (NoImplicitFloat)
  1682. CmdArgs.push_back("-no-implicit-float");
  1683. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  1684. StringRef Value = A->getValue();
  1685. if (Value == "intel" || Value == "att") {
  1686. CmdArgs.push_back("-mllvm");
  1687. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  1688. } else {
  1689. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  1690. << A->getOption().getName() << Value;
  1691. }
  1692. }
  1693. }
  1694. void Clang::AddHexagonTargetArgs(const ArgList &Args,
  1695. ArgStringList &CmdArgs) const {
  1696. CmdArgs.push_back("-mqdsp6-compat");
  1697. CmdArgs.push_back("-Wreturn-type");
  1698. if (const char *v =
  1699. toolchains::HexagonToolChain::GetSmallDataThreshold(Args)) {
  1700. std::string SmallDataThreshold = "-hexagon-small-data-threshold=";
  1701. SmallDataThreshold += v;
  1702. CmdArgs.push_back("-mllvm");
  1703. CmdArgs.push_back(Args.MakeArgString(SmallDataThreshold));
  1704. }
  1705. if (!Args.hasArg(options::OPT_fno_short_enums))
  1706. CmdArgs.push_back("-fshort-enums");
  1707. if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
  1708. CmdArgs.push_back("-mllvm");
  1709. CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
  1710. }
  1711. CmdArgs.push_back("-mllvm");
  1712. CmdArgs.push_back("-machine-sink-split=0");
  1713. }
  1714. // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
  1715. static bool DecodeAArch64Features(const Driver &D, StringRef text,
  1716. std::vector<const char *> &Features) {
  1717. SmallVector<StringRef, 8> Split;
  1718. text.split(Split, StringRef("+"), -1, false);
  1719. for (StringRef Feature : Split) {
  1720. const char *result = llvm::StringSwitch<const char *>(Feature)
  1721. .Case("fp", "+fp-armv8")
  1722. .Case("simd", "+neon")
  1723. .Case("crc", "+crc")
  1724. .Case("crypto", "+crypto")
  1725. .Case("nofp", "-fp-armv8")
  1726. .Case("nosimd", "-neon")
  1727. .Case("nocrc", "-crc")
  1728. .Case("nocrypto", "-crypto")
  1729. .Default(nullptr);
  1730. if (result)
  1731. Features.push_back(result);
  1732. else if (Feature == "neon" || Feature == "noneon")
  1733. D.Diag(diag::err_drv_no_neon_modifier);
  1734. else
  1735. return false;
  1736. }
  1737. return true;
  1738. }
  1739. // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
  1740. // decode CPU and feature.
  1741. static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
  1742. std::vector<const char *> &Features) {
  1743. std::pair<StringRef, StringRef> Split = Mcpu.split("+");
  1744. CPU = Split.first;
  1745. if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
  1746. CPU == "cortex-a72") {
  1747. Features.push_back("+neon");
  1748. Features.push_back("+crc");
  1749. Features.push_back("+crypto");
  1750. } else if (CPU == "generic") {
  1751. Features.push_back("+neon");
  1752. } else {
  1753. return false;
  1754. }
  1755. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  1756. return false;
  1757. return true;
  1758. }
  1759. static bool
  1760. getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
  1761. const ArgList &Args,
  1762. std::vector<const char *> &Features) {
  1763. std::string MarchLowerCase = March.lower();
  1764. std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
  1765. if (Split.first == "armv8-a" || Split.first == "armv8a") {
  1766. // ok, no additional features.
  1767. } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
  1768. Features.push_back("+v8.1a");
  1769. } else {
  1770. return false;
  1771. }
  1772. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  1773. return false;
  1774. return true;
  1775. }
  1776. static bool
  1777. getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  1778. const ArgList &Args,
  1779. std::vector<const char *> &Features) {
  1780. StringRef CPU;
  1781. std::string McpuLowerCase = Mcpu.lower();
  1782. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
  1783. return false;
  1784. return true;
  1785. }
  1786. static bool
  1787. getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
  1788. const ArgList &Args,
  1789. std::vector<const char *> &Features) {
  1790. std::string MtuneLowerCase = Mtune.lower();
  1791. // Handle CPU name is 'native'.
  1792. if (MtuneLowerCase == "native")
  1793. MtuneLowerCase = llvm::sys::getHostCPUName();
  1794. if (MtuneLowerCase == "cyclone") {
  1795. Features.push_back("+zcm");
  1796. Features.push_back("+zcz");
  1797. }
  1798. return true;
  1799. }
  1800. static bool
  1801. getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  1802. const ArgList &Args,
  1803. std::vector<const char *> &Features) {
  1804. StringRef CPU;
  1805. std::vector<const char *> DecodedFeature;
  1806. std::string McpuLowerCase = Mcpu.lower();
  1807. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
  1808. return false;
  1809. return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
  1810. }
  1811. static void getAArch64TargetFeatures(const Driver &D,
  1812. const llvm::Triple &Triple,
  1813. const ArgList &Args,
  1814. std::vector<const char *> &Features) {
  1815. Arg *A;
  1816. bool success = true;
  1817. // Enable NEON by default.
  1818. Features.push_back("+neon");
  1819. if ((A = Args.getLastArg(options::OPT_march_EQ)))
  1820. success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
  1821. else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
  1822. success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  1823. else if (Args.hasArg(options::OPT_arch))
  1824. success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
  1825. Features);
  1826. if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
  1827. success =
  1828. getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
  1829. else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
  1830. success =
  1831. getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  1832. else if (Args.hasArg(options::OPT_arch))
  1833. success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
  1834. Args, Features);
  1835. if (!success)
  1836. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  1837. if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
  1838. Features.push_back("-fp-armv8");
  1839. Features.push_back("-crypto");
  1840. Features.push_back("-neon");
  1841. }
  1842. // En/disable crc
  1843. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  1844. if (A->getOption().matches(options::OPT_mcrc))
  1845. Features.push_back("+crc");
  1846. else
  1847. Features.push_back("-crc");
  1848. }
  1849. if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  1850. options::OPT_munaligned_access))
  1851. if (A->getOption().matches(options::OPT_mno_unaligned_access))
  1852. Features.push_back("+strict-align");
  1853. if (Args.hasArg(options::OPT_ffixed_x18) || Triple.isOSDarwin())
  1854. Features.push_back("+reserve-x18");
  1855. }
  1856. static void getWebAssemblyTargetFeatures(const ArgList &Args,
  1857. std::vector<const char *> &Features) {
  1858. for (const Arg *A : Args.filtered(options::OPT_m_wasm_Features_Group)) {
  1859. StringRef Name = A->getOption().getName();
  1860. A->claim();
  1861. // Skip over "-m".
  1862. assert(Name.startswith("m") && "Invalid feature name.");
  1863. Name = Name.substr(1);
  1864. bool IsNegative = Name.startswith("no-");
  1865. if (IsNegative)
  1866. Name = Name.substr(3);
  1867. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  1868. }
  1869. }
  1870. static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
  1871. const ArgList &Args, ArgStringList &CmdArgs,
  1872. bool ForAS) {
  1873. const Driver &D = TC.getDriver();
  1874. std::vector<const char *> Features;
  1875. switch (Triple.getArch()) {
  1876. default:
  1877. break;
  1878. case llvm::Triple::mips:
  1879. case llvm::Triple::mipsel:
  1880. case llvm::Triple::mips64:
  1881. case llvm::Triple::mips64el:
  1882. getMIPSTargetFeatures(D, Triple, Args, Features);
  1883. break;
  1884. case llvm::Triple::arm:
  1885. case llvm::Triple::armeb:
  1886. case llvm::Triple::thumb:
  1887. case llvm::Triple::thumbeb:
  1888. getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
  1889. break;
  1890. case llvm::Triple::ppc:
  1891. case llvm::Triple::ppc64:
  1892. case llvm::Triple::ppc64le:
  1893. getPPCTargetFeatures(Args, Features);
  1894. break;
  1895. case llvm::Triple::systemz:
  1896. getSystemZTargetFeatures(Args, Features);
  1897. break;
  1898. case llvm::Triple::aarch64:
  1899. case llvm::Triple::aarch64_be:
  1900. getAArch64TargetFeatures(D, Triple, Args, Features);
  1901. break;
  1902. case llvm::Triple::x86:
  1903. case llvm::Triple::x86_64:
  1904. getX86TargetFeatures(D, Triple, Args, Features);
  1905. break;
  1906. case llvm::Triple::wasm32:
  1907. case llvm::Triple::wasm64:
  1908. getWebAssemblyTargetFeatures(Args, Features);
  1909. break;
  1910. }
  1911. // Find the last of each feature.
  1912. llvm::StringMap<unsigned> LastOpt;
  1913. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  1914. const char *Name = Features[I];
  1915. assert(Name[0] == '-' || Name[0] == '+');
  1916. LastOpt[Name + 1] = I;
  1917. }
  1918. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  1919. // If this feature was overridden, ignore it.
  1920. const char *Name = Features[I];
  1921. llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
  1922. assert(LastI != LastOpt.end());
  1923. unsigned Last = LastI->second;
  1924. if (Last != I)
  1925. continue;
  1926. CmdArgs.push_back("-target-feature");
  1927. CmdArgs.push_back(Name);
  1928. }
  1929. }
  1930. static bool
  1931. shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
  1932. const llvm::Triple &Triple) {
  1933. // We use the zero-cost exception tables for Objective-C if the non-fragile
  1934. // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
  1935. // later.
  1936. if (runtime.isNonFragile())
  1937. return true;
  1938. if (!Triple.isMacOSX())
  1939. return false;
  1940. return (!Triple.isMacOSXVersionLT(10, 5) &&
  1941. (Triple.getArch() == llvm::Triple::x86_64 ||
  1942. Triple.getArch() == llvm::Triple::arm));
  1943. }
  1944. /// Adds exception related arguments to the driver command arguments. There's a
  1945. /// master flag, -fexceptions and also language specific flags to enable/disable
  1946. /// C++ and Objective-C exceptions. This makes it possible to for example
  1947. /// disable C++ exceptions but enable Objective-C exceptions.
  1948. static void addExceptionArgs(const ArgList &Args, types::ID InputType,
  1949. const ToolChain &TC, bool KernelOrKext,
  1950. const ObjCRuntime &objcRuntime,
  1951. ArgStringList &CmdArgs) {
  1952. const Driver &D = TC.getDriver();
  1953. const llvm::Triple &Triple = TC.getTriple();
  1954. if (KernelOrKext) {
  1955. // -mkernel and -fapple-kext imply no exceptions, so claim exception related
  1956. // arguments now to avoid warnings about unused arguments.
  1957. Args.ClaimAllArgs(options::OPT_fexceptions);
  1958. Args.ClaimAllArgs(options::OPT_fno_exceptions);
  1959. Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
  1960. Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
  1961. Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
  1962. Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
  1963. return;
  1964. }
  1965. // See if the user explicitly enabled exceptions.
  1966. bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  1967. false);
  1968. // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
  1969. // is not necessarily sensible, but follows GCC.
  1970. if (types::isObjC(InputType) &&
  1971. Args.hasFlag(options::OPT_fobjc_exceptions,
  1972. options::OPT_fno_objc_exceptions, true)) {
  1973. CmdArgs.push_back("-fobjc-exceptions");
  1974. EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
  1975. }
  1976. if (types::isCXX(InputType)) {
  1977. // Disable C++ EH by default on XCore, PS4, and MSVC.
  1978. // FIXME: Remove MSVC from this list once things work.
  1979. bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
  1980. !Triple.isPS4CPU() &&
  1981. !Triple.isWindowsMSVCEnvironment();
  1982. Arg *ExceptionArg = Args.getLastArg(
  1983. options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
  1984. options::OPT_fexceptions, options::OPT_fno_exceptions);
  1985. if (ExceptionArg)
  1986. CXXExceptionsEnabled =
  1987. ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
  1988. ExceptionArg->getOption().matches(options::OPT_fexceptions);
  1989. if (CXXExceptionsEnabled) {
  1990. if (Triple.isPS4CPU()) {
  1991. ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
  1992. assert(ExceptionArg &&
  1993. "On the PS4 exceptions should only be enabled if passing "
  1994. "an argument");
  1995. if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
  1996. const Arg *RTTIArg = TC.getRTTIArg();
  1997. assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
  1998. D.Diag(diag::err_drv_argument_not_allowed_with)
  1999. << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
  2000. } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
  2001. D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
  2002. } else
  2003. assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
  2004. CmdArgs.push_back("-fcxx-exceptions");
  2005. EH = true;
  2006. }
  2007. }
  2008. if (EH)
  2009. CmdArgs.push_back("-fexceptions");
  2010. }
  2011. static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
  2012. bool Default = true;
  2013. if (TC.getTriple().isOSDarwin()) {
  2014. // The native darwin assembler doesn't support the linker_option directives,
  2015. // so we disable them if we think the .s file will be passed to it.
  2016. Default = TC.useIntegratedAs();
  2017. }
  2018. return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
  2019. Default);
  2020. }
  2021. static bool ShouldDisableDwarfDirectory(const ArgList &Args,
  2022. const ToolChain &TC) {
  2023. bool UseDwarfDirectory =
  2024. Args.hasFlag(options::OPT_fdwarf_directory_asm,
  2025. options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
  2026. return !UseDwarfDirectory;
  2027. }
  2028. /// \brief Check whether the given input tree contains any compilation actions.
  2029. static bool ContainsCompileAction(const Action *A) {
  2030. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
  2031. return true;
  2032. for (const auto &Act : *A)
  2033. if (ContainsCompileAction(Act))
  2034. return true;
  2035. return false;
  2036. }
  2037. /// \brief Check if -relax-all should be passed to the internal assembler.
  2038. /// This is done by default when compiling non-assembler source with -O0.
  2039. static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
  2040. bool RelaxDefault = true;
  2041. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2042. RelaxDefault = A->getOption().matches(options::OPT_O0);
  2043. if (RelaxDefault) {
  2044. RelaxDefault = false;
  2045. for (const auto &Act : C.getActions()) {
  2046. if (ContainsCompileAction(Act)) {
  2047. RelaxDefault = true;
  2048. break;
  2049. }
  2050. }
  2051. }
  2052. return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
  2053. RelaxDefault);
  2054. }
  2055. // Extract the integer N from a string spelled "-dwarf-N", returning 0
  2056. // on mismatch. The StringRef input (rather than an Arg) allows
  2057. // for use by the "-Xassembler" option parser.
  2058. static unsigned DwarfVersionNum(StringRef ArgValue) {
  2059. return llvm::StringSwitch<unsigned>(ArgValue)
  2060. .Case("-gdwarf-2", 2)
  2061. .Case("-gdwarf-3", 3)
  2062. .Case("-gdwarf-4", 4)
  2063. .Default(0);
  2064. }
  2065. static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
  2066. CodeGenOptions::DebugInfoKind DebugInfoKind,
  2067. unsigned DwarfVersion) {
  2068. switch (DebugInfoKind) {
  2069. case CodeGenOptions::DebugLineTablesOnly:
  2070. CmdArgs.push_back("-debug-info-kind=line-tables-only");
  2071. break;
  2072. case CodeGenOptions::LimitedDebugInfo:
  2073. CmdArgs.push_back("-debug-info-kind=limited");
  2074. break;
  2075. case CodeGenOptions::FullDebugInfo:
  2076. CmdArgs.push_back("-debug-info-kind=standalone");
  2077. break;
  2078. default:
  2079. break;
  2080. }
  2081. if (DwarfVersion > 0)
  2082. CmdArgs.push_back(
  2083. Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
  2084. }
  2085. static void CollectArgsForIntegratedAssembler(Compilation &C,
  2086. const ArgList &Args,
  2087. ArgStringList &CmdArgs,
  2088. const Driver &D) {
  2089. if (UseRelaxAll(C, Args))
  2090. CmdArgs.push_back("-mrelax-all");
  2091. // When passing -I arguments to the assembler we sometimes need to
  2092. // unconditionally take the next argument. For example, when parsing
  2093. // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
  2094. // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
  2095. // arg after parsing the '-I' arg.
  2096. bool TakeNextArg = false;
  2097. // When using an integrated assembler, translate -Wa, and -Xassembler
  2098. // options.
  2099. bool CompressDebugSections = false;
  2100. for (const Arg *A :
  2101. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  2102. A->claim();
  2103. for (StringRef Value : A->getValues()) {
  2104. if (TakeNextArg) {
  2105. CmdArgs.push_back(Value.data());
  2106. TakeNextArg = false;
  2107. continue;
  2108. }
  2109. if (Value == "-force_cpusubtype_ALL") {
  2110. // Do nothing, this is the default and we don't support anything else.
  2111. } else if (Value == "-L") {
  2112. CmdArgs.push_back("-msave-temp-labels");
  2113. } else if (Value == "--fatal-warnings") {
  2114. CmdArgs.push_back("-massembler-fatal-warnings");
  2115. } else if (Value == "--noexecstack") {
  2116. CmdArgs.push_back("-mnoexecstack");
  2117. } else if (Value == "-compress-debug-sections" ||
  2118. Value == "--compress-debug-sections") {
  2119. CompressDebugSections = true;
  2120. } else if (Value == "-nocompress-debug-sections" ||
  2121. Value == "--nocompress-debug-sections") {
  2122. CompressDebugSections = false;
  2123. } else if (Value.startswith("-I")) {
  2124. CmdArgs.push_back(Value.data());
  2125. // We need to consume the next argument if the current arg is a plain
  2126. // -I. The next arg will be the include directory.
  2127. if (Value == "-I")
  2128. TakeNextArg = true;
  2129. } else if (Value.startswith("-gdwarf-")) {
  2130. // "-gdwarf-N" options are not cc1as options.
  2131. unsigned DwarfVersion = DwarfVersionNum(Value);
  2132. if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
  2133. CmdArgs.push_back(Value.data());
  2134. } else {
  2135. RenderDebugEnablingArgs(
  2136. Args, CmdArgs, CodeGenOptions::LimitedDebugInfo, DwarfVersion);
  2137. }
  2138. } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
  2139. Value.startswith("-mhwdiv") || Value.startswith("-march")) {
  2140. // Do nothing, we'll validate it later.
  2141. } else if (Value == "--trap") {
  2142. CmdArgs.push_back("-target-feature");
  2143. CmdArgs.push_back("+use-tcc-in-div");
  2144. } else if (Value == "--break") {
  2145. CmdArgs.push_back("-target-feature");
  2146. CmdArgs.push_back("-use-tcc-in-div");
  2147. } else if (Value.startswith("-msoft-float")) {
  2148. CmdArgs.push_back("-target-feature");
  2149. CmdArgs.push_back("+soft-float");
  2150. } else if (Value.startswith("-mhard-float")) {
  2151. CmdArgs.push_back("-target-feature");
  2152. CmdArgs.push_back("-soft-float");
  2153. } else {
  2154. D.Diag(diag::err_drv_unsupported_option_argument)
  2155. << A->getOption().getName() << Value;
  2156. }
  2157. }
  2158. }
  2159. if (CompressDebugSections) {
  2160. if (llvm::zlib::isAvailable())
  2161. CmdArgs.push_back("-compress-debug-sections");
  2162. else
  2163. D.Diag(diag::warn_debug_compression_unavailable);
  2164. }
  2165. }
  2166. static const char *getCompilerRTArgString(const ToolChain &TC,
  2167. const llvm::opt::ArgList &Args,
  2168. StringRef Component,
  2169. bool Shared = false) {
  2170. return Args.MakeArgString(TC.getCompilerRT(Args, Component, Shared));
  2171. }
  2172. // This adds the static libclang_rt.builtins-arch.a directly to the command line
  2173. // FIXME: Make sure we can also emit shared objects if they're requested
  2174. // and available, check for possible errors, etc.
  2175. static void addClangRT(const ToolChain &TC, const ArgList &Args,
  2176. ArgStringList &CmdArgs) {
  2177. CmdArgs.push_back(getCompilerRTArgString(TC, Args, "builtins"));
  2178. }
  2179. static void addProfileRT(const ToolChain &TC, const ArgList &Args,
  2180. ArgStringList &CmdArgs) {
  2181. if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  2182. false) ||
  2183. Args.hasArg(options::OPT_fprofile_generate) ||
  2184. Args.hasArg(options::OPT_fprofile_generate_EQ) ||
  2185. Args.hasArg(options::OPT_fprofile_instr_generate) ||
  2186. Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
  2187. Args.hasArg(options::OPT_fcreate_profile) ||
  2188. Args.hasArg(options::OPT_coverage)))
  2189. return;
  2190. CmdArgs.push_back(getCompilerRTArgString(TC, Args, "profile"));
  2191. }
  2192. namespace {
  2193. enum OpenMPRuntimeKind {
  2194. /// An unknown OpenMP runtime. We can't generate effective OpenMP code
  2195. /// without knowing what runtime to target.
  2196. OMPRT_Unknown,
  2197. /// The LLVM OpenMP runtime. When completed and integrated, this will become
  2198. /// the default for Clang.
  2199. OMPRT_OMP,
  2200. /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
  2201. /// this runtime but can swallow the pragmas, and find and link against the
  2202. /// runtime library itself.
  2203. OMPRT_GOMP,
  2204. /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
  2205. /// OpenMP runtime. We support this mode for users with existing dependencies
  2206. /// on this runtime library name.
  2207. OMPRT_IOMP5
  2208. };
  2209. }
  2210. /// Compute the desired OpenMP runtime from the flag provided.
  2211. static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
  2212. const ArgList &Args) {
  2213. StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
  2214. const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
  2215. if (A)
  2216. RuntimeName = A->getValue();
  2217. auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
  2218. .Case("libomp", OMPRT_OMP)
  2219. .Case("libgomp", OMPRT_GOMP)
  2220. .Case("libiomp5", OMPRT_IOMP5)
  2221. .Default(OMPRT_Unknown);
  2222. if (RT == OMPRT_Unknown) {
  2223. if (A)
  2224. TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
  2225. << A->getOption().getName() << A->getValue();
  2226. else
  2227. // FIXME: We could use a nicer diagnostic here.
  2228. TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
  2229. }
  2230. return RT;
  2231. }
  2232. static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
  2233. const ArgList &Args) {
  2234. if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  2235. options::OPT_fno_openmp, false))
  2236. return;
  2237. switch (getOpenMPRuntime(TC, Args)) {
  2238. case OMPRT_OMP:
  2239. CmdArgs.push_back("-lomp");
  2240. break;
  2241. case OMPRT_GOMP:
  2242. CmdArgs.push_back("-lgomp");
  2243. break;
  2244. case OMPRT_IOMP5:
  2245. CmdArgs.push_back("-liomp5");
  2246. break;
  2247. case OMPRT_Unknown:
  2248. // Already diagnosed.
  2249. break;
  2250. }
  2251. }
  2252. static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
  2253. ArgStringList &CmdArgs, StringRef Sanitizer,
  2254. bool IsShared) {
  2255. // Static runtimes must be forced into executable, so we wrap them in
  2256. // whole-archive.
  2257. if (!IsShared)
  2258. CmdArgs.push_back("-whole-archive");
  2259. CmdArgs.push_back(getCompilerRTArgString(TC, Args, Sanitizer, IsShared));
  2260. if (!IsShared)
  2261. CmdArgs.push_back("-no-whole-archive");
  2262. }
  2263. // Tries to use a file with the list of dynamic symbols that need to be exported
  2264. // from the runtime library. Returns true if the file was found.
  2265. static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
  2266. ArgStringList &CmdArgs,
  2267. StringRef Sanitizer) {
  2268. SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
  2269. if (llvm::sys::fs::exists(SanRT + ".syms")) {
  2270. CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
  2271. return true;
  2272. }
  2273. return false;
  2274. }
  2275. static void linkSanitizerRuntimeDeps(const ToolChain &TC,
  2276. ArgStringList &CmdArgs) {
  2277. // Force linking against the system libraries sanitizers depends on
  2278. // (see PR15823 why this is necessary).
  2279. CmdArgs.push_back("--no-as-needed");
  2280. CmdArgs.push_back("-lpthread");
  2281. CmdArgs.push_back("-lrt");
  2282. CmdArgs.push_back("-lm");
  2283. // There's no libdl on FreeBSD.
  2284. if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
  2285. CmdArgs.push_back("-ldl");
  2286. }
  2287. static void
  2288. collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2289. SmallVectorImpl<StringRef> &SharedRuntimes,
  2290. SmallVectorImpl<StringRef> &StaticRuntimes,
  2291. SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
  2292. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  2293. // Collect shared runtimes.
  2294. if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
  2295. SharedRuntimes.push_back("asan");
  2296. }
  2297. // Collect static runtimes.
  2298. if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
  2299. // Don't link static runtimes into DSOs or if compiling for Android.
  2300. return;
  2301. }
  2302. if (SanArgs.needsAsanRt()) {
  2303. if (SanArgs.needsSharedAsanRt()) {
  2304. HelperStaticRuntimes.push_back("asan-preinit");
  2305. } else {
  2306. StaticRuntimes.push_back("asan");
  2307. if (SanArgs.linkCXXRuntimes())
  2308. StaticRuntimes.push_back("asan_cxx");
  2309. }
  2310. }
  2311. if (SanArgs.needsDfsanRt())
  2312. StaticRuntimes.push_back("dfsan");
  2313. if (SanArgs.needsLsanRt())
  2314. StaticRuntimes.push_back("lsan");
  2315. if (SanArgs.needsMsanRt()) {
  2316. StaticRuntimes.push_back("msan");
  2317. if (SanArgs.linkCXXRuntimes())
  2318. StaticRuntimes.push_back("msan_cxx");
  2319. }
  2320. if (SanArgs.needsTsanRt()) {
  2321. StaticRuntimes.push_back("tsan");
  2322. if (SanArgs.linkCXXRuntimes())
  2323. StaticRuntimes.push_back("tsan_cxx");
  2324. }
  2325. if (SanArgs.needsUbsanRt()) {
  2326. StaticRuntimes.push_back("ubsan_standalone");
  2327. if (SanArgs.linkCXXRuntimes())
  2328. StaticRuntimes.push_back("ubsan_standalone_cxx");
  2329. }
  2330. if (SanArgs.needsSafeStackRt())
  2331. StaticRuntimes.push_back("safestack");
  2332. }
  2333. // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
  2334. // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
  2335. static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2336. ArgStringList &CmdArgs) {
  2337. SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
  2338. HelperStaticRuntimes;
  2339. collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
  2340. HelperStaticRuntimes);
  2341. for (auto RT : SharedRuntimes)
  2342. addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
  2343. for (auto RT : HelperStaticRuntimes)
  2344. addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
  2345. bool AddExportDynamic = false;
  2346. for (auto RT : StaticRuntimes) {
  2347. addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
  2348. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  2349. }
  2350. // If there is a static runtime with no dynamic list, force all the symbols
  2351. // to be dynamic to be sure we export sanitizer interface functions.
  2352. if (AddExportDynamic)
  2353. CmdArgs.push_back("-export-dynamic");
  2354. return !StaticRuntimes.empty();
  2355. }
  2356. static bool areOptimizationsEnabled(const ArgList &Args) {
  2357. // Find the last -O arg and see if it is non-zero.
  2358. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2359. return !A->getOption().matches(options::OPT_O0);
  2360. // Defaults to -O0.
  2361. return false;
  2362. }
  2363. static bool shouldUseFramePointerForTarget(const ArgList &Args,
  2364. const llvm::Triple &Triple) {
  2365. switch (Triple.getArch()) {
  2366. case llvm::Triple::xcore:
  2367. case llvm::Triple::wasm32:
  2368. case llvm::Triple::wasm64:
  2369. // XCore never wants frame pointers, regardless of OS.
  2370. // WebAssembly never wants frame pointers.
  2371. return false;
  2372. default:
  2373. break;
  2374. }
  2375. if (Triple.isOSLinux()) {
  2376. switch (Triple.getArch()) {
  2377. // Don't use a frame pointer on linux if optimizing for certain targets.
  2378. case llvm::Triple::mips64:
  2379. case llvm::Triple::mips64el:
  2380. case llvm::Triple::mips:
  2381. case llvm::Triple::mipsel:
  2382. case llvm::Triple::systemz:
  2383. case llvm::Triple::x86:
  2384. case llvm::Triple::x86_64:
  2385. return !areOptimizationsEnabled(Args);
  2386. default:
  2387. return true;
  2388. }
  2389. }
  2390. if (Triple.isOSWindows()) {
  2391. switch (Triple.getArch()) {
  2392. case llvm::Triple::x86:
  2393. return !areOptimizationsEnabled(Args);
  2394. case llvm::Triple::arm:
  2395. case llvm::Triple::thumb:
  2396. // Windows on ARM builds with FPO disabled to aid fast stack walking
  2397. return true;
  2398. default:
  2399. // All other supported Windows ISAs use xdata unwind information, so frame
  2400. // pointers are not generally useful.
  2401. return false;
  2402. }
  2403. }
  2404. return true;
  2405. }
  2406. static bool shouldUseFramePointer(const ArgList &Args,
  2407. const llvm::Triple &Triple) {
  2408. if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
  2409. options::OPT_fomit_frame_pointer))
  2410. return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
  2411. return shouldUseFramePointerForTarget(Args, Triple);
  2412. }
  2413. static bool shouldUseLeafFramePointer(const ArgList &Args,
  2414. const llvm::Triple &Triple) {
  2415. if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
  2416. options::OPT_momit_leaf_frame_pointer))
  2417. return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
  2418. if (Triple.isPS4CPU())
  2419. return false;
  2420. return shouldUseFramePointerForTarget(Args, Triple);
  2421. }
  2422. /// Add a CC1 option to specify the debug compilation directory.
  2423. static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
  2424. SmallString<128> cwd;
  2425. if (!llvm::sys::fs::current_path(cwd)) {
  2426. CmdArgs.push_back("-fdebug-compilation-dir");
  2427. CmdArgs.push_back(Args.MakeArgString(cwd));
  2428. }
  2429. }
  2430. static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
  2431. Arg *FinalOutput = Args.getLastArg(options::OPT_o);
  2432. if (FinalOutput && Args.hasArg(options::OPT_c)) {
  2433. SmallString<128> T(FinalOutput->getValue());
  2434. llvm::sys::path::replace_extension(T, "dwo");
  2435. return Args.MakeArgString(T);
  2436. } else {
  2437. // Use the compilation dir.
  2438. SmallString<128> T(
  2439. Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
  2440. SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
  2441. llvm::sys::path::replace_extension(F, "dwo");
  2442. T += F;
  2443. return Args.MakeArgString(F);
  2444. }
  2445. }
  2446. static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
  2447. const JobAction &JA, const ArgList &Args,
  2448. const InputInfo &Output, const char *OutFile) {
  2449. ArgStringList ExtractArgs;
  2450. ExtractArgs.push_back("--extract-dwo");
  2451. ArgStringList StripArgs;
  2452. StripArgs.push_back("--strip-dwo");
  2453. // Grabbing the output of the earlier compile step.
  2454. StripArgs.push_back(Output.getFilename());
  2455. ExtractArgs.push_back(Output.getFilename());
  2456. ExtractArgs.push_back(OutFile);
  2457. const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
  2458. InputInfo II(Output.getFilename(), types::TY_Object, Output.getFilename());
  2459. // First extract the dwo sections.
  2460. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
  2461. // Then remove them from the original .o file.
  2462. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
  2463. }
  2464. /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
  2465. /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
  2466. static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
  2467. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  2468. if (A->getOption().matches(options::OPT_O4) ||
  2469. A->getOption().matches(options::OPT_Ofast))
  2470. return true;
  2471. if (A->getOption().matches(options::OPT_O0))
  2472. return false;
  2473. assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
  2474. // Vectorize -Os.
  2475. StringRef S(A->getValue());
  2476. if (S == "s")
  2477. return true;
  2478. // Don't vectorize -Oz, unless it's the slp vectorizer.
  2479. if (S == "z")
  2480. return isSlpVec;
  2481. unsigned OptLevel = 0;
  2482. if (S.getAsInteger(10, OptLevel))
  2483. return false;
  2484. return OptLevel > 1;
  2485. }
  2486. return false;
  2487. }
  2488. /// Add -x lang to \p CmdArgs for \p Input.
  2489. static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
  2490. ArgStringList &CmdArgs) {
  2491. // When using -verify-pch, we don't want to provide the type
  2492. // 'precompiled-header' if it was inferred from the file extension
  2493. if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
  2494. return;
  2495. CmdArgs.push_back("-x");
  2496. if (Args.hasArg(options::OPT_rewrite_objc))
  2497. CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
  2498. else
  2499. CmdArgs.push_back(types::getTypeName(Input.getType()));
  2500. }
  2501. static VersionTuple getMSCompatibilityVersion(unsigned Version) {
  2502. if (Version < 100)
  2503. return VersionTuple(Version);
  2504. if (Version < 10000)
  2505. return VersionTuple(Version / 100, Version % 100);
  2506. unsigned Build = 0, Factor = 1;
  2507. for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
  2508. Build = Build + (Version % 10) * Factor;
  2509. return VersionTuple(Version / 100, Version % 100, Build);
  2510. }
  2511. // Claim options we don't want to warn if they are unused. We do this for
  2512. // options that build systems might add but are unused when assembling or only
  2513. // running the preprocessor for example.
  2514. static void claimNoWarnArgs(const ArgList &Args) {
  2515. // Don't warn about unused -f(no-)?lto. This can happen when we're
  2516. // preprocessing, precompiling or assembling.
  2517. Args.ClaimAllArgs(options::OPT_flto);
  2518. Args.ClaimAllArgs(options::OPT_fno_lto);
  2519. }
  2520. static void appendUserToPath(SmallVectorImpl<char> &Result) {
  2521. #ifdef LLVM_ON_UNIX
  2522. const char *Username = getenv("LOGNAME");
  2523. #else
  2524. const char *Username = getenv("USERNAME");
  2525. #endif
  2526. if (Username) {
  2527. // Validate that LoginName can be used in a path, and get its length.
  2528. size_t Len = 0;
  2529. for (const char *P = Username; *P; ++P, ++Len) {
  2530. if (!isAlphanumeric(*P) && *P != '_') {
  2531. Username = nullptr;
  2532. break;
  2533. }
  2534. }
  2535. if (Username && Len > 0) {
  2536. Result.append(Username, Username + Len);
  2537. return;
  2538. }
  2539. }
  2540. // Fallback to user id.
  2541. #ifdef LLVM_ON_UNIX
  2542. std::string UID = llvm::utostr(getuid());
  2543. #else
  2544. // FIXME: Windows seems to have an 'SID' that might work.
  2545. std::string UID = "9999";
  2546. #endif
  2547. Result.append(UID.begin(), UID.end());
  2548. }
  2549. VersionTuple visualstudio::getMSVCVersion(const Driver *D,
  2550. const llvm::Triple &Triple,
  2551. const llvm::opt::ArgList &Args,
  2552. bool IsWindowsMSVC) {
  2553. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  2554. IsWindowsMSVC) ||
  2555. Args.hasArg(options::OPT_fmsc_version) ||
  2556. Args.hasArg(options::OPT_fms_compatibility_version)) {
  2557. const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
  2558. const Arg *MSCompatibilityVersion =
  2559. Args.getLastArg(options::OPT_fms_compatibility_version);
  2560. if (MSCVersion && MSCompatibilityVersion) {
  2561. if (D)
  2562. D->Diag(diag::err_drv_argument_not_allowed_with)
  2563. << MSCVersion->getAsString(Args)
  2564. << MSCompatibilityVersion->getAsString(Args);
  2565. return VersionTuple();
  2566. }
  2567. if (MSCompatibilityVersion) {
  2568. VersionTuple MSVT;
  2569. if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
  2570. D->Diag(diag::err_drv_invalid_value)
  2571. << MSCompatibilityVersion->getAsString(Args)
  2572. << MSCompatibilityVersion->getValue();
  2573. return MSVT;
  2574. }
  2575. if (MSCVersion) {
  2576. unsigned Version = 0;
  2577. if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
  2578. D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
  2579. << MSCVersion->getValue();
  2580. return getMSCompatibilityVersion(Version);
  2581. }
  2582. unsigned Major, Minor, Micro;
  2583. Triple.getEnvironmentVersion(Major, Minor, Micro);
  2584. if (Major || Minor || Micro)
  2585. return VersionTuple(Major, Minor, Micro);
  2586. return VersionTuple(18);
  2587. }
  2588. return VersionTuple();
  2589. }
  2590. static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
  2591. const InputInfo &Output, const ArgList &Args,
  2592. ArgStringList &CmdArgs) {
  2593. auto *ProfileGenerateArg = Args.getLastArg(
  2594. options::OPT_fprofile_instr_generate,
  2595. options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
  2596. options::OPT_fprofile_generate_EQ,
  2597. options::OPT_fno_profile_instr_generate);
  2598. if (ProfileGenerateArg &&
  2599. ProfileGenerateArg->getOption().matches(
  2600. options::OPT_fno_profile_instr_generate))
  2601. ProfileGenerateArg = nullptr;
  2602. auto *ProfileUseArg = Args.getLastArg(
  2603. options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
  2604. options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
  2605. options::OPT_fno_profile_instr_use);
  2606. if (ProfileUseArg &&
  2607. ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
  2608. ProfileUseArg = nullptr;
  2609. if (ProfileGenerateArg && ProfileUseArg)
  2610. D.Diag(diag::err_drv_argument_not_allowed_with)
  2611. << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
  2612. if (ProfileGenerateArg) {
  2613. if (ProfileGenerateArg->getOption().matches(
  2614. options::OPT_fprofile_instr_generate_EQ))
  2615. ProfileGenerateArg->render(Args, CmdArgs);
  2616. else if (ProfileGenerateArg->getOption().matches(
  2617. options::OPT_fprofile_generate_EQ)) {
  2618. SmallString<128> Path(ProfileGenerateArg->getValue());
  2619. llvm::sys::path::append(Path, "default.profraw");
  2620. CmdArgs.push_back(
  2621. Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
  2622. } else
  2623. Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
  2624. }
  2625. if (ProfileUseArg) {
  2626. if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
  2627. ProfileUseArg->render(Args, CmdArgs);
  2628. else if ((ProfileUseArg->getOption().matches(
  2629. options::OPT_fprofile_use_EQ) ||
  2630. ProfileUseArg->getOption().matches(
  2631. options::OPT_fprofile_instr_use))) {
  2632. SmallString<128> Path(
  2633. ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
  2634. if (Path.empty() || llvm::sys::fs::is_directory(Path))
  2635. llvm::sys::path::append(Path, "default.profdata");
  2636. CmdArgs.push_back(
  2637. Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
  2638. }
  2639. }
  2640. if (Args.hasArg(options::OPT_ftest_coverage) ||
  2641. Args.hasArg(options::OPT_coverage))
  2642. CmdArgs.push_back("-femit-coverage-notes");
  2643. if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  2644. false) ||
  2645. Args.hasArg(options::OPT_coverage))
  2646. CmdArgs.push_back("-femit-coverage-data");
  2647. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  2648. options::OPT_fno_coverage_mapping, false) &&
  2649. !ProfileGenerateArg)
  2650. D.Diag(diag::err_drv_argument_only_allowed_with)
  2651. << "-fcoverage-mapping"
  2652. << "-fprofile-instr-generate";
  2653. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  2654. options::OPT_fno_coverage_mapping, false))
  2655. CmdArgs.push_back("-fcoverage-mapping");
  2656. if (C.getArgs().hasArg(options::OPT_c) ||
  2657. C.getArgs().hasArg(options::OPT_S)) {
  2658. if (Output.isFilename()) {
  2659. CmdArgs.push_back("-coverage-file");
  2660. SmallString<128> CoverageFilename;
  2661. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
  2662. CoverageFilename = FinalOutput->getValue();
  2663. } else {
  2664. CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
  2665. }
  2666. if (llvm::sys::path::is_relative(CoverageFilename)) {
  2667. SmallString<128> Pwd;
  2668. if (!llvm::sys::fs::current_path(Pwd)) {
  2669. llvm::sys::path::append(Pwd, CoverageFilename);
  2670. CoverageFilename.swap(Pwd);
  2671. }
  2672. }
  2673. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  2674. }
  2675. }
  2676. }
  2677. /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
  2678. /// smooshes them together with platform defaults, to decide whether
  2679. /// this compile should be using PIC mode or not. Returns a tuple of
  2680. /// (RelocationModel, PICLevel, IsPIE).
  2681. static std::tuple<llvm::Reloc::Model, unsigned, bool>
  2682. ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
  2683. const ArgList &Args) {
  2684. // FIXME: why does this code...and so much everywhere else, use both
  2685. // ToolChain.getTriple() and Triple?
  2686. bool PIE = ToolChain.isPIEDefault();
  2687. bool PIC = PIE || ToolChain.isPICDefault();
  2688. bool IsPICLevelTwo = PIC;
  2689. bool KernelOrKext =
  2690. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  2691. // Android-specific defaults for PIC/PIE
  2692. if (ToolChain.getTriple().isAndroid()) {
  2693. switch (ToolChain.getArch()) {
  2694. case llvm::Triple::arm:
  2695. case llvm::Triple::armeb:
  2696. case llvm::Triple::thumb:
  2697. case llvm::Triple::thumbeb:
  2698. case llvm::Triple::aarch64:
  2699. case llvm::Triple::mips:
  2700. case llvm::Triple::mipsel:
  2701. case llvm::Triple::mips64:
  2702. case llvm::Triple::mips64el:
  2703. PIC = true; // "-fpic"
  2704. break;
  2705. case llvm::Triple::x86:
  2706. case llvm::Triple::x86_64:
  2707. PIC = true; // "-fPIC"
  2708. IsPICLevelTwo = true;
  2709. break;
  2710. default:
  2711. break;
  2712. }
  2713. }
  2714. // OpenBSD-specific defaults for PIE
  2715. if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
  2716. switch (ToolChain.getArch()) {
  2717. case llvm::Triple::mips64:
  2718. case llvm::Triple::mips64el:
  2719. case llvm::Triple::sparcel:
  2720. case llvm::Triple::x86:
  2721. case llvm::Triple::x86_64:
  2722. IsPICLevelTwo = false; // "-fpie"
  2723. break;
  2724. case llvm::Triple::ppc:
  2725. case llvm::Triple::sparc:
  2726. case llvm::Triple::sparcv9:
  2727. IsPICLevelTwo = true; // "-fPIE"
  2728. break;
  2729. default:
  2730. break;
  2731. }
  2732. }
  2733. // The last argument relating to either PIC or PIE wins, and no
  2734. // other argument is used. If the last argument is any flavor of the
  2735. // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
  2736. // option implicitly enables PIC at the same level.
  2737. Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
  2738. options::OPT_fpic, options::OPT_fno_pic,
  2739. options::OPT_fPIE, options::OPT_fno_PIE,
  2740. options::OPT_fpie, options::OPT_fno_pie);
  2741. // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
  2742. // is forced, then neither PIC nor PIE flags will have no effect.
  2743. if (!ToolChain.isPICDefaultForced()) {
  2744. if (LastPICArg) {
  2745. Option O = LastPICArg->getOption();
  2746. if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
  2747. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
  2748. PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
  2749. PIC =
  2750. PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
  2751. IsPICLevelTwo =
  2752. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
  2753. } else {
  2754. PIE = PIC = false;
  2755. }
  2756. }
  2757. }
  2758. // Introduce a Darwin-specific hack. If the default is PIC, but the
  2759. // PIC level would've been set to level 1, force it back to level 2
  2760. // PIC instead. This matches the behavior of Darwin GCC (based on
  2761. // chandlerc's informal testing in 2012).
  2762. if (PIC && ToolChain.getTriple().isOSDarwin())
  2763. IsPICLevelTwo |= ToolChain.isPICDefault();
  2764. // This kernel flags are a trump-card: they will disable PIC/PIE
  2765. // generation, independent of the argument order.
  2766. if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)))
  2767. PIC = PIE = false;
  2768. if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
  2769. // This is a very special mode. It trumps the other modes, almost no one
  2770. // uses it, and it isn't even valid on any OS but Darwin.
  2771. if (!ToolChain.getTriple().isOSDarwin())
  2772. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  2773. << A->getSpelling() << ToolChain.getTriple().str();
  2774. // FIXME: Warn when this flag trumps some other PIC or PIE flag.
  2775. // Only a forced PIC mode can cause the actual compile to have PIC defines
  2776. // etc., no flags are sufficient. This behavior was selected to closely
  2777. // match that of llvm-gcc and Apple GCC before that.
  2778. PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
  2779. return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
  2780. }
  2781. if (PIC)
  2782. return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
  2783. return std::make_tuple(llvm::Reloc::Static, 0, false);
  2784. }
  2785. static const char *RelocationModelName(llvm::Reloc::Model Model) {
  2786. switch (Model) {
  2787. case llvm::Reloc::Default:
  2788. return nullptr;
  2789. case llvm::Reloc::Static:
  2790. return "static";
  2791. case llvm::Reloc::PIC_:
  2792. return "pic";
  2793. case llvm::Reloc::DynamicNoPIC:
  2794. return "dynamic-no-pic";
  2795. }
  2796. llvm_unreachable("Unknown Reloc::Model kind");
  2797. }
  2798. static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
  2799. ArgStringList &CmdArgs) {
  2800. llvm::Reloc::Model RelocationModel;
  2801. unsigned PICLevel;
  2802. bool IsPIE;
  2803. std::tie(RelocationModel, PICLevel, IsPIE) =
  2804. ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
  2805. if (RelocationModel != llvm::Reloc::Static)
  2806. CmdArgs.push_back("-KPIC");
  2807. }
  2808. void Clang::ConstructJob(Compilation &C, const JobAction &JA,
  2809. const InputInfo &Output, const InputInfoList &Inputs,
  2810. const ArgList &Args, const char *LinkingOutput) const {
  2811. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  2812. const llvm::Triple Triple(TripleStr);
  2813. bool KernelOrKext =
  2814. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  2815. const Driver &D = getToolChain().getDriver();
  2816. ArgStringList CmdArgs;
  2817. bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
  2818. bool IsWindowsCygnus =
  2819. getToolChain().getTriple().isWindowsCygwinEnvironment();
  2820. bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
  2821. // Check number of inputs for sanity. We need at least one input.
  2822. assert(Inputs.size() >= 1 && "Must have at least one input.");
  2823. const InputInfo &Input = Inputs[0];
  2824. // CUDA compilation may have multiple inputs (source file + results of
  2825. // device-side compilations). All other jobs are expected to have exactly one
  2826. // input.
  2827. bool IsCuda = types::isCuda(Input.getType());
  2828. assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
  2829. // Invoke ourselves in -cc1 mode.
  2830. //
  2831. // FIXME: Implement custom jobs for internal actions.
  2832. CmdArgs.push_back("-cc1");
  2833. // Add the "effective" target triple.
  2834. CmdArgs.push_back("-triple");
  2835. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  2836. if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
  2837. Triple.getArch() == llvm::Triple::thumb)) {
  2838. unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
  2839. unsigned Version;
  2840. Triple.getArchName().substr(Offset).getAsInteger(10, Version);
  2841. if (Version < 7)
  2842. D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
  2843. << TripleStr;
  2844. }
  2845. // Push all default warning arguments that are specific to
  2846. // the given target. These come before user provided warning options
  2847. // are provided.
  2848. getToolChain().addClangWarningOptions(CmdArgs);
  2849. // Select the appropriate action.
  2850. RewriteKind rewriteKind = RK_None;
  2851. if (isa<AnalyzeJobAction>(JA)) {
  2852. assert(JA.getType() == types::TY_Plist && "Invalid output type.");
  2853. CmdArgs.push_back("-analyze");
  2854. } else if (isa<MigrateJobAction>(JA)) {
  2855. CmdArgs.push_back("-migrate");
  2856. } else if (isa<PreprocessJobAction>(JA)) {
  2857. if (Output.getType() == types::TY_Dependencies)
  2858. CmdArgs.push_back("-Eonly");
  2859. else {
  2860. CmdArgs.push_back("-E");
  2861. if (Args.hasArg(options::OPT_rewrite_objc) &&
  2862. !Args.hasArg(options::OPT_g_Group))
  2863. CmdArgs.push_back("-P");
  2864. }
  2865. } else if (isa<AssembleJobAction>(JA)) {
  2866. CmdArgs.push_back("-emit-obj");
  2867. CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
  2868. // Also ignore explicit -force_cpusubtype_ALL option.
  2869. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  2870. } else if (isa<PrecompileJobAction>(JA)) {
  2871. // Use PCH if the user requested it.
  2872. bool UsePCH = D.CCCUsePCH;
  2873. if (JA.getType() == types::TY_Nothing)
  2874. CmdArgs.push_back("-fsyntax-only");
  2875. else if (UsePCH)
  2876. CmdArgs.push_back("-emit-pch");
  2877. else
  2878. CmdArgs.push_back("-emit-pth");
  2879. } else if (isa<VerifyPCHJobAction>(JA)) {
  2880. CmdArgs.push_back("-verify-pch");
  2881. } else {
  2882. assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
  2883. "Invalid action for clang tool.");
  2884. if (JA.getType() == types::TY_LTO_IR || JA.getType() == types::TY_LTO_BC) {
  2885. CmdArgs.push_back("-flto");
  2886. }
  2887. if (JA.getType() == types::TY_Nothing) {
  2888. CmdArgs.push_back("-fsyntax-only");
  2889. } else if (JA.getType() == types::TY_LLVM_IR ||
  2890. JA.getType() == types::TY_LTO_IR) {
  2891. CmdArgs.push_back("-emit-llvm");
  2892. } else if (JA.getType() == types::TY_LLVM_BC ||
  2893. JA.getType() == types::TY_LTO_BC) {
  2894. CmdArgs.push_back("-emit-llvm-bc");
  2895. } else if (JA.getType() == types::TY_PP_Asm) {
  2896. CmdArgs.push_back("-S");
  2897. } else if (JA.getType() == types::TY_AST) {
  2898. CmdArgs.push_back("-emit-pch");
  2899. } else if (JA.getType() == types::TY_ModuleFile) {
  2900. CmdArgs.push_back("-module-file-info");
  2901. } else if (JA.getType() == types::TY_RewrittenObjC) {
  2902. CmdArgs.push_back("-rewrite-objc");
  2903. rewriteKind = RK_NonFragile;
  2904. } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
  2905. CmdArgs.push_back("-rewrite-objc");
  2906. rewriteKind = RK_Fragile;
  2907. } else {
  2908. assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
  2909. }
  2910. // Preserve use-list order by default when emitting bitcode, so that
  2911. // loading the bitcode up in 'opt' or 'llc' and running passes gives the
  2912. // same result as running passes here. For LTO, we don't need to preserve
  2913. // the use-list order, since serialization to bitcode is part of the flow.
  2914. if (JA.getType() == types::TY_LLVM_BC)
  2915. CmdArgs.push_back("-emit-llvm-uselists");
  2916. }
  2917. // We normally speed up the clang process a bit by skipping destructors at
  2918. // exit, but when we're generating diagnostics we can rely on some of the
  2919. // cleanup.
  2920. if (!C.isForDiagnostics())
  2921. CmdArgs.push_back("-disable-free");
  2922. // Disable the verification pass in -asserts builds.
  2923. #ifdef NDEBUG
  2924. CmdArgs.push_back("-disable-llvm-verifier");
  2925. #endif
  2926. // Set the main file name, so that debug info works even with
  2927. // -save-temps.
  2928. CmdArgs.push_back("-main-file-name");
  2929. CmdArgs.push_back(getBaseInputName(Args, Input));
  2930. // Some flags which affect the language (via preprocessor
  2931. // defines).
  2932. if (Args.hasArg(options::OPT_static))
  2933. CmdArgs.push_back("-static-define");
  2934. if (isa<AnalyzeJobAction>(JA)) {
  2935. // Enable region store model by default.
  2936. CmdArgs.push_back("-analyzer-store=region");
  2937. // Treat blocks as analysis entry points.
  2938. CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
  2939. CmdArgs.push_back("-analyzer-eagerly-assume");
  2940. // Add default argument set.
  2941. if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
  2942. CmdArgs.push_back("-analyzer-checker=core");
  2943. if (!IsWindowsMSVC)
  2944. CmdArgs.push_back("-analyzer-checker=unix");
  2945. if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
  2946. CmdArgs.push_back("-analyzer-checker=osx");
  2947. CmdArgs.push_back("-analyzer-checker=deadcode");
  2948. if (types::isCXX(Input.getType()))
  2949. CmdArgs.push_back("-analyzer-checker=cplusplus");
  2950. // Enable the following experimental checkers for testing.
  2951. CmdArgs.push_back(
  2952. "-analyzer-checker=security.insecureAPI.UncheckedReturn");
  2953. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
  2954. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
  2955. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
  2956. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
  2957. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
  2958. // Default nullability checks.
  2959. CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
  2960. CmdArgs.push_back(
  2961. "-analyzer-checker=nullability.NullReturnedFromNonnull");
  2962. }
  2963. // Set the output format. The default is plist, for (lame) historical
  2964. // reasons.
  2965. CmdArgs.push_back("-analyzer-output");
  2966. if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
  2967. CmdArgs.push_back(A->getValue());
  2968. else
  2969. CmdArgs.push_back("plist");
  2970. // Disable the presentation of standard compiler warnings when
  2971. // using --analyze. We only want to show static analyzer diagnostics
  2972. // or frontend errors.
  2973. CmdArgs.push_back("-w");
  2974. // Add -Xanalyzer arguments when running as analyzer.
  2975. Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
  2976. }
  2977. CheckCodeGenerationOptions(D, Args);
  2978. llvm::Reloc::Model RelocationModel;
  2979. unsigned PICLevel;
  2980. bool IsPIE;
  2981. std::tie(RelocationModel, PICLevel, IsPIE) =
  2982. ParsePICArgs(getToolChain(), Triple, Args);
  2983. const char *RMName = RelocationModelName(RelocationModel);
  2984. if (RMName) {
  2985. CmdArgs.push_back("-mrelocation-model");
  2986. CmdArgs.push_back(RMName);
  2987. }
  2988. if (PICLevel > 0) {
  2989. CmdArgs.push_back("-pic-level");
  2990. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  2991. if (IsPIE) {
  2992. CmdArgs.push_back("-pie-level");
  2993. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  2994. }
  2995. }
  2996. CmdArgs.push_back("-mthread-model");
  2997. if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
  2998. CmdArgs.push_back(A->getValue());
  2999. else
  3000. CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
  3001. Args.AddLastArg(CmdArgs, options::OPT_fveclib);
  3002. if (!Args.hasFlag(options::OPT_fmerge_all_constants,
  3003. options::OPT_fno_merge_all_constants))
  3004. CmdArgs.push_back("-fno-merge-all-constants");
  3005. // LLVM Code Generator Options.
  3006. if (Args.hasArg(options::OPT_frewrite_map_file) ||
  3007. Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
  3008. for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
  3009. options::OPT_frewrite_map_file_EQ)) {
  3010. CmdArgs.push_back("-frewrite-map-file");
  3011. CmdArgs.push_back(A->getValue());
  3012. A->claim();
  3013. }
  3014. }
  3015. if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
  3016. StringRef v = A->getValue();
  3017. CmdArgs.push_back("-mllvm");
  3018. CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
  3019. A->claim();
  3020. }
  3021. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  3022. CmdArgs.push_back("-mregparm");
  3023. CmdArgs.push_back(A->getValue());
  3024. }
  3025. if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
  3026. options::OPT_freg_struct_return)) {
  3027. if (getToolChain().getArch() != llvm::Triple::x86) {
  3028. D.Diag(diag::err_drv_unsupported_opt_for_target)
  3029. << A->getSpelling() << getToolChain().getTriple().str();
  3030. } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
  3031. CmdArgs.push_back("-fpcc-struct-return");
  3032. } else {
  3033. assert(A->getOption().matches(options::OPT_freg_struct_return));
  3034. CmdArgs.push_back("-freg-struct-return");
  3035. }
  3036. }
  3037. if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
  3038. CmdArgs.push_back("-mrtd");
  3039. if (shouldUseFramePointer(Args, getToolChain().getTriple()))
  3040. CmdArgs.push_back("-mdisable-fp-elim");
  3041. if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
  3042. options::OPT_fno_zero_initialized_in_bss))
  3043. CmdArgs.push_back("-mno-zero-initialized-in-bss");
  3044. bool OFastEnabled = isOptimizationLevelFast(Args);
  3045. // If -Ofast is the optimization level, then -fstrict-aliasing should be
  3046. // enabled. This alias option is being used to simplify the hasFlag logic.
  3047. OptSpecifier StrictAliasingAliasOption =
  3048. OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
  3049. // We turn strict aliasing off by default if we're in CL mode, since MSVC
  3050. // doesn't do any TBAA.
  3051. bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
  3052. if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
  3053. options::OPT_fno_strict_aliasing, TBAAOnByDefault))
  3054. CmdArgs.push_back("-relaxed-aliasing");
  3055. if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
  3056. options::OPT_fno_struct_path_tbaa))
  3057. CmdArgs.push_back("-no-struct-path-tbaa");
  3058. if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
  3059. false))
  3060. CmdArgs.push_back("-fstrict-enums");
  3061. if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
  3062. options::OPT_fno_strict_vtable_pointers,
  3063. false))
  3064. CmdArgs.push_back("-fstrict-vtable-pointers");
  3065. if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
  3066. options::OPT_fno_optimize_sibling_calls))
  3067. CmdArgs.push_back("-mdisable-tail-calls");
  3068. // Handle segmented stacks.
  3069. if (Args.hasArg(options::OPT_fsplit_stack))
  3070. CmdArgs.push_back("-split-stacks");
  3071. // If -Ofast is the optimization level, then -ffast-math should be enabled.
  3072. // This alias option is being used to simplify the getLastArg logic.
  3073. OptSpecifier FastMathAliasOption =
  3074. OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
  3075. // Handle various floating point optimization flags, mapping them to the
  3076. // appropriate LLVM code generation flags. The pattern for all of these is to
  3077. // default off the codegen optimizations, and if any flag enables them and no
  3078. // flag disables them after the flag enabling them, enable the codegen
  3079. // optimization. This is complicated by several "umbrella" flags.
  3080. if (Arg *A = Args.getLastArg(
  3081. options::OPT_ffast_math, FastMathAliasOption,
  3082. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3083. options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
  3084. options::OPT_fno_honor_infinities))
  3085. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3086. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3087. A->getOption().getID() != options::OPT_fhonor_infinities)
  3088. CmdArgs.push_back("-menable-no-infs");
  3089. if (Arg *A = Args.getLastArg(
  3090. options::OPT_ffast_math, FastMathAliasOption,
  3091. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3092. options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
  3093. options::OPT_fno_honor_nans))
  3094. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3095. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3096. A->getOption().getID() != options::OPT_fhonor_nans)
  3097. CmdArgs.push_back("-menable-no-nans");
  3098. // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
  3099. bool MathErrno = getToolChain().IsMathErrnoDefault();
  3100. if (Arg *A =
  3101. Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3102. options::OPT_fno_fast_math, options::OPT_fmath_errno,
  3103. options::OPT_fno_math_errno)) {
  3104. // Turning on -ffast_math (with either flag) removes the need for MathErrno.
  3105. // However, turning *off* -ffast_math merely restores the toolchain default
  3106. // (which may be false).
  3107. if (A->getOption().getID() == options::OPT_fno_math_errno ||
  3108. A->getOption().getID() == options::OPT_ffast_math ||
  3109. A->getOption().getID() == options::OPT_Ofast)
  3110. MathErrno = false;
  3111. else if (A->getOption().getID() == options::OPT_fmath_errno)
  3112. MathErrno = true;
  3113. }
  3114. if (MathErrno)
  3115. CmdArgs.push_back("-fmath-errno");
  3116. // There are several flags which require disabling very specific
  3117. // optimizations. Any of these being disabled forces us to turn off the
  3118. // entire set of LLVM optimizations, so collect them through all the flag
  3119. // madness.
  3120. bool AssociativeMath = false;
  3121. if (Arg *A = Args.getLastArg(
  3122. options::OPT_ffast_math, FastMathAliasOption,
  3123. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3124. options::OPT_fno_unsafe_math_optimizations,
  3125. options::OPT_fassociative_math, options::OPT_fno_associative_math))
  3126. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3127. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3128. A->getOption().getID() != options::OPT_fno_associative_math)
  3129. AssociativeMath = true;
  3130. bool ReciprocalMath = false;
  3131. if (Arg *A = Args.getLastArg(
  3132. options::OPT_ffast_math, FastMathAliasOption,
  3133. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3134. options::OPT_fno_unsafe_math_optimizations,
  3135. options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
  3136. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3137. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3138. A->getOption().getID() != options::OPT_fno_reciprocal_math)
  3139. ReciprocalMath = true;
  3140. bool SignedZeros = true;
  3141. if (Arg *A = Args.getLastArg(
  3142. options::OPT_ffast_math, FastMathAliasOption,
  3143. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3144. options::OPT_fno_unsafe_math_optimizations,
  3145. options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
  3146. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3147. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3148. A->getOption().getID() != options::OPT_fsigned_zeros)
  3149. SignedZeros = false;
  3150. bool TrappingMath = true;
  3151. if (Arg *A = Args.getLastArg(
  3152. options::OPT_ffast_math, FastMathAliasOption,
  3153. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3154. options::OPT_fno_unsafe_math_optimizations,
  3155. options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
  3156. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3157. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3158. A->getOption().getID() != options::OPT_ftrapping_math)
  3159. TrappingMath = false;
  3160. if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
  3161. !TrappingMath)
  3162. CmdArgs.push_back("-menable-unsafe-fp-math");
  3163. if (!SignedZeros)
  3164. CmdArgs.push_back("-fno-signed-zeros");
  3165. if (ReciprocalMath)
  3166. CmdArgs.push_back("-freciprocal-math");
  3167. // Validate and pass through -fp-contract option.
  3168. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3169. options::OPT_fno_fast_math,
  3170. options::OPT_ffp_contract)) {
  3171. if (A->getOption().getID() == options::OPT_ffp_contract) {
  3172. StringRef Val = A->getValue();
  3173. if (Val == "fast" || Val == "on" || Val == "off") {
  3174. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
  3175. } else {
  3176. D.Diag(diag::err_drv_unsupported_option_argument)
  3177. << A->getOption().getName() << Val;
  3178. }
  3179. } else if (A->getOption().matches(options::OPT_ffast_math) ||
  3180. (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
  3181. // If fast-math is set then set the fp-contract mode to fast.
  3182. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
  3183. }
  3184. }
  3185. ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
  3186. // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
  3187. // and if we find them, tell the frontend to provide the appropriate
  3188. // preprocessor macros. This is distinct from enabling any optimizations as
  3189. // these options induce language changes which must survive serialization
  3190. // and deserialization, etc.
  3191. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3192. options::OPT_fno_fast_math))
  3193. if (!A->getOption().matches(options::OPT_fno_fast_math))
  3194. CmdArgs.push_back("-ffast-math");
  3195. if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
  3196. options::OPT_fno_fast_math))
  3197. if (A->getOption().matches(options::OPT_ffinite_math_only))
  3198. CmdArgs.push_back("-ffinite-math-only");
  3199. // Decide whether to use verbose asm. Verbose assembly is the default on
  3200. // toolchains which have the integrated assembler on by default.
  3201. bool IsIntegratedAssemblerDefault =
  3202. getToolChain().IsIntegratedAssemblerDefault();
  3203. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  3204. IsIntegratedAssemblerDefault) ||
  3205. Args.hasArg(options::OPT_dA))
  3206. CmdArgs.push_back("-masm-verbose");
  3207. if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
  3208. IsIntegratedAssemblerDefault))
  3209. CmdArgs.push_back("-no-integrated-as");
  3210. if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
  3211. CmdArgs.push_back("-mdebug-pass");
  3212. CmdArgs.push_back("Structure");
  3213. }
  3214. if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
  3215. CmdArgs.push_back("-mdebug-pass");
  3216. CmdArgs.push_back("Arguments");
  3217. }
  3218. // Enable -mconstructor-aliases except on darwin, where we have to
  3219. // work around a linker bug; see <rdar://problem/7651567>.
  3220. if (!getToolChain().getTriple().isOSDarwin())
  3221. CmdArgs.push_back("-mconstructor-aliases");
  3222. // Darwin's kernel doesn't support guard variables; just die if we
  3223. // try to use them.
  3224. if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
  3225. CmdArgs.push_back("-fforbid-guard-variables");
  3226. if (Args.hasArg(options::OPT_mms_bitfields)) {
  3227. CmdArgs.push_back("-mms-bitfields");
  3228. }
  3229. // This is a coarse approximation of what llvm-gcc actually does, both
  3230. // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
  3231. // complicated ways.
  3232. bool AsynchronousUnwindTables =
  3233. Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
  3234. options::OPT_fno_asynchronous_unwind_tables,
  3235. (getToolChain().IsUnwindTablesDefault() ||
  3236. getToolChain().getSanitizerArgs().needsUnwindTables()) &&
  3237. !KernelOrKext);
  3238. if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
  3239. AsynchronousUnwindTables))
  3240. CmdArgs.push_back("-munwind-tables");
  3241. getToolChain().addClangTargetOptions(Args, CmdArgs);
  3242. if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
  3243. CmdArgs.push_back("-mlimit-float-precision");
  3244. CmdArgs.push_back(A->getValue());
  3245. }
  3246. // FIXME: Handle -mtune=.
  3247. (void)Args.hasArg(options::OPT_mtune_EQ);
  3248. if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
  3249. CmdArgs.push_back("-mcode-model");
  3250. CmdArgs.push_back(A->getValue());
  3251. }
  3252. // Add the target cpu
  3253. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
  3254. if (!CPU.empty()) {
  3255. CmdArgs.push_back("-target-cpu");
  3256. CmdArgs.push_back(Args.MakeArgString(CPU));
  3257. }
  3258. if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
  3259. CmdArgs.push_back("-mfpmath");
  3260. CmdArgs.push_back(A->getValue());
  3261. }
  3262. // Add the target features
  3263. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
  3264. // Add target specific flags.
  3265. switch (getToolChain().getArch()) {
  3266. default:
  3267. break;
  3268. case llvm::Triple::arm:
  3269. case llvm::Triple::armeb:
  3270. case llvm::Triple::thumb:
  3271. case llvm::Triple::thumbeb:
  3272. // Use the effective triple, which takes into account the deployment target.
  3273. AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
  3274. break;
  3275. case llvm::Triple::aarch64:
  3276. case llvm::Triple::aarch64_be:
  3277. AddAArch64TargetArgs(Args, CmdArgs);
  3278. break;
  3279. case llvm::Triple::mips:
  3280. case llvm::Triple::mipsel:
  3281. case llvm::Triple::mips64:
  3282. case llvm::Triple::mips64el:
  3283. AddMIPSTargetArgs(Args, CmdArgs);
  3284. break;
  3285. case llvm::Triple::ppc:
  3286. case llvm::Triple::ppc64:
  3287. case llvm::Triple::ppc64le:
  3288. AddPPCTargetArgs(Args, CmdArgs);
  3289. break;
  3290. case llvm::Triple::sparc:
  3291. case llvm::Triple::sparcel:
  3292. case llvm::Triple::sparcv9:
  3293. AddSparcTargetArgs(Args, CmdArgs);
  3294. break;
  3295. case llvm::Triple::x86:
  3296. case llvm::Triple::x86_64:
  3297. AddX86TargetArgs(Args, CmdArgs);
  3298. break;
  3299. case llvm::Triple::hexagon:
  3300. AddHexagonTargetArgs(Args, CmdArgs);
  3301. break;
  3302. }
  3303. // The 'g' groups options involve a somewhat intricate sequence of decisions
  3304. // about what to pass from the driver to the frontend, but by the time they
  3305. // reach cc1 they've been factored into two well-defined orthogonal choices:
  3306. // * what level of debug info to generate
  3307. // * what dwarf version to write
  3308. // This avoids having to monkey around further in cc1 other than to disable
  3309. // codeview if not running in a Windows environment. Perhaps even that
  3310. // decision should be made in the driver as well though.
  3311. enum CodeGenOptions::DebugInfoKind DebugInfoKind =
  3312. CodeGenOptions::NoDebugInfo;
  3313. // These two are potentially updated by AddClangCLArgs.
  3314. unsigned DwarfVersion = 0;
  3315. bool EmitCodeView = false;
  3316. // Add clang-cl arguments.
  3317. if (getToolChain().getDriver().IsCLMode())
  3318. AddClangCLArgs(Args, CmdArgs, &DebugInfoKind, &EmitCodeView);
  3319. // Pass the linker version in use.
  3320. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  3321. CmdArgs.push_back("-target-linker-version");
  3322. CmdArgs.push_back(A->getValue());
  3323. }
  3324. if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
  3325. CmdArgs.push_back("-momit-leaf-frame-pointer");
  3326. // Explicitly error on some things we know we don't support and can't just
  3327. // ignore.
  3328. types::ID InputType = Input.getType();
  3329. if (!Args.hasArg(options::OPT_fallow_unsupported)) {
  3330. Arg *Unsupported;
  3331. if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
  3332. getToolChain().getArch() == llvm::Triple::x86) {
  3333. if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
  3334. (Unsupported = Args.getLastArg(options::OPT_mkernel)))
  3335. D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
  3336. << Unsupported->getOption().getName();
  3337. }
  3338. }
  3339. Args.AddAllArgs(CmdArgs, options::OPT_v);
  3340. Args.AddLastArg(CmdArgs, options::OPT_H);
  3341. if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
  3342. CmdArgs.push_back("-header-include-file");
  3343. CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
  3344. : "-");
  3345. }
  3346. Args.AddLastArg(CmdArgs, options::OPT_P);
  3347. Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
  3348. if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
  3349. CmdArgs.push_back("-diagnostic-log-file");
  3350. CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
  3351. : "-");
  3352. }
  3353. Args.ClaimAllArgs(options::OPT_g_Group);
  3354. Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
  3355. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  3356. // If you say "-gline-tables-only -gsplit-dwarf", split-dwarf wins,
  3357. // which mandates turning on "-g". But -split-dwarf is not a g_group option,
  3358. // hence it takes a nontrivial test to decide about line-tables-only.
  3359. if (A->getOption().matches(options::OPT_gline_tables_only) &&
  3360. (!SplitDwarfArg || A->getIndex() > SplitDwarfArg->getIndex())) {
  3361. DebugInfoKind = CodeGenOptions::DebugLineTablesOnly;
  3362. SplitDwarfArg = nullptr;
  3363. } else if (!A->getOption().matches(options::OPT_g0)) {
  3364. // Some 'g' group option other than one expressly disabling debug info
  3365. // must have been the final (winning) one. They're all equivalent.
  3366. DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
  3367. }
  3368. }
  3369. // If a -gdwarf argument appeared, use it, unless DebugInfoKind is None
  3370. // (because that would mean that "-g0" was the rightmost 'g' group option).
  3371. // FIXME: specifying "-gdwarf-<N>" "-g1" in that order works,
  3372. // but "-g1" "-gdwarf-<N>" does not. A deceptively simple (but wrong) "fix"
  3373. // exists of removing the gdwarf options from the g_group.
  3374. if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
  3375. options::OPT_gdwarf_4))
  3376. DwarfVersion = DwarfVersionNum(A->getSpelling());
  3377. // Forward -gcodeview.
  3378. // 'EmitCodeView might have been set by CL-compatibility argument parsing.
  3379. if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
  3380. // DwarfVersion remains at 0 if no explicit choice was made.
  3381. CmdArgs.push_back("-gcodeview");
  3382. } else if (DwarfVersion == 0 &&
  3383. DebugInfoKind != CodeGenOptions::NoDebugInfo) {
  3384. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  3385. }
  3386. // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
  3387. Args.ClaimAllArgs(options::OPT_g_flags_Group);
  3388. if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
  3389. /*Default*/ true))
  3390. CmdArgs.push_back("-dwarf-column-info");
  3391. // FIXME: Move backend command line options to the module.
  3392. if (Args.hasArg(options::OPT_gmodules)) {
  3393. DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
  3394. CmdArgs.push_back("-dwarf-ext-refs");
  3395. CmdArgs.push_back("-fmodule-format=obj");
  3396. }
  3397. // -gsplit-dwarf should turn on -g and enable the backend dwarf
  3398. // splitting and extraction.
  3399. // FIXME: Currently only works on Linux.
  3400. if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
  3401. DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
  3402. CmdArgs.push_back("-backend-option");
  3403. CmdArgs.push_back("-split-dwarf=Enable");
  3404. }
  3405. // After we've dealt with all combinations of things that could
  3406. // make DebugInfoKind be other than None or DebugLineTablesOnly,
  3407. // figure out if we need to "upgrade" it to standalone debug info.
  3408. // We parse these two '-f' options whether or not they will be used,
  3409. // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
  3410. bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
  3411. options::OPT_fno_standalone_debug,
  3412. getToolChain().GetDefaultStandaloneDebug());
  3413. if (DebugInfoKind == CodeGenOptions::LimitedDebugInfo && NeedFullDebug)
  3414. DebugInfoKind = CodeGenOptions::FullDebugInfo;
  3415. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion);
  3416. // -ggnu-pubnames turns on gnu style pubnames in the backend.
  3417. if (Args.hasArg(options::OPT_ggnu_pubnames)) {
  3418. CmdArgs.push_back("-backend-option");
  3419. CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
  3420. }
  3421. // -gdwarf-aranges turns on the emission of the aranges section in the
  3422. // backend.
  3423. if (Args.hasArg(options::OPT_gdwarf_aranges)) {
  3424. CmdArgs.push_back("-backend-option");
  3425. CmdArgs.push_back("-generate-arange-section");
  3426. }
  3427. if (Args.hasFlag(options::OPT_fdebug_types_section,
  3428. options::OPT_fno_debug_types_section, false)) {
  3429. CmdArgs.push_back("-backend-option");
  3430. CmdArgs.push_back("-generate-type-units");
  3431. }
  3432. // CloudABI uses -ffunction-sections and -fdata-sections by default.
  3433. bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI;
  3434. if (Args.hasFlag(options::OPT_ffunction_sections,
  3435. options::OPT_fno_function_sections, UseSeparateSections)) {
  3436. CmdArgs.push_back("-ffunction-sections");
  3437. }
  3438. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  3439. UseSeparateSections)) {
  3440. CmdArgs.push_back("-fdata-sections");
  3441. }
  3442. if (!Args.hasFlag(options::OPT_funique_section_names,
  3443. options::OPT_fno_unique_section_names, true))
  3444. CmdArgs.push_back("-fno-unique-section-names");
  3445. Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
  3446. addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
  3447. // Pass options for controlling the default header search paths.
  3448. if (Args.hasArg(options::OPT_nostdinc)) {
  3449. CmdArgs.push_back("-nostdsysteminc");
  3450. CmdArgs.push_back("-nobuiltininc");
  3451. } else {
  3452. if (Args.hasArg(options::OPT_nostdlibinc))
  3453. CmdArgs.push_back("-nostdsysteminc");
  3454. Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
  3455. Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
  3456. }
  3457. // Pass the path to compiler resource files.
  3458. CmdArgs.push_back("-resource-dir");
  3459. CmdArgs.push_back(D.ResourceDir.c_str());
  3460. Args.AddLastArg(CmdArgs, options::OPT_working_directory);
  3461. bool ARCMTEnabled = false;
  3462. if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
  3463. if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
  3464. options::OPT_ccc_arcmt_modify,
  3465. options::OPT_ccc_arcmt_migrate)) {
  3466. ARCMTEnabled = true;
  3467. switch (A->getOption().getID()) {
  3468. default:
  3469. llvm_unreachable("missed a case");
  3470. case options::OPT_ccc_arcmt_check:
  3471. CmdArgs.push_back("-arcmt-check");
  3472. break;
  3473. case options::OPT_ccc_arcmt_modify:
  3474. CmdArgs.push_back("-arcmt-modify");
  3475. break;
  3476. case options::OPT_ccc_arcmt_migrate:
  3477. CmdArgs.push_back("-arcmt-migrate");
  3478. CmdArgs.push_back("-mt-migrate-directory");
  3479. CmdArgs.push_back(A->getValue());
  3480. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
  3481. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
  3482. break;
  3483. }
  3484. }
  3485. } else {
  3486. Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
  3487. Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
  3488. Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
  3489. }
  3490. if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
  3491. if (ARCMTEnabled) {
  3492. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  3493. << "-ccc-arcmt-migrate";
  3494. }
  3495. CmdArgs.push_back("-mt-migrate-directory");
  3496. CmdArgs.push_back(A->getValue());
  3497. if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
  3498. options::OPT_objcmt_migrate_subscripting,
  3499. options::OPT_objcmt_migrate_property)) {
  3500. // None specified, means enable them all.
  3501. CmdArgs.push_back("-objcmt-migrate-literals");
  3502. CmdArgs.push_back("-objcmt-migrate-subscripting");
  3503. CmdArgs.push_back("-objcmt-migrate-property");
  3504. } else {
  3505. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  3506. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  3507. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  3508. }
  3509. } else {
  3510. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  3511. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  3512. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  3513. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
  3514. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
  3515. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
  3516. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
  3517. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
  3518. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
  3519. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
  3520. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
  3521. Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
  3522. Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
  3523. Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
  3524. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
  3525. Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
  3526. }
  3527. // Add preprocessing options like -I, -D, etc. if we are using the
  3528. // preprocessor.
  3529. //
  3530. // FIXME: Support -fpreprocessed
  3531. if (types::getPreprocessedType(InputType) != types::TY_INVALID)
  3532. AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
  3533. // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
  3534. // that "The compiler can only warn and ignore the option if not recognized".
  3535. // When building with ccache, it will pass -D options to clang even on
  3536. // preprocessed inputs and configure concludes that -fPIC is not supported.
  3537. Args.ClaimAllArgs(options::OPT_D);
  3538. // Manually translate -O4 to -O3; let clang reject others.
  3539. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  3540. if (A->getOption().matches(options::OPT_O4)) {
  3541. CmdArgs.push_back("-O3");
  3542. D.Diag(diag::warn_O4_is_O3);
  3543. } else {
  3544. A->render(Args, CmdArgs);
  3545. }
  3546. }
  3547. // Warn about ignored options to clang.
  3548. for (const Arg *A :
  3549. Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
  3550. D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
  3551. A->claim();
  3552. }
  3553. claimNoWarnArgs(Args);
  3554. Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
  3555. Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
  3556. if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
  3557. CmdArgs.push_back("-pedantic");
  3558. Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
  3559. Args.AddLastArg(CmdArgs, options::OPT_w);
  3560. // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
  3561. // (-ansi is equivalent to -std=c89 or -std=c++98).
  3562. //
  3563. // If a std is supplied, only add -trigraphs if it follows the
  3564. // option.
  3565. bool ImplyVCPPCXXVer = false;
  3566. if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
  3567. if (Std->getOption().matches(options::OPT_ansi))
  3568. if (types::isCXX(InputType))
  3569. CmdArgs.push_back("-std=c++98");
  3570. else
  3571. CmdArgs.push_back("-std=c89");
  3572. else
  3573. Std->render(Args, CmdArgs);
  3574. // If -f(no-)trigraphs appears after the language standard flag, honor it.
  3575. if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
  3576. options::OPT_ftrigraphs,
  3577. options::OPT_fno_trigraphs))
  3578. if (A != Std)
  3579. A->render(Args, CmdArgs);
  3580. } else {
  3581. // Honor -std-default.
  3582. //
  3583. // FIXME: Clang doesn't correctly handle -std= when the input language
  3584. // doesn't match. For the time being just ignore this for C++ inputs;
  3585. // eventually we want to do all the standard defaulting here instead of
  3586. // splitting it between the driver and clang -cc1.
  3587. if (!types::isCXX(InputType))
  3588. Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
  3589. /*Joined=*/true);
  3590. else if (IsWindowsMSVC)
  3591. ImplyVCPPCXXVer = true;
  3592. Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
  3593. options::OPT_fno_trigraphs);
  3594. }
  3595. // GCC's behavior for -Wwrite-strings is a bit strange:
  3596. // * In C, this "warning flag" changes the types of string literals from
  3597. // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
  3598. // for the discarded qualifier.
  3599. // * In C++, this is just a normal warning flag.
  3600. //
  3601. // Implementing this warning correctly in C is hard, so we follow GCC's
  3602. // behavior for now. FIXME: Directly diagnose uses of a string literal as
  3603. // a non-const char* in C, rather than using this crude hack.
  3604. if (!types::isCXX(InputType)) {
  3605. // FIXME: This should behave just like a warning flag, and thus should also
  3606. // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
  3607. Arg *WriteStrings =
  3608. Args.getLastArg(options::OPT_Wwrite_strings,
  3609. options::OPT_Wno_write_strings, options::OPT_w);
  3610. if (WriteStrings &&
  3611. WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
  3612. CmdArgs.push_back("-fconst-strings");
  3613. }
  3614. // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
  3615. // during C++ compilation, which it is by default. GCC keeps this define even
  3616. // in the presence of '-w', match this behavior bug-for-bug.
  3617. if (types::isCXX(InputType) &&
  3618. Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
  3619. true)) {
  3620. CmdArgs.push_back("-fdeprecated-macro");
  3621. }
  3622. // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
  3623. if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
  3624. if (Asm->getOption().matches(options::OPT_fasm))
  3625. CmdArgs.push_back("-fgnu-keywords");
  3626. else
  3627. CmdArgs.push_back("-fno-gnu-keywords");
  3628. }
  3629. if (ShouldDisableDwarfDirectory(Args, getToolChain()))
  3630. CmdArgs.push_back("-fno-dwarf-directory-asm");
  3631. if (ShouldDisableAutolink(Args, getToolChain()))
  3632. CmdArgs.push_back("-fno-autolink");
  3633. // Add in -fdebug-compilation-dir if necessary.
  3634. addDebugCompDirArg(Args, CmdArgs);
  3635. for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
  3636. StringRef Map = A->getValue();
  3637. if (Map.find('=') == StringRef::npos)
  3638. D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
  3639. else
  3640. CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
  3641. A->claim();
  3642. }
  3643. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
  3644. options::OPT_ftemplate_depth_EQ)) {
  3645. CmdArgs.push_back("-ftemplate-depth");
  3646. CmdArgs.push_back(A->getValue());
  3647. }
  3648. if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
  3649. CmdArgs.push_back("-foperator-arrow-depth");
  3650. CmdArgs.push_back(A->getValue());
  3651. }
  3652. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
  3653. CmdArgs.push_back("-fconstexpr-depth");
  3654. CmdArgs.push_back(A->getValue());
  3655. }
  3656. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
  3657. CmdArgs.push_back("-fconstexpr-steps");
  3658. CmdArgs.push_back(A->getValue());
  3659. }
  3660. if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
  3661. CmdArgs.push_back("-fbracket-depth");
  3662. CmdArgs.push_back(A->getValue());
  3663. }
  3664. if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
  3665. options::OPT_Wlarge_by_value_copy_def)) {
  3666. if (A->getNumValues()) {
  3667. StringRef bytes = A->getValue();
  3668. CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
  3669. } else
  3670. CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
  3671. }
  3672. if (Args.hasArg(options::OPT_relocatable_pch))
  3673. CmdArgs.push_back("-relocatable-pch");
  3674. if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
  3675. CmdArgs.push_back("-fconstant-string-class");
  3676. CmdArgs.push_back(A->getValue());
  3677. }
  3678. if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
  3679. CmdArgs.push_back("-ftabstop");
  3680. CmdArgs.push_back(A->getValue());
  3681. }
  3682. CmdArgs.push_back("-ferror-limit");
  3683. if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
  3684. CmdArgs.push_back(A->getValue());
  3685. else
  3686. CmdArgs.push_back("19");
  3687. if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
  3688. CmdArgs.push_back("-fmacro-backtrace-limit");
  3689. CmdArgs.push_back(A->getValue());
  3690. }
  3691. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
  3692. CmdArgs.push_back("-ftemplate-backtrace-limit");
  3693. CmdArgs.push_back(A->getValue());
  3694. }
  3695. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
  3696. CmdArgs.push_back("-fconstexpr-backtrace-limit");
  3697. CmdArgs.push_back(A->getValue());
  3698. }
  3699. if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
  3700. CmdArgs.push_back("-fspell-checking-limit");
  3701. CmdArgs.push_back(A->getValue());
  3702. }
  3703. // Pass -fmessage-length=.
  3704. CmdArgs.push_back("-fmessage-length");
  3705. if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
  3706. CmdArgs.push_back(A->getValue());
  3707. } else {
  3708. // If -fmessage-length=N was not specified, determine whether this is a
  3709. // terminal and, if so, implicitly define -fmessage-length appropriately.
  3710. unsigned N = llvm::sys::Process::StandardErrColumns();
  3711. CmdArgs.push_back(Args.MakeArgString(Twine(N)));
  3712. }
  3713. // -fvisibility= and -fvisibility-ms-compat are of a piece.
  3714. if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
  3715. options::OPT_fvisibility_ms_compat)) {
  3716. if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
  3717. CmdArgs.push_back("-fvisibility");
  3718. CmdArgs.push_back(A->getValue());
  3719. } else {
  3720. assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
  3721. CmdArgs.push_back("-fvisibility");
  3722. CmdArgs.push_back("hidden");
  3723. CmdArgs.push_back("-ftype-visibility");
  3724. CmdArgs.push_back("default");
  3725. }
  3726. }
  3727. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
  3728. Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
  3729. // -fhosted is default.
  3730. if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
  3731. KernelOrKext)
  3732. CmdArgs.push_back("-ffreestanding");
  3733. // Forward -f (flag) options which we can pass directly.
  3734. Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
  3735. Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
  3736. Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
  3737. // Emulated TLS is enabled by default on Android, and can be enabled manually
  3738. // with -femulated-tls.
  3739. bool EmulatedTLSDefault = Triple.isAndroid();
  3740. if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
  3741. EmulatedTLSDefault))
  3742. CmdArgs.push_back("-femulated-tls");
  3743. // AltiVec-like language extensions aren't relevant for assembling.
  3744. if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
  3745. Args.AddLastArg(CmdArgs, options::OPT_faltivec);
  3746. Args.AddLastArg(CmdArgs, options::OPT_fzvector);
  3747. }
  3748. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
  3749. Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
  3750. // Forward flags for OpenMP
  3751. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  3752. options::OPT_fno_openmp, false))
  3753. switch (getOpenMPRuntime(getToolChain(), Args)) {
  3754. case OMPRT_OMP:
  3755. case OMPRT_IOMP5:
  3756. // Clang can generate useful OpenMP code for these two runtime libraries.
  3757. CmdArgs.push_back("-fopenmp");
  3758. // If no option regarding the use of TLS in OpenMP codegeneration is
  3759. // given, decide a default based on the target. Otherwise rely on the
  3760. // options and pass the right information to the frontend.
  3761. if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
  3762. options::OPT_fnoopenmp_use_tls, /*Default=*/true))
  3763. CmdArgs.push_back("-fnoopenmp-use-tls");
  3764. break;
  3765. default:
  3766. // By default, if Clang doesn't know how to generate useful OpenMP code
  3767. // for a specific runtime library, we just don't pass the '-fopenmp' flag
  3768. // down to the actual compilation.
  3769. // FIXME: It would be better to have a mode which *only* omits IR
  3770. // generation based on the OpenMP support so that we get consistent
  3771. // semantic analysis, etc.
  3772. break;
  3773. }
  3774. const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
  3775. Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
  3776. // Report an error for -faltivec on anything other than PowerPC.
  3777. if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
  3778. const llvm::Triple::ArchType Arch = getToolChain().getArch();
  3779. if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  3780. Arch == llvm::Triple::ppc64le))
  3781. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  3782. << "ppc/ppc64/ppc64le";
  3783. }
  3784. // -fzvector is incompatible with -faltivec.
  3785. if (Arg *A = Args.getLastArg(options::OPT_fzvector))
  3786. if (Args.hasArg(options::OPT_faltivec))
  3787. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  3788. << "-faltivec";
  3789. if (getToolChain().SupportsProfiling())
  3790. Args.AddLastArg(CmdArgs, options::OPT_pg);
  3791. // -flax-vector-conversions is default.
  3792. if (!Args.hasFlag(options::OPT_flax_vector_conversions,
  3793. options::OPT_fno_lax_vector_conversions))
  3794. CmdArgs.push_back("-fno-lax-vector-conversions");
  3795. if (Args.getLastArg(options::OPT_fapple_kext) ||
  3796. (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
  3797. CmdArgs.push_back("-fapple-kext");
  3798. Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
  3799. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
  3800. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
  3801. Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
  3802. Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
  3803. if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
  3804. CmdArgs.push_back("-ftrapv-handler");
  3805. CmdArgs.push_back(A->getValue());
  3806. }
  3807. Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
  3808. // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
  3809. // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
  3810. if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
  3811. if (A->getOption().matches(options::OPT_fwrapv))
  3812. CmdArgs.push_back("-fwrapv");
  3813. } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
  3814. options::OPT_fno_strict_overflow)) {
  3815. if (A->getOption().matches(options::OPT_fno_strict_overflow))
  3816. CmdArgs.push_back("-fwrapv");
  3817. }
  3818. if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
  3819. options::OPT_fno_reroll_loops))
  3820. if (A->getOption().matches(options::OPT_freroll_loops))
  3821. CmdArgs.push_back("-freroll-loops");
  3822. Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
  3823. Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
  3824. options::OPT_fno_unroll_loops);
  3825. Args.AddLastArg(CmdArgs, options::OPT_pthread);
  3826. // -stack-protector=0 is default.
  3827. unsigned StackProtectorLevel = 0;
  3828. if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
  3829. Args.ClaimAllArgs(options::OPT_fno_stack_protector);
  3830. Args.ClaimAllArgs(options::OPT_fstack_protector_all);
  3831. Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
  3832. Args.ClaimAllArgs(options::OPT_fstack_protector);
  3833. } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
  3834. options::OPT_fstack_protector_all,
  3835. options::OPT_fstack_protector_strong,
  3836. options::OPT_fstack_protector)) {
  3837. if (A->getOption().matches(options::OPT_fstack_protector)) {
  3838. StackProtectorLevel = std::max<unsigned>(
  3839. LangOptions::SSPOn,
  3840. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
  3841. } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
  3842. StackProtectorLevel = LangOptions::SSPStrong;
  3843. else if (A->getOption().matches(options::OPT_fstack_protector_all))
  3844. StackProtectorLevel = LangOptions::SSPReq;
  3845. } else {
  3846. StackProtectorLevel =
  3847. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
  3848. }
  3849. if (StackProtectorLevel) {
  3850. CmdArgs.push_back("-stack-protector");
  3851. CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
  3852. }
  3853. // --param ssp-buffer-size=
  3854. for (const Arg *A : Args.filtered(options::OPT__param)) {
  3855. StringRef Str(A->getValue());
  3856. if (Str.startswith("ssp-buffer-size=")) {
  3857. if (StackProtectorLevel) {
  3858. CmdArgs.push_back("-stack-protector-buffer-size");
  3859. // FIXME: Verify the argument is a valid integer.
  3860. CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
  3861. }
  3862. A->claim();
  3863. }
  3864. }
  3865. // Translate -mstackrealign
  3866. if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
  3867. false))
  3868. CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
  3869. if (Args.hasArg(options::OPT_mstack_alignment)) {
  3870. StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
  3871. CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
  3872. }
  3873. if (Args.hasArg(options::OPT_mstack_probe_size)) {
  3874. StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
  3875. if (!Size.empty())
  3876. CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
  3877. else
  3878. CmdArgs.push_back("-mstack-probe-size=0");
  3879. }
  3880. switch (getToolChain().getArch()) {
  3881. case llvm::Triple::aarch64:
  3882. case llvm::Triple::aarch64_be:
  3883. case llvm::Triple::arm:
  3884. case llvm::Triple::armeb:
  3885. case llvm::Triple::thumb:
  3886. case llvm::Triple::thumbeb:
  3887. CmdArgs.push_back("-fallow-half-arguments-and-returns");
  3888. break;
  3889. default:
  3890. break;
  3891. }
  3892. if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
  3893. options::OPT_mno_restrict_it)) {
  3894. if (A->getOption().matches(options::OPT_mrestrict_it)) {
  3895. CmdArgs.push_back("-backend-option");
  3896. CmdArgs.push_back("-arm-restrict-it");
  3897. } else {
  3898. CmdArgs.push_back("-backend-option");
  3899. CmdArgs.push_back("-arm-no-restrict-it");
  3900. }
  3901. } else if (Triple.isOSWindows() &&
  3902. (Triple.getArch() == llvm::Triple::arm ||
  3903. Triple.getArch() == llvm::Triple::thumb)) {
  3904. // Windows on ARM expects restricted IT blocks
  3905. CmdArgs.push_back("-backend-option");
  3906. CmdArgs.push_back("-arm-restrict-it");
  3907. }
  3908. // Forward -f options with positive and negative forms; we translate
  3909. // these by hand.
  3910. if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
  3911. StringRef fname = A->getValue();
  3912. if (!llvm::sys::fs::exists(fname))
  3913. D.Diag(diag::err_drv_no_such_file) << fname;
  3914. else
  3915. A->render(Args, CmdArgs);
  3916. }
  3917. // -fbuiltin is default unless -mkernel is used
  3918. if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
  3919. !Args.hasArg(options::OPT_mkernel)))
  3920. CmdArgs.push_back("-fno-builtin");
  3921. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  3922. options::OPT_fno_assume_sane_operator_new))
  3923. CmdArgs.push_back("-fno-assume-sane-operator-new");
  3924. // -fblocks=0 is default.
  3925. if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
  3926. getToolChain().IsBlocksDefault()) ||
  3927. (Args.hasArg(options::OPT_fgnu_runtime) &&
  3928. Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
  3929. !Args.hasArg(options::OPT_fno_blocks))) {
  3930. CmdArgs.push_back("-fblocks");
  3931. if (!Args.hasArg(options::OPT_fgnu_runtime) &&
  3932. !getToolChain().hasBlocksRuntime())
  3933. CmdArgs.push_back("-fblocks-runtime-optional");
  3934. }
  3935. // -fmodules enables the use of precompiled modules (off by default).
  3936. // Users can pass -fno-cxx-modules to turn off modules support for
  3937. // C++/Objective-C++ programs.
  3938. bool HaveModules = false;
  3939. if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
  3940. bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
  3941. options::OPT_fno_cxx_modules, true);
  3942. if (AllowedInCXX || !types::isCXX(InputType)) {
  3943. CmdArgs.push_back("-fmodules");
  3944. HaveModules = true;
  3945. }
  3946. }
  3947. // -fmodule-maps enables implicit reading of module map files. By default,
  3948. // this is enabled if we are using precompiled modules.
  3949. if (Args.hasFlag(options::OPT_fimplicit_module_maps,
  3950. options::OPT_fno_implicit_module_maps, HaveModules)) {
  3951. CmdArgs.push_back("-fimplicit-module-maps");
  3952. }
  3953. // -fmodules-decluse checks that modules used are declared so (off by
  3954. // default).
  3955. if (Args.hasFlag(options::OPT_fmodules_decluse,
  3956. options::OPT_fno_modules_decluse, false)) {
  3957. CmdArgs.push_back("-fmodules-decluse");
  3958. }
  3959. // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
  3960. // all #included headers are part of modules.
  3961. if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
  3962. options::OPT_fno_modules_strict_decluse, false)) {
  3963. CmdArgs.push_back("-fmodules-strict-decluse");
  3964. }
  3965. // -fno-implicit-modules turns off implicitly compiling modules on demand.
  3966. if (!Args.hasFlag(options::OPT_fimplicit_modules,
  3967. options::OPT_fno_implicit_modules)) {
  3968. CmdArgs.push_back("-fno-implicit-modules");
  3969. }
  3970. // -fmodule-name specifies the module that is currently being built (or
  3971. // used for header checking by -fmodule-maps).
  3972. Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
  3973. // -fmodule-map-file can be used to specify files containing module
  3974. // definitions.
  3975. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
  3976. // -fmodule-file can be used to specify files containing precompiled modules.
  3977. if (HaveModules)
  3978. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
  3979. else
  3980. Args.ClaimAllArgs(options::OPT_fmodule_file);
  3981. // -fmodule-cache-path specifies where our implicitly-built module files
  3982. // should be written.
  3983. SmallString<128> Path;
  3984. if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
  3985. Path = A->getValue();
  3986. if (HaveModules) {
  3987. if (C.isForDiagnostics()) {
  3988. // When generating crash reports, we want to emit the modules along with
  3989. // the reproduction sources, so we ignore any provided module path.
  3990. Path = Output.getFilename();
  3991. llvm::sys::path::replace_extension(Path, ".cache");
  3992. llvm::sys::path::append(Path, "modules");
  3993. } else if (Path.empty()) {
  3994. // No module path was provided: use the default.
  3995. llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
  3996. llvm::sys::path::append(Path, "org.llvm.clang.");
  3997. appendUserToPath(Path);
  3998. llvm::sys::path::append(Path, "ModuleCache");
  3999. }
  4000. const char Arg[] = "-fmodules-cache-path=";
  4001. Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
  4002. CmdArgs.push_back(Args.MakeArgString(Path));
  4003. }
  4004. // When building modules and generating crashdumps, we need to dump a module
  4005. // dependency VFS alongside the output.
  4006. if (HaveModules && C.isForDiagnostics()) {
  4007. SmallString<128> VFSDir(Output.getFilename());
  4008. llvm::sys::path::replace_extension(VFSDir, ".cache");
  4009. // Add the cache directory as a temp so the crash diagnostics pick it up.
  4010. C.addTempFile(Args.MakeArgString(VFSDir));
  4011. llvm::sys::path::append(VFSDir, "vfs");
  4012. CmdArgs.push_back("-module-dependency-dir");
  4013. CmdArgs.push_back(Args.MakeArgString(VFSDir));
  4014. }
  4015. if (HaveModules)
  4016. Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
  4017. // Pass through all -fmodules-ignore-macro arguments.
  4018. Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
  4019. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
  4020. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
  4021. Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
  4022. if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
  4023. if (Args.hasArg(options::OPT_fbuild_session_timestamp))
  4024. D.Diag(diag::err_drv_argument_not_allowed_with)
  4025. << A->getAsString(Args) << "-fbuild-session-timestamp";
  4026. llvm::sys::fs::file_status Status;
  4027. if (llvm::sys::fs::status(A->getValue(), Status))
  4028. D.Diag(diag::err_drv_no_such_file) << A->getValue();
  4029. CmdArgs.push_back(Args.MakeArgString(
  4030. "-fbuild-session-timestamp=" +
  4031. Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
  4032. }
  4033. if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
  4034. if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
  4035. options::OPT_fbuild_session_file))
  4036. D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
  4037. Args.AddLastArg(CmdArgs,
  4038. options::OPT_fmodules_validate_once_per_build_session);
  4039. }
  4040. Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
  4041. // -faccess-control is default.
  4042. if (Args.hasFlag(options::OPT_fno_access_control,
  4043. options::OPT_faccess_control, false))
  4044. CmdArgs.push_back("-fno-access-control");
  4045. // -felide-constructors is the default.
  4046. if (Args.hasFlag(options::OPT_fno_elide_constructors,
  4047. options::OPT_felide_constructors, false))
  4048. CmdArgs.push_back("-fno-elide-constructors");
  4049. ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
  4050. if (KernelOrKext || (types::isCXX(InputType) &&
  4051. (RTTIMode == ToolChain::RM_DisabledExplicitly ||
  4052. RTTIMode == ToolChain::RM_DisabledImplicitly)))
  4053. CmdArgs.push_back("-fno-rtti");
  4054. // -fshort-enums=0 is default for all architectures except Hexagon.
  4055. if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
  4056. getToolChain().getArch() == llvm::Triple::hexagon))
  4057. CmdArgs.push_back("-fshort-enums");
  4058. // -fsigned-char is default.
  4059. if (Arg *A = Args.getLastArg(
  4060. options::OPT_fsigned_char, options::OPT_fno_signed_char,
  4061. options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
  4062. if (A->getOption().matches(options::OPT_funsigned_char) ||
  4063. A->getOption().matches(options::OPT_fno_signed_char)) {
  4064. CmdArgs.push_back("-fno-signed-char");
  4065. }
  4066. } else if (!isSignedCharDefault(getToolChain().getTriple())) {
  4067. CmdArgs.push_back("-fno-signed-char");
  4068. }
  4069. // -fuse-cxa-atexit is default.
  4070. if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
  4071. options::OPT_fno_use_cxa_atexit,
  4072. !IsWindowsCygnus && !IsWindowsGNU &&
  4073. getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
  4074. getToolChain().getArch() != llvm::Triple::hexagon &&
  4075. getToolChain().getArch() != llvm::Triple::xcore) ||
  4076. KernelOrKext)
  4077. CmdArgs.push_back("-fno-use-cxa-atexit");
  4078. // -fms-extensions=0 is default.
  4079. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  4080. IsWindowsMSVC))
  4081. CmdArgs.push_back("-fms-extensions");
  4082. // -fno-use-line-directives is default.
  4083. if (Args.hasFlag(options::OPT_fuse_line_directives,
  4084. options::OPT_fno_use_line_directives, false))
  4085. CmdArgs.push_back("-fuse-line-directives");
  4086. // -fms-compatibility=0 is default.
  4087. if (Args.hasFlag(options::OPT_fms_compatibility,
  4088. options::OPT_fno_ms_compatibility,
  4089. (IsWindowsMSVC &&
  4090. Args.hasFlag(options::OPT_fms_extensions,
  4091. options::OPT_fno_ms_extensions, true))))
  4092. CmdArgs.push_back("-fms-compatibility");
  4093. // -fms-compatibility-version=18.00 is default.
  4094. VersionTuple MSVT = visualstudio::getMSVCVersion(
  4095. &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
  4096. if (!MSVT.empty())
  4097. CmdArgs.push_back(
  4098. Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
  4099. bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
  4100. if (ImplyVCPPCXXVer) {
  4101. if (IsMSVC2015Compatible)
  4102. CmdArgs.push_back("-std=c++14");
  4103. else
  4104. CmdArgs.push_back("-std=c++11");
  4105. }
  4106. // -fno-borland-extensions is default.
  4107. if (Args.hasFlag(options::OPT_fborland_extensions,
  4108. options::OPT_fno_borland_extensions, false))
  4109. CmdArgs.push_back("-fborland-extensions");
  4110. // -fno-declspec is default, except for PS4.
  4111. if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
  4112. getToolChain().getTriple().isPS4()))
  4113. CmdArgs.push_back("-fdeclspec");
  4114. else if (Args.hasArg(options::OPT_fno_declspec))
  4115. CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
  4116. // -fthreadsafe-static is default, except for MSVC compatibility versions less
  4117. // than 19.
  4118. if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
  4119. options::OPT_fno_threadsafe_statics,
  4120. !IsWindowsMSVC || IsMSVC2015Compatible))
  4121. CmdArgs.push_back("-fno-threadsafe-statics");
  4122. // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
  4123. // needs it.
  4124. if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
  4125. options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
  4126. CmdArgs.push_back("-fdelayed-template-parsing");
  4127. // -fgnu-keywords default varies depending on language; only pass if
  4128. // specified.
  4129. if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
  4130. options::OPT_fno_gnu_keywords))
  4131. A->render(Args, CmdArgs);
  4132. if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
  4133. false))
  4134. CmdArgs.push_back("-fgnu89-inline");
  4135. if (Args.hasArg(options::OPT_fno_inline))
  4136. CmdArgs.push_back("-fno-inline");
  4137. if (Args.hasArg(options::OPT_fno_inline_functions))
  4138. CmdArgs.push_back("-fno-inline-functions");
  4139. ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
  4140. // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
  4141. // legacy is the default. Except for deployment taget of 10.5,
  4142. // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
  4143. // gets ignored silently.
  4144. if (objcRuntime.isNonFragile()) {
  4145. if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
  4146. options::OPT_fno_objc_legacy_dispatch,
  4147. objcRuntime.isLegacyDispatchDefaultForArch(
  4148. getToolChain().getArch()))) {
  4149. if (getToolChain().UseObjCMixedDispatch())
  4150. CmdArgs.push_back("-fobjc-dispatch-method=mixed");
  4151. else
  4152. CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
  4153. }
  4154. }
  4155. // When ObjectiveC legacy runtime is in effect on MacOSX,
  4156. // turn on the option to do Array/Dictionary subscripting
  4157. // by default.
  4158. if (getToolChain().getArch() == llvm::Triple::x86 &&
  4159. getToolChain().getTriple().isMacOSX() &&
  4160. !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
  4161. objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
  4162. objcRuntime.isNeXTFamily())
  4163. CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
  4164. // -fencode-extended-block-signature=1 is default.
  4165. if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
  4166. CmdArgs.push_back("-fencode-extended-block-signature");
  4167. }
  4168. // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
  4169. // NOTE: This logic is duplicated in ToolChains.cpp.
  4170. bool ARC = isObjCAutoRefCount(Args);
  4171. if (ARC) {
  4172. getToolChain().CheckObjCARC();
  4173. CmdArgs.push_back("-fobjc-arc");
  4174. // FIXME: It seems like this entire block, and several around it should be
  4175. // wrapped in isObjC, but for now we just use it here as this is where it
  4176. // was being used previously.
  4177. if (types::isCXX(InputType) && types::isObjC(InputType)) {
  4178. if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  4179. CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
  4180. else
  4181. CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
  4182. }
  4183. // Allow the user to enable full exceptions code emission.
  4184. // We define off for Objective-CC, on for Objective-C++.
  4185. if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
  4186. options::OPT_fno_objc_arc_exceptions,
  4187. /*default*/ types::isCXX(InputType)))
  4188. CmdArgs.push_back("-fobjc-arc-exceptions");
  4189. }
  4190. // -fobjc-infer-related-result-type is the default, except in the Objective-C
  4191. // rewriter.
  4192. if (rewriteKind != RK_None)
  4193. CmdArgs.push_back("-fno-objc-infer-related-result-type");
  4194. // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
  4195. // takes precedence.
  4196. const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
  4197. if (!GCArg)
  4198. GCArg = Args.getLastArg(options::OPT_fobjc_gc);
  4199. if (GCArg) {
  4200. if (ARC) {
  4201. D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
  4202. } else if (getToolChain().SupportsObjCGC()) {
  4203. GCArg->render(Args, CmdArgs);
  4204. } else {
  4205. // FIXME: We should move this to a hard error.
  4206. D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
  4207. }
  4208. }
  4209. if (Args.hasFlag(options::OPT_fapplication_extension,
  4210. options::OPT_fno_application_extension, false))
  4211. CmdArgs.push_back("-fapplication-extension");
  4212. // Handle GCC-style exception args.
  4213. if (!C.getDriver().IsCLMode())
  4214. addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
  4215. CmdArgs);
  4216. if (getToolChain().UseSjLjExceptions())
  4217. CmdArgs.push_back("-fsjlj-exceptions");
  4218. // C++ "sane" operator new.
  4219. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4220. options::OPT_fno_assume_sane_operator_new))
  4221. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4222. // -fsized-deallocation is off by default, as it is an ABI-breaking change for
  4223. // most platforms.
  4224. if (Args.hasFlag(options::OPT_fsized_deallocation,
  4225. options::OPT_fno_sized_deallocation, false))
  4226. CmdArgs.push_back("-fsized-deallocation");
  4227. // -fconstant-cfstrings is default, and may be subject to argument translation
  4228. // on Darwin.
  4229. if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
  4230. options::OPT_fno_constant_cfstrings) ||
  4231. !Args.hasFlag(options::OPT_mconstant_cfstrings,
  4232. options::OPT_mno_constant_cfstrings))
  4233. CmdArgs.push_back("-fno-constant-cfstrings");
  4234. // -fshort-wchar default varies depending on platform; only
  4235. // pass if specified.
  4236. if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
  4237. options::OPT_fno_short_wchar))
  4238. A->render(Args, CmdArgs);
  4239. // -fno-pascal-strings is default, only pass non-default.
  4240. if (Args.hasFlag(options::OPT_fpascal_strings,
  4241. options::OPT_fno_pascal_strings, false))
  4242. CmdArgs.push_back("-fpascal-strings");
  4243. // Honor -fpack-struct= and -fpack-struct, if given. Note that
  4244. // -fno-pack-struct doesn't apply to -fpack-struct=.
  4245. if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
  4246. std::string PackStructStr = "-fpack-struct=";
  4247. PackStructStr += A->getValue();
  4248. CmdArgs.push_back(Args.MakeArgString(PackStructStr));
  4249. } else if (Args.hasFlag(options::OPT_fpack_struct,
  4250. options::OPT_fno_pack_struct, false)) {
  4251. CmdArgs.push_back("-fpack-struct=1");
  4252. }
  4253. // Handle -fmax-type-align=N and -fno-type-align
  4254. bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
  4255. if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
  4256. if (!SkipMaxTypeAlign) {
  4257. std::string MaxTypeAlignStr = "-fmax-type-align=";
  4258. MaxTypeAlignStr += A->getValue();
  4259. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4260. }
  4261. } else if (getToolChain().getTriple().isOSDarwin()) {
  4262. if (!SkipMaxTypeAlign) {
  4263. std::string MaxTypeAlignStr = "-fmax-type-align=16";
  4264. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4265. }
  4266. }
  4267. // -fcommon is the default unless compiling kernel code or the target says so
  4268. bool NoCommonDefault =
  4269. KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
  4270. if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
  4271. !NoCommonDefault))
  4272. CmdArgs.push_back("-fno-common");
  4273. // -fsigned-bitfields is default, and clang doesn't yet support
  4274. // -funsigned-bitfields.
  4275. if (!Args.hasFlag(options::OPT_fsigned_bitfields,
  4276. options::OPT_funsigned_bitfields))
  4277. D.Diag(diag::warn_drv_clang_unsupported)
  4278. << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
  4279. // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
  4280. if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
  4281. D.Diag(diag::err_drv_clang_unsupported)
  4282. << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
  4283. // -finput_charset=UTF-8 is default. Reject others
  4284. if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
  4285. StringRef value = inputCharset->getValue();
  4286. if (value != "UTF-8")
  4287. D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
  4288. << value;
  4289. }
  4290. // -fexec_charset=UTF-8 is default. Reject others
  4291. if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
  4292. StringRef value = execCharset->getValue();
  4293. if (value != "UTF-8")
  4294. D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
  4295. << value;
  4296. }
  4297. // -fcaret-diagnostics is default.
  4298. if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
  4299. options::OPT_fno_caret_diagnostics, true))
  4300. CmdArgs.push_back("-fno-caret-diagnostics");
  4301. // -fdiagnostics-fixit-info is default, only pass non-default.
  4302. if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
  4303. options::OPT_fno_diagnostics_fixit_info))
  4304. CmdArgs.push_back("-fno-diagnostics-fixit-info");
  4305. // Enable -fdiagnostics-show-option by default.
  4306. if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
  4307. options::OPT_fno_diagnostics_show_option))
  4308. CmdArgs.push_back("-fdiagnostics-show-option");
  4309. if (const Arg *A =
  4310. Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
  4311. CmdArgs.push_back("-fdiagnostics-show-category");
  4312. CmdArgs.push_back(A->getValue());
  4313. }
  4314. if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
  4315. CmdArgs.push_back("-fdiagnostics-format");
  4316. CmdArgs.push_back(A->getValue());
  4317. }
  4318. if (Arg *A = Args.getLastArg(
  4319. options::OPT_fdiagnostics_show_note_include_stack,
  4320. options::OPT_fno_diagnostics_show_note_include_stack)) {
  4321. if (A->getOption().matches(
  4322. options::OPT_fdiagnostics_show_note_include_stack))
  4323. CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
  4324. else
  4325. CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
  4326. }
  4327. // Color diagnostics are the default, unless the terminal doesn't support
  4328. // them.
  4329. // Support both clang's -f[no-]color-diagnostics and gcc's
  4330. // -f[no-]diagnostics-colors[=never|always|auto].
  4331. enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
  4332. for (const auto &Arg : Args) {
  4333. const Option &O = Arg->getOption();
  4334. if (!O.matches(options::OPT_fcolor_diagnostics) &&
  4335. !O.matches(options::OPT_fdiagnostics_color) &&
  4336. !O.matches(options::OPT_fno_color_diagnostics) &&
  4337. !O.matches(options::OPT_fno_diagnostics_color) &&
  4338. !O.matches(options::OPT_fdiagnostics_color_EQ))
  4339. continue;
  4340. Arg->claim();
  4341. if (O.matches(options::OPT_fcolor_diagnostics) ||
  4342. O.matches(options::OPT_fdiagnostics_color)) {
  4343. ShowColors = Colors_On;
  4344. } else if (O.matches(options::OPT_fno_color_diagnostics) ||
  4345. O.matches(options::OPT_fno_diagnostics_color)) {
  4346. ShowColors = Colors_Off;
  4347. } else {
  4348. assert(O.matches(options::OPT_fdiagnostics_color_EQ));
  4349. StringRef value(Arg->getValue());
  4350. if (value == "always")
  4351. ShowColors = Colors_On;
  4352. else if (value == "never")
  4353. ShowColors = Colors_Off;
  4354. else if (value == "auto")
  4355. ShowColors = Colors_Auto;
  4356. else
  4357. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  4358. << ("-fdiagnostics-color=" + value).str();
  4359. }
  4360. }
  4361. if (ShowColors == Colors_On ||
  4362. (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
  4363. CmdArgs.push_back("-fcolor-diagnostics");
  4364. if (Args.hasArg(options::OPT_fansi_escape_codes))
  4365. CmdArgs.push_back("-fansi-escape-codes");
  4366. if (!Args.hasFlag(options::OPT_fshow_source_location,
  4367. options::OPT_fno_show_source_location))
  4368. CmdArgs.push_back("-fno-show-source-location");
  4369. if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
  4370. true))
  4371. CmdArgs.push_back("-fno-show-column");
  4372. if (!Args.hasFlag(options::OPT_fspell_checking,
  4373. options::OPT_fno_spell_checking))
  4374. CmdArgs.push_back("-fno-spell-checking");
  4375. // -fno-asm-blocks is default.
  4376. if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
  4377. false))
  4378. CmdArgs.push_back("-fasm-blocks");
  4379. // -fgnu-inline-asm is default.
  4380. if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
  4381. options::OPT_fno_gnu_inline_asm, true))
  4382. CmdArgs.push_back("-fno-gnu-inline-asm");
  4383. // Enable vectorization per default according to the optimization level
  4384. // selected. For optimization levels that want vectorization we use the alias
  4385. // option to simplify the hasFlag logic.
  4386. bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
  4387. OptSpecifier VectorizeAliasOption =
  4388. EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
  4389. if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
  4390. options::OPT_fno_vectorize, EnableVec))
  4391. CmdArgs.push_back("-vectorize-loops");
  4392. // -fslp-vectorize is enabled based on the optimization level selected.
  4393. bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
  4394. OptSpecifier SLPVectAliasOption =
  4395. EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
  4396. if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
  4397. options::OPT_fno_slp_vectorize, EnableSLPVec))
  4398. CmdArgs.push_back("-vectorize-slp");
  4399. // -fno-slp-vectorize-aggressive is default.
  4400. if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
  4401. options::OPT_fno_slp_vectorize_aggressive, false))
  4402. CmdArgs.push_back("-vectorize-slp-aggressive");
  4403. if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
  4404. A->render(Args, CmdArgs);
  4405. // -fdollars-in-identifiers default varies depending on platform and
  4406. // language; only pass if specified.
  4407. if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
  4408. options::OPT_fno_dollars_in_identifiers)) {
  4409. if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
  4410. CmdArgs.push_back("-fdollars-in-identifiers");
  4411. else
  4412. CmdArgs.push_back("-fno-dollars-in-identifiers");
  4413. }
  4414. // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
  4415. // practical purposes.
  4416. if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
  4417. options::OPT_fno_unit_at_a_time)) {
  4418. if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
  4419. D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
  4420. }
  4421. if (Args.hasFlag(options::OPT_fapple_pragma_pack,
  4422. options::OPT_fno_apple_pragma_pack, false))
  4423. CmdArgs.push_back("-fapple-pragma-pack");
  4424. // le32-specific flags:
  4425. // -fno-math-builtin: clang should not convert math builtins to intrinsics
  4426. // by default.
  4427. if (getToolChain().getArch() == llvm::Triple::le32) {
  4428. CmdArgs.push_back("-fno-math-builtin");
  4429. }
  4430. // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
  4431. //
  4432. // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
  4433. #if 0
  4434. if (getToolChain().getTriple().isOSDarwin() &&
  4435. (getToolChain().getArch() == llvm::Triple::arm ||
  4436. getToolChain().getArch() == llvm::Triple::thumb)) {
  4437. if (!Args.hasArg(options::OPT_fbuiltin_strcat))
  4438. CmdArgs.push_back("-fno-builtin-strcat");
  4439. if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
  4440. CmdArgs.push_back("-fno-builtin-strcpy");
  4441. }
  4442. #endif
  4443. // Enable rewrite includes if the user's asked for it or if we're generating
  4444. // diagnostics.
  4445. // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
  4446. // nice to enable this when doing a crashdump for modules as well.
  4447. if (Args.hasFlag(options::OPT_frewrite_includes,
  4448. options::OPT_fno_rewrite_includes, false) ||
  4449. (C.isForDiagnostics() && !HaveModules))
  4450. CmdArgs.push_back("-frewrite-includes");
  4451. // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
  4452. if (Arg *A = Args.getLastArg(options::OPT_traditional,
  4453. options::OPT_traditional_cpp)) {
  4454. if (isa<PreprocessJobAction>(JA))
  4455. CmdArgs.push_back("-traditional-cpp");
  4456. else
  4457. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  4458. }
  4459. Args.AddLastArg(CmdArgs, options::OPT_dM);
  4460. Args.AddLastArg(CmdArgs, options::OPT_dD);
  4461. // Handle serialized diagnostics.
  4462. if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
  4463. CmdArgs.push_back("-serialize-diagnostic-file");
  4464. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  4465. }
  4466. if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
  4467. CmdArgs.push_back("-fretain-comments-from-system-headers");
  4468. // Forward -fcomment-block-commands to -cc1.
  4469. Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
  4470. // Forward -fparse-all-comments to -cc1.
  4471. Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
  4472. // Turn -fplugin=name.so into -load name.so
  4473. for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
  4474. CmdArgs.push_back("-load");
  4475. CmdArgs.push_back(A->getValue());
  4476. A->claim();
  4477. }
  4478. // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
  4479. // parser.
  4480. Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
  4481. for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
  4482. A->claim();
  4483. // We translate this by hand to the -cc1 argument, since nightly test uses
  4484. // it and developers have been trained to spell it with -mllvm.
  4485. if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
  4486. CmdArgs.push_back("-disable-llvm-optzns");
  4487. } else
  4488. A->render(Args, CmdArgs);
  4489. }
  4490. // With -save-temps, we want to save the unoptimized bitcode output from the
  4491. // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
  4492. // by the frontend.
  4493. if (C.getDriver().isSaveTempsEnabled() && isa<CompileJobAction>(JA))
  4494. CmdArgs.push_back("-disable-llvm-passes");
  4495. if (Output.getType() == types::TY_Dependencies) {
  4496. // Handled with other dependency code.
  4497. } else if (Output.isFilename()) {
  4498. CmdArgs.push_back("-o");
  4499. CmdArgs.push_back(Output.getFilename());
  4500. } else {
  4501. assert(Output.isNothing() && "Invalid output.");
  4502. }
  4503. addDashXForInput(Args, Input, CmdArgs);
  4504. if (Input.isFilename())
  4505. CmdArgs.push_back(Input.getFilename());
  4506. else
  4507. Input.getInputArg().renderAsInput(Args, CmdArgs);
  4508. Args.AddAllArgs(CmdArgs, options::OPT_undef);
  4509. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  4510. // Optionally embed the -cc1 level arguments into the debug info, for build
  4511. // analysis.
  4512. if (getToolChain().UseDwarfDebugFlags()) {
  4513. ArgStringList OriginalArgs;
  4514. for (const auto &Arg : Args)
  4515. Arg->render(Args, OriginalArgs);
  4516. SmallString<256> Flags;
  4517. Flags += Exec;
  4518. for (const char *OriginalArg : OriginalArgs) {
  4519. SmallString<128> EscapedArg;
  4520. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  4521. Flags += " ";
  4522. Flags += EscapedArg;
  4523. }
  4524. CmdArgs.push_back("-dwarf-debug-flags");
  4525. CmdArgs.push_back(Args.MakeArgString(Flags));
  4526. }
  4527. // Add the split debug info name to the command lines here so we
  4528. // can propagate it to the backend.
  4529. bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
  4530. (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
  4531. isa<BackendJobAction>(JA));
  4532. const char *SplitDwarfOut;
  4533. if (SplitDwarf) {
  4534. CmdArgs.push_back("-split-dwarf-file");
  4535. SplitDwarfOut = SplitDebugName(Args, Input);
  4536. CmdArgs.push_back(SplitDwarfOut);
  4537. }
  4538. // Host-side cuda compilation receives device-side outputs as Inputs[1...].
  4539. // Include them with -fcuda-include-gpubinary.
  4540. if (IsCuda && Inputs.size() > 1)
  4541. for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
  4542. CmdArgs.push_back("-fcuda-include-gpubinary");
  4543. CmdArgs.push_back(I->getFilename());
  4544. }
  4545. // Finally add the compile command to the compilation.
  4546. if (Args.hasArg(options::OPT__SLASH_fallback) &&
  4547. Output.getType() == types::TY_Object &&
  4548. (InputType == types::TY_C || InputType == types::TY_CXX)) {
  4549. auto CLCommand =
  4550. getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
  4551. C.addCommand(llvm::make_unique<FallbackCommand>(
  4552. JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
  4553. } else {
  4554. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  4555. }
  4556. // Handle the debug info splitting at object creation time if we're
  4557. // creating an object.
  4558. // TODO: Currently only works on linux with newer objcopy.
  4559. if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
  4560. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
  4561. if (Arg *A = Args.getLastArg(options::OPT_pg))
  4562. if (Args.hasArg(options::OPT_fomit_frame_pointer))
  4563. D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
  4564. << A->getAsString(Args);
  4565. // Claim some arguments which clang supports automatically.
  4566. // -fpch-preprocess is used with gcc to add a special marker in the output to
  4567. // include the PCH file. Clang's PTH solution is completely transparent, so we
  4568. // do not need to deal with it at all.
  4569. Args.ClaimAllArgs(options::OPT_fpch_preprocess);
  4570. // Claim some arguments which clang doesn't support, but we don't
  4571. // care to warn the user about.
  4572. Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
  4573. Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
  4574. // Disable warnings for clang -E -emit-llvm foo.c
  4575. Args.ClaimAllArgs(options::OPT_emit_llvm);
  4576. }
  4577. /// Add options related to the Objective-C runtime/ABI.
  4578. ///
  4579. /// Returns true if the runtime is non-fragile.
  4580. ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
  4581. ArgStringList &cmdArgs,
  4582. RewriteKind rewriteKind) const {
  4583. // Look for the controlling runtime option.
  4584. Arg *runtimeArg =
  4585. args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
  4586. options::OPT_fobjc_runtime_EQ);
  4587. // Just forward -fobjc-runtime= to the frontend. This supercedes
  4588. // options about fragility.
  4589. if (runtimeArg &&
  4590. runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
  4591. ObjCRuntime runtime;
  4592. StringRef value = runtimeArg->getValue();
  4593. if (runtime.tryParse(value)) {
  4594. getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
  4595. << value;
  4596. }
  4597. runtimeArg->render(args, cmdArgs);
  4598. return runtime;
  4599. }
  4600. // Otherwise, we'll need the ABI "version". Version numbers are
  4601. // slightly confusing for historical reasons:
  4602. // 1 - Traditional "fragile" ABI
  4603. // 2 - Non-fragile ABI, version 1
  4604. // 3 - Non-fragile ABI, version 2
  4605. unsigned objcABIVersion = 1;
  4606. // If -fobjc-abi-version= is present, use that to set the version.
  4607. if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
  4608. StringRef value = abiArg->getValue();
  4609. if (value == "1")
  4610. objcABIVersion = 1;
  4611. else if (value == "2")
  4612. objcABIVersion = 2;
  4613. else if (value == "3")
  4614. objcABIVersion = 3;
  4615. else
  4616. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
  4617. } else {
  4618. // Otherwise, determine if we are using the non-fragile ABI.
  4619. bool nonFragileABIIsDefault =
  4620. (rewriteKind == RK_NonFragile ||
  4621. (rewriteKind == RK_None &&
  4622. getToolChain().IsObjCNonFragileABIDefault()));
  4623. if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
  4624. options::OPT_fno_objc_nonfragile_abi,
  4625. nonFragileABIIsDefault)) {
  4626. // Determine the non-fragile ABI version to use.
  4627. #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
  4628. unsigned nonFragileABIVersion = 1;
  4629. #else
  4630. unsigned nonFragileABIVersion = 2;
  4631. #endif
  4632. if (Arg *abiArg =
  4633. args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
  4634. StringRef value = abiArg->getValue();
  4635. if (value == "1")
  4636. nonFragileABIVersion = 1;
  4637. else if (value == "2")
  4638. nonFragileABIVersion = 2;
  4639. else
  4640. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  4641. << value;
  4642. }
  4643. objcABIVersion = 1 + nonFragileABIVersion;
  4644. } else {
  4645. objcABIVersion = 1;
  4646. }
  4647. }
  4648. // We don't actually care about the ABI version other than whether
  4649. // it's non-fragile.
  4650. bool isNonFragile = objcABIVersion != 1;
  4651. // If we have no runtime argument, ask the toolchain for its default runtime.
  4652. // However, the rewriter only really supports the Mac runtime, so assume that.
  4653. ObjCRuntime runtime;
  4654. if (!runtimeArg) {
  4655. switch (rewriteKind) {
  4656. case RK_None:
  4657. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  4658. break;
  4659. case RK_Fragile:
  4660. runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
  4661. break;
  4662. case RK_NonFragile:
  4663. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  4664. break;
  4665. }
  4666. // -fnext-runtime
  4667. } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
  4668. // On Darwin, make this use the default behavior for the toolchain.
  4669. if (getToolChain().getTriple().isOSDarwin()) {
  4670. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  4671. // Otherwise, build for a generic macosx port.
  4672. } else {
  4673. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  4674. }
  4675. // -fgnu-runtime
  4676. } else {
  4677. assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
  4678. // Legacy behaviour is to target the gnustep runtime if we are i
  4679. // non-fragile mode or the GCC runtime in fragile mode.
  4680. if (isNonFragile)
  4681. runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
  4682. else
  4683. runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
  4684. }
  4685. cmdArgs.push_back(
  4686. args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
  4687. return runtime;
  4688. }
  4689. static bool maybeConsumeDash(const std::string &EH, size_t &I) {
  4690. bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
  4691. I += HaveDash;
  4692. return !HaveDash;
  4693. }
  4694. struct EHFlags {
  4695. EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
  4696. bool Synch;
  4697. bool Asynch;
  4698. bool NoExceptC;
  4699. };
  4700. /// /EH controls whether to run destructor cleanups when exceptions are
  4701. /// thrown. There are three modifiers:
  4702. /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
  4703. /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
  4704. /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
  4705. /// - c: Assume that extern "C" functions are implicitly noexcept. This
  4706. /// modifier is an optimization, so we ignore it for now.
  4707. /// The default is /EHs-c-, meaning cleanups are disabled.
  4708. static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
  4709. EHFlags EH;
  4710. std::vector<std::string> EHArgs =
  4711. Args.getAllArgValues(options::OPT__SLASH_EH);
  4712. for (auto EHVal : EHArgs) {
  4713. for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
  4714. switch (EHVal[I]) {
  4715. case 'a':
  4716. EH.Asynch = maybeConsumeDash(EHVal, I);
  4717. continue;
  4718. case 'c':
  4719. EH.NoExceptC = maybeConsumeDash(EHVal, I);
  4720. continue;
  4721. case 's':
  4722. EH.Synch = maybeConsumeDash(EHVal, I);
  4723. continue;
  4724. default:
  4725. break;
  4726. }
  4727. D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
  4728. break;
  4729. }
  4730. }
  4731. return EH;
  4732. }
  4733. void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs,
  4734. enum CodeGenOptions::DebugInfoKind *DebugInfoKind,
  4735. bool *EmitCodeView) const {
  4736. unsigned RTOptionID = options::OPT__SLASH_MT;
  4737. if (Args.hasArg(options::OPT__SLASH_LDd))
  4738. // The /LDd option implies /MTd. The dependent lib part can be overridden,
  4739. // but defining _DEBUG is sticky.
  4740. RTOptionID = options::OPT__SLASH_MTd;
  4741. if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
  4742. RTOptionID = A->getOption().getID();
  4743. StringRef FlagForCRT;
  4744. switch (RTOptionID) {
  4745. case options::OPT__SLASH_MD:
  4746. if (Args.hasArg(options::OPT__SLASH_LDd))
  4747. CmdArgs.push_back("-D_DEBUG");
  4748. CmdArgs.push_back("-D_MT");
  4749. CmdArgs.push_back("-D_DLL");
  4750. FlagForCRT = "--dependent-lib=msvcrt";
  4751. break;
  4752. case options::OPT__SLASH_MDd:
  4753. CmdArgs.push_back("-D_DEBUG");
  4754. CmdArgs.push_back("-D_MT");
  4755. CmdArgs.push_back("-D_DLL");
  4756. FlagForCRT = "--dependent-lib=msvcrtd";
  4757. break;
  4758. case options::OPT__SLASH_MT:
  4759. if (Args.hasArg(options::OPT__SLASH_LDd))
  4760. CmdArgs.push_back("-D_DEBUG");
  4761. CmdArgs.push_back("-D_MT");
  4762. FlagForCRT = "--dependent-lib=libcmt";
  4763. break;
  4764. case options::OPT__SLASH_MTd:
  4765. CmdArgs.push_back("-D_DEBUG");
  4766. CmdArgs.push_back("-D_MT");
  4767. FlagForCRT = "--dependent-lib=libcmtd";
  4768. break;
  4769. default:
  4770. llvm_unreachable("Unexpected option ID.");
  4771. }
  4772. if (Args.hasArg(options::OPT__SLASH_Zl)) {
  4773. CmdArgs.push_back("-D_VC_NODEFAULTLIB");
  4774. } else {
  4775. CmdArgs.push_back(FlagForCRT.data());
  4776. // This provides POSIX compatibility (maps 'open' to '_open'), which most
  4777. // users want. The /Za flag to cl.exe turns this off, but it's not
  4778. // implemented in clang.
  4779. CmdArgs.push_back("--dependent-lib=oldnames");
  4780. }
  4781. // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
  4782. // would produce interleaved output, so ignore /showIncludes in such cases.
  4783. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
  4784. if (Arg *A = Args.getLastArg(options::OPT_show_includes))
  4785. A->render(Args, CmdArgs);
  4786. // This controls whether or not we emit RTTI data for polymorphic types.
  4787. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  4788. /*default=*/false))
  4789. CmdArgs.push_back("-fno-rtti-data");
  4790. // Emit CodeView if -Z7 is present.
  4791. *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
  4792. bool EmitDwarf = Args.hasArg(options::OPT_gdwarf);
  4793. // If we are emitting CV but not DWARF, don't build information that LLVM
  4794. // can't yet process.
  4795. if (*EmitCodeView && !EmitDwarf)
  4796. *DebugInfoKind = CodeGenOptions::DebugLineTablesOnly;
  4797. if (*EmitCodeView)
  4798. CmdArgs.push_back("-gcodeview");
  4799. const Driver &D = getToolChain().getDriver();
  4800. EHFlags EH = parseClangCLEHFlags(D, Args);
  4801. // FIXME: Do something with NoExceptC.
  4802. if (EH.Synch || EH.Asynch) {
  4803. CmdArgs.push_back("-fcxx-exceptions");
  4804. CmdArgs.push_back("-fexceptions");
  4805. }
  4806. // /EP should expand to -E -P.
  4807. if (Args.hasArg(options::OPT__SLASH_EP)) {
  4808. CmdArgs.push_back("-E");
  4809. CmdArgs.push_back("-P");
  4810. }
  4811. unsigned VolatileOptionID;
  4812. if (getToolChain().getArch() == llvm::Triple::x86_64 ||
  4813. getToolChain().getArch() == llvm::Triple::x86)
  4814. VolatileOptionID = options::OPT__SLASH_volatile_ms;
  4815. else
  4816. VolatileOptionID = options::OPT__SLASH_volatile_iso;
  4817. if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
  4818. VolatileOptionID = A->getOption().getID();
  4819. if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
  4820. CmdArgs.push_back("-fms-volatile");
  4821. Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
  4822. Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
  4823. if (MostGeneralArg && BestCaseArg)
  4824. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  4825. << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
  4826. if (MostGeneralArg) {
  4827. Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
  4828. Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
  4829. Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
  4830. Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
  4831. Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
  4832. if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
  4833. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  4834. << FirstConflict->getAsString(Args)
  4835. << SecondConflict->getAsString(Args);
  4836. if (SingleArg)
  4837. CmdArgs.push_back("-fms-memptr-rep=single");
  4838. else if (MultipleArg)
  4839. CmdArgs.push_back("-fms-memptr-rep=multiple");
  4840. else
  4841. CmdArgs.push_back("-fms-memptr-rep=virtual");
  4842. }
  4843. if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
  4844. A->render(Args, CmdArgs);
  4845. if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
  4846. CmdArgs.push_back("-fdiagnostics-format");
  4847. if (Args.hasArg(options::OPT__SLASH_fallback))
  4848. CmdArgs.push_back("msvc-fallback");
  4849. else
  4850. CmdArgs.push_back("msvc");
  4851. }
  4852. }
  4853. visualstudio::Compiler *Clang::getCLFallback() const {
  4854. if (!CLFallback)
  4855. CLFallback.reset(new visualstudio::Compiler(getToolChain()));
  4856. return CLFallback.get();
  4857. }
  4858. void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
  4859. ArgStringList &CmdArgs) const {
  4860. StringRef CPUName;
  4861. StringRef ABIName;
  4862. const llvm::Triple &Triple = getToolChain().getTriple();
  4863. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  4864. CmdArgs.push_back("-target-abi");
  4865. CmdArgs.push_back(ABIName.data());
  4866. }
  4867. void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
  4868. const InputInfo &Output, const InputInfoList &Inputs,
  4869. const ArgList &Args,
  4870. const char *LinkingOutput) const {
  4871. ArgStringList CmdArgs;
  4872. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  4873. const InputInfo &Input = Inputs[0];
  4874. std::string TripleStr =
  4875. getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
  4876. const llvm::Triple Triple(TripleStr);
  4877. // Don't warn about "clang -w -c foo.s"
  4878. Args.ClaimAllArgs(options::OPT_w);
  4879. // and "clang -emit-llvm -c foo.s"
  4880. Args.ClaimAllArgs(options::OPT_emit_llvm);
  4881. claimNoWarnArgs(Args);
  4882. // Invoke ourselves in -cc1as mode.
  4883. //
  4884. // FIXME: Implement custom jobs for internal actions.
  4885. CmdArgs.push_back("-cc1as");
  4886. // Add the "effective" target triple.
  4887. CmdArgs.push_back("-triple");
  4888. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  4889. // Set the output mode, we currently only expect to be used as a real
  4890. // assembler.
  4891. CmdArgs.push_back("-filetype");
  4892. CmdArgs.push_back("obj");
  4893. // Set the main file name, so that debug info works even with
  4894. // -save-temps or preprocessed assembly.
  4895. CmdArgs.push_back("-main-file-name");
  4896. CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
  4897. // Add the target cpu
  4898. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
  4899. if (!CPU.empty()) {
  4900. CmdArgs.push_back("-target-cpu");
  4901. CmdArgs.push_back(Args.MakeArgString(CPU));
  4902. }
  4903. // Add the target features
  4904. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
  4905. // Ignore explicit -force_cpusubtype_ALL option.
  4906. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  4907. // Pass along any -I options so we get proper .include search paths.
  4908. Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
  4909. // Determine the original source input.
  4910. const Action *SourceAction = &JA;
  4911. while (SourceAction->getKind() != Action::InputClass) {
  4912. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  4913. SourceAction = SourceAction->getInputs()[0];
  4914. }
  4915. // Forward -g and handle debug info related flags, assuming we are dealing
  4916. // with an actual assembly file.
  4917. if (SourceAction->getType() == types::TY_Asm ||
  4918. SourceAction->getType() == types::TY_PP_Asm) {
  4919. bool WantDebug = false;
  4920. unsigned DwarfVersion = 0;
  4921. Args.ClaimAllArgs(options::OPT_g_Group);
  4922. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  4923. WantDebug = !A->getOption().matches(options::OPT_g0);
  4924. if (WantDebug) {
  4925. if ((DwarfVersion = DwarfVersionNum(A->getSpelling())) == 0)
  4926. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  4927. }
  4928. }
  4929. RenderDebugEnablingArgs(Args, CmdArgs,
  4930. (WantDebug ? CodeGenOptions::LimitedDebugInfo
  4931. : CodeGenOptions::NoDebugInfo),
  4932. DwarfVersion);
  4933. // Add the -fdebug-compilation-dir flag if needed.
  4934. addDebugCompDirArg(Args, CmdArgs);
  4935. // Set the AT_producer to the clang version when using the integrated
  4936. // assembler on assembly source files.
  4937. CmdArgs.push_back("-dwarf-debug-producer");
  4938. CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
  4939. // And pass along -I options
  4940. Args.AddAllArgs(CmdArgs, options::OPT_I);
  4941. }
  4942. // Handle -fPIC et al -- the relocation-model affects the assembler
  4943. // for some targets.
  4944. llvm::Reloc::Model RelocationModel;
  4945. unsigned PICLevel;
  4946. bool IsPIE;
  4947. std::tie(RelocationModel, PICLevel, IsPIE) =
  4948. ParsePICArgs(getToolChain(), Triple, Args);
  4949. const char *RMName = RelocationModelName(RelocationModel);
  4950. if (RMName) {
  4951. CmdArgs.push_back("-mrelocation-model");
  4952. CmdArgs.push_back(RMName);
  4953. }
  4954. // Optionally embed the -cc1as level arguments into the debug info, for build
  4955. // analysis.
  4956. if (getToolChain().UseDwarfDebugFlags()) {
  4957. ArgStringList OriginalArgs;
  4958. for (const auto &Arg : Args)
  4959. Arg->render(Args, OriginalArgs);
  4960. SmallString<256> Flags;
  4961. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  4962. Flags += Exec;
  4963. for (const char *OriginalArg : OriginalArgs) {
  4964. SmallString<128> EscapedArg;
  4965. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  4966. Flags += " ";
  4967. Flags += EscapedArg;
  4968. }
  4969. CmdArgs.push_back("-dwarf-debug-flags");
  4970. CmdArgs.push_back(Args.MakeArgString(Flags));
  4971. }
  4972. // FIXME: Add -static support, once we have it.
  4973. // Add target specific flags.
  4974. switch (getToolChain().getArch()) {
  4975. default:
  4976. break;
  4977. case llvm::Triple::mips:
  4978. case llvm::Triple::mipsel:
  4979. case llvm::Triple::mips64:
  4980. case llvm::Triple::mips64el:
  4981. AddMIPSTargetArgs(Args, CmdArgs);
  4982. break;
  4983. }
  4984. // Consume all the warning flags. Usually this would be handled more
  4985. // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
  4986. // doesn't handle that so rather than warning about unused flags that are
  4987. // actually used, we'll lie by omission instead.
  4988. // FIXME: Stop lying and consume only the appropriate driver flags
  4989. for (const Arg *A : Args.filtered(options::OPT_W_Group))
  4990. A->claim();
  4991. CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
  4992. getToolChain().getDriver());
  4993. Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
  4994. assert(Output.isFilename() && "Unexpected lipo output.");
  4995. CmdArgs.push_back("-o");
  4996. CmdArgs.push_back(Output.getFilename());
  4997. assert(Input.isFilename() && "Invalid input.");
  4998. CmdArgs.push_back(Input.getFilename());
  4999. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5000. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5001. // Handle the debug info splitting at object creation time if we're
  5002. // creating an object.
  5003. // TODO: Currently only works on linux with newer objcopy.
  5004. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  5005. getToolChain().getTriple().isOSLinux())
  5006. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  5007. SplitDebugName(Args, Input));
  5008. }
  5009. void GnuTool::anchor() {}
  5010. void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
  5011. const InputInfo &Output,
  5012. const InputInfoList &Inputs, const ArgList &Args,
  5013. const char *LinkingOutput) const {
  5014. const Driver &D = getToolChain().getDriver();
  5015. ArgStringList CmdArgs;
  5016. for (const auto &A : Args) {
  5017. if (forwardToGCC(A->getOption())) {
  5018. // Don't forward any -g arguments to assembly steps.
  5019. if (isa<AssembleJobAction>(JA) &&
  5020. A->getOption().matches(options::OPT_g_Group))
  5021. continue;
  5022. // Don't forward any -W arguments to assembly and link steps.
  5023. if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
  5024. A->getOption().matches(options::OPT_W_Group))
  5025. continue;
  5026. // It is unfortunate that we have to claim here, as this means
  5027. // we will basically never report anything interesting for
  5028. // platforms using a generic gcc, even if we are just using gcc
  5029. // to get to the assembler.
  5030. A->claim();
  5031. A->render(Args, CmdArgs);
  5032. }
  5033. }
  5034. RenderExtraToolArgs(JA, CmdArgs);
  5035. // If using a driver driver, force the arch.
  5036. if (getToolChain().getTriple().isOSDarwin()) {
  5037. CmdArgs.push_back("-arch");
  5038. CmdArgs.push_back(
  5039. Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
  5040. }
  5041. // Try to force gcc to match the tool chain we want, if we recognize
  5042. // the arch.
  5043. //
  5044. // FIXME: The triple class should directly provide the information we want
  5045. // here.
  5046. switch (getToolChain().getArch()) {
  5047. default:
  5048. break;
  5049. case llvm::Triple::x86:
  5050. case llvm::Triple::ppc:
  5051. CmdArgs.push_back("-m32");
  5052. break;
  5053. case llvm::Triple::x86_64:
  5054. case llvm::Triple::ppc64:
  5055. case llvm::Triple::ppc64le:
  5056. CmdArgs.push_back("-m64");
  5057. break;
  5058. case llvm::Triple::sparcel:
  5059. CmdArgs.push_back("-EL");
  5060. break;
  5061. }
  5062. if (Output.isFilename()) {
  5063. CmdArgs.push_back("-o");
  5064. CmdArgs.push_back(Output.getFilename());
  5065. } else {
  5066. assert(Output.isNothing() && "Unexpected output");
  5067. CmdArgs.push_back("-fsyntax-only");
  5068. }
  5069. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5070. // Only pass -x if gcc will understand it; otherwise hope gcc
  5071. // understands the suffix correctly. The main use case this would go
  5072. // wrong in is for linker inputs if they happened to have an odd
  5073. // suffix; really the only way to get this to happen is a command
  5074. // like '-x foobar a.c' which will treat a.c like a linker input.
  5075. //
  5076. // FIXME: For the linker case specifically, can we safely convert
  5077. // inputs into '-Wl,' options?
  5078. for (const auto &II : Inputs) {
  5079. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5080. if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
  5081. II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
  5082. D.Diag(diag::err_drv_no_linker_llvm_support)
  5083. << getToolChain().getTripleString();
  5084. else if (II.getType() == types::TY_AST)
  5085. D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
  5086. else if (II.getType() == types::TY_ModuleFile)
  5087. D.Diag(diag::err_drv_no_module_support)
  5088. << getToolChain().getTripleString();
  5089. if (types::canTypeBeUserSpecified(II.getType())) {
  5090. CmdArgs.push_back("-x");
  5091. CmdArgs.push_back(types::getTypeName(II.getType()));
  5092. }
  5093. if (II.isFilename())
  5094. CmdArgs.push_back(II.getFilename());
  5095. else {
  5096. const Arg &A = II.getInputArg();
  5097. // Reverse translate some rewritten options.
  5098. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
  5099. CmdArgs.push_back("-lstdc++");
  5100. continue;
  5101. }
  5102. // Don't render as input, we need gcc to do the translations.
  5103. A.render(Args, CmdArgs);
  5104. }
  5105. }
  5106. const std::string customGCCName = D.getCCCGenericGCCName();
  5107. const char *GCCName;
  5108. if (!customGCCName.empty())
  5109. GCCName = customGCCName.c_str();
  5110. else if (D.CCCIsCXX()) {
  5111. GCCName = "g++";
  5112. } else
  5113. GCCName = "gcc";
  5114. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
  5115. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5116. }
  5117. void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
  5118. ArgStringList &CmdArgs) const {
  5119. CmdArgs.push_back("-E");
  5120. }
  5121. void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
  5122. ArgStringList &CmdArgs) const {
  5123. const Driver &D = getToolChain().getDriver();
  5124. switch (JA.getType()) {
  5125. // If -flto, etc. are present then make sure not to force assembly output.
  5126. case types::TY_LLVM_IR:
  5127. case types::TY_LTO_IR:
  5128. case types::TY_LLVM_BC:
  5129. case types::TY_LTO_BC:
  5130. CmdArgs.push_back("-c");
  5131. break;
  5132. case types::TY_PP_Asm:
  5133. CmdArgs.push_back("-S");
  5134. break;
  5135. case types::TY_Nothing:
  5136. CmdArgs.push_back("-fsyntax-only");
  5137. break;
  5138. default:
  5139. D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
  5140. }
  5141. }
  5142. void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
  5143. ArgStringList &CmdArgs) const {
  5144. // The types are (hopefully) good enough.
  5145. }
  5146. // Hexagon tools start.
  5147. void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
  5148. ArgStringList &CmdArgs) const {}
  5149. void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  5150. const InputInfo &Output,
  5151. const InputInfoList &Inputs,
  5152. const ArgList &Args,
  5153. const char *LinkingOutput) const {
  5154. claimNoWarnArgs(Args);
  5155. const Driver &D = getToolChain().getDriver();
  5156. ArgStringList CmdArgs;
  5157. std::string MarchString = "-march=";
  5158. MarchString += toolchains::HexagonToolChain::GetTargetCPU(Args);
  5159. CmdArgs.push_back(Args.MakeArgString(MarchString));
  5160. RenderExtraToolArgs(JA, CmdArgs);
  5161. if (Output.isFilename()) {
  5162. CmdArgs.push_back("-o");
  5163. CmdArgs.push_back(Output.getFilename());
  5164. } else {
  5165. assert(Output.isNothing() && "Unexpected output");
  5166. CmdArgs.push_back("-fsyntax-only");
  5167. }
  5168. if (const char *v = toolchains::HexagonToolChain::GetSmallDataThreshold(Args))
  5169. CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
  5170. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5171. // Only pass -x if gcc will understand it; otherwise hope gcc
  5172. // understands the suffix correctly. The main use case this would go
  5173. // wrong in is for linker inputs if they happened to have an odd
  5174. // suffix; really the only way to get this to happen is a command
  5175. // like '-x foobar a.c' which will treat a.c like a linker input.
  5176. //
  5177. // FIXME: For the linker case specifically, can we safely convert
  5178. // inputs into '-Wl,' options?
  5179. for (const auto &II : Inputs) {
  5180. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5181. if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
  5182. II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
  5183. D.Diag(clang::diag::err_drv_no_linker_llvm_support)
  5184. << getToolChain().getTripleString();
  5185. else if (II.getType() == types::TY_AST)
  5186. D.Diag(clang::diag::err_drv_no_ast_support)
  5187. << getToolChain().getTripleString();
  5188. else if (II.getType() == types::TY_ModuleFile)
  5189. D.Diag(diag::err_drv_no_module_support)
  5190. << getToolChain().getTripleString();
  5191. if (II.isFilename())
  5192. CmdArgs.push_back(II.getFilename());
  5193. else
  5194. // Don't render as input, we need gcc to do the translations.
  5195. // FIXME: Pranav: What is this ?
  5196. II.getInputArg().render(Args, CmdArgs);
  5197. }
  5198. const char *GCCName = "hexagon-as";
  5199. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
  5200. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5201. }
  5202. void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
  5203. ArgStringList &CmdArgs) const {
  5204. // The types are (hopefully) good enough.
  5205. }
  5206. static void
  5207. constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
  5208. const toolchains::HexagonToolChain &ToolChain,
  5209. const InputInfo &Output, const InputInfoList &Inputs,
  5210. const ArgList &Args, ArgStringList &CmdArgs,
  5211. const char *LinkingOutput) {
  5212. const Driver &D = ToolChain.getDriver();
  5213. //----------------------------------------------------------------------------
  5214. //
  5215. //----------------------------------------------------------------------------
  5216. bool hasStaticArg = Args.hasArg(options::OPT_static);
  5217. bool buildingLib = Args.hasArg(options::OPT_shared);
  5218. bool buildPIE = Args.hasArg(options::OPT_pie);
  5219. bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
  5220. bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
  5221. bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
  5222. bool useG0 = false;
  5223. bool useShared = buildingLib && !hasStaticArg;
  5224. //----------------------------------------------------------------------------
  5225. // Silence warnings for various options
  5226. //----------------------------------------------------------------------------
  5227. Args.ClaimAllArgs(options::OPT_g_Group);
  5228. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5229. Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
  5230. // handled somewhere else.
  5231. Args.ClaimAllArgs(options::OPT_static_libgcc);
  5232. //----------------------------------------------------------------------------
  5233. //
  5234. //----------------------------------------------------------------------------
  5235. for (const auto &Opt : ToolChain.ExtraOpts)
  5236. CmdArgs.push_back(Opt.c_str());
  5237. std::string MarchString = toolchains::HexagonToolChain::GetTargetCPU(Args);
  5238. CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
  5239. if (buildingLib) {
  5240. CmdArgs.push_back("-shared");
  5241. CmdArgs.push_back("-call_shared"); // should be the default, but doing as
  5242. // hexagon-gcc does
  5243. }
  5244. if (hasStaticArg)
  5245. CmdArgs.push_back("-static");
  5246. if (buildPIE && !buildingLib)
  5247. CmdArgs.push_back("-pie");
  5248. if (const char *v =
  5249. toolchains::HexagonToolChain::GetSmallDataThreshold(Args)) {
  5250. CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
  5251. useG0 = toolchains::HexagonToolChain::UsesG0(v);
  5252. }
  5253. //----------------------------------------------------------------------------
  5254. //
  5255. //----------------------------------------------------------------------------
  5256. CmdArgs.push_back("-o");
  5257. CmdArgs.push_back(Output.getFilename());
  5258. const std::string MarchSuffix = "/" + MarchString;
  5259. const std::string G0Suffix = "/G0";
  5260. const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
  5261. const std::string RootDir = ToolChain.GetGnuDir(D.InstalledDir, Args) + "/";
  5262. const std::string StartFilesDir =
  5263. RootDir + "hexagon/lib" + (useG0 ? MarchG0Suffix : MarchSuffix);
  5264. //----------------------------------------------------------------------------
  5265. // moslib
  5266. //----------------------------------------------------------------------------
  5267. std::vector<std::string> oslibs;
  5268. bool hasStandalone = false;
  5269. for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
  5270. A->claim();
  5271. oslibs.emplace_back(A->getValue());
  5272. hasStandalone = hasStandalone || (oslibs.back() == "standalone");
  5273. }
  5274. if (oslibs.empty()) {
  5275. oslibs.push_back("standalone");
  5276. hasStandalone = true;
  5277. }
  5278. //----------------------------------------------------------------------------
  5279. // Start Files
  5280. //----------------------------------------------------------------------------
  5281. if (incStdLib && incStartFiles) {
  5282. if (!buildingLib) {
  5283. if (hasStandalone) {
  5284. CmdArgs.push_back(
  5285. Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
  5286. }
  5287. CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
  5288. }
  5289. std::string initObj = useShared ? "/initS.o" : "/init.o";
  5290. CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
  5291. }
  5292. //----------------------------------------------------------------------------
  5293. // Library Search Paths
  5294. //----------------------------------------------------------------------------
  5295. const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
  5296. for (const auto &LibPath : LibPaths)
  5297. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
  5298. //----------------------------------------------------------------------------
  5299. //
  5300. //----------------------------------------------------------------------------
  5301. Args.AddAllArgs(CmdArgs,
  5302. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  5303. options::OPT_t, options::OPT_u_Group});
  5304. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  5305. //----------------------------------------------------------------------------
  5306. // Libraries
  5307. //----------------------------------------------------------------------------
  5308. if (incStdLib && incDefLibs) {
  5309. if (D.CCCIsCXX()) {
  5310. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  5311. CmdArgs.push_back("-lm");
  5312. }
  5313. CmdArgs.push_back("--start-group");
  5314. if (!buildingLib) {
  5315. for (const std::string &Lib : oslibs)
  5316. CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
  5317. CmdArgs.push_back("-lc");
  5318. }
  5319. CmdArgs.push_back("-lgcc");
  5320. CmdArgs.push_back("--end-group");
  5321. }
  5322. //----------------------------------------------------------------------------
  5323. // End files
  5324. //----------------------------------------------------------------------------
  5325. if (incStdLib && incStartFiles) {
  5326. std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
  5327. CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
  5328. }
  5329. }
  5330. void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5331. const InputInfo &Output,
  5332. const InputInfoList &Inputs,
  5333. const ArgList &Args,
  5334. const char *LinkingOutput) const {
  5335. const toolchains::HexagonToolChain &ToolChain =
  5336. static_cast<const toolchains::HexagonToolChain &>(getToolChain());
  5337. ArgStringList CmdArgs;
  5338. constructHexagonLinkArgs(C, JA, ToolChain, Output, Inputs, Args, CmdArgs,
  5339. LinkingOutput);
  5340. std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
  5341. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  5342. CmdArgs, Inputs));
  5343. }
  5344. // Hexagon tools end.
  5345. void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5346. const InputInfo &Output,
  5347. const InputInfoList &Inputs,
  5348. const ArgList &Args,
  5349. const char *LinkingOutput) const {
  5350. std::string Linker = getToolChain().GetProgramPath(getShortName());
  5351. ArgStringList CmdArgs;
  5352. CmdArgs.push_back("-flavor");
  5353. CmdArgs.push_back("gnu");
  5354. CmdArgs.push_back("-target");
  5355. CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
  5356. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  5357. CmdArgs.push_back("-o");
  5358. CmdArgs.push_back(Output.getFilename());
  5359. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  5360. CmdArgs, Inputs));
  5361. }
  5362. // AMDGPU tools end.
  5363. const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
  5364. std::string MArch;
  5365. if (!Arch.empty())
  5366. MArch = Arch;
  5367. else
  5368. MArch = Triple.getArchName();
  5369. MArch = StringRef(MArch).lower();
  5370. // Handle -march=native.
  5371. if (MArch == "native") {
  5372. std::string CPU = llvm::sys::getHostCPUName();
  5373. if (CPU != "generic") {
  5374. // Translate the native cpu into the architecture suffix for that CPU.
  5375. StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
  5376. // If there is no valid architecture suffix for this CPU we don't know how
  5377. // to handle it, so return no architecture.
  5378. if (Suffix.empty())
  5379. MArch = "";
  5380. else
  5381. MArch = std::string("arm") + Suffix.str();
  5382. }
  5383. }
  5384. return MArch;
  5385. }
  5386. /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
  5387. StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
  5388. std::string MArch = getARMArch(Arch, Triple);
  5389. // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
  5390. // here means an -march=native that we can't handle, so instead return no CPU.
  5391. if (MArch.empty())
  5392. return StringRef();
  5393. // We need to return an empty string here on invalid MArch values as the
  5394. // various places that call this function can't cope with a null result.
  5395. return Triple.getARMCPUForArch(MArch);
  5396. }
  5397. /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
  5398. std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
  5399. const llvm::Triple &Triple) {
  5400. // FIXME: Warn on inconsistent use of -mcpu and -march.
  5401. // If we have -mcpu=, use that.
  5402. if (!CPU.empty()) {
  5403. std::string MCPU = StringRef(CPU).lower();
  5404. // Handle -mcpu=native.
  5405. if (MCPU == "native")
  5406. return llvm::sys::getHostCPUName();
  5407. else
  5408. return MCPU;
  5409. }
  5410. return getARMCPUForMArch(Arch, Triple);
  5411. }
  5412. /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
  5413. /// CPU (or Arch, if CPU is generic).
  5414. // FIXME: This is redundant with -mcpu, why does LLVM use this.
  5415. StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
  5416. const llvm::Triple &Triple) {
  5417. unsigned ArchKind;
  5418. if (CPU == "generic") {
  5419. std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
  5420. ArchKind = llvm::ARM::parseArch(ARMArch);
  5421. if (ArchKind == llvm::ARM::AK_INVALID)
  5422. // In case of generic Arch, i.e. "arm",
  5423. // extract arch from default cpu of the Triple
  5424. ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
  5425. } else {
  5426. ArchKind = llvm::ARM::parseCPUArch(CPU);
  5427. }
  5428. if (ArchKind == llvm::ARM::AK_INVALID)
  5429. return "";
  5430. return llvm::ARM::getSubArch(ArchKind);
  5431. }
  5432. void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
  5433. const llvm::Triple &Triple) {
  5434. if (Args.hasArg(options::OPT_r))
  5435. return;
  5436. // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
  5437. // to generate BE-8 executables.
  5438. if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
  5439. CmdArgs.push_back("--be8");
  5440. }
  5441. mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
  5442. // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
  5443. // was first introduced in Release 3. However, other compilers have
  5444. // traditionally allowed it for Release 2 so we should do the same.
  5445. return (NanEncoding)llvm::StringSwitch<int>(CPU)
  5446. .Case("mips1", NanLegacy)
  5447. .Case("mips2", NanLegacy)
  5448. .Case("mips3", NanLegacy)
  5449. .Case("mips4", NanLegacy)
  5450. .Case("mips5", NanLegacy)
  5451. .Case("mips32", NanLegacy)
  5452. .Case("mips32r2", NanLegacy | Nan2008)
  5453. .Case("mips32r3", NanLegacy | Nan2008)
  5454. .Case("mips32r5", NanLegacy | Nan2008)
  5455. .Case("mips32r6", Nan2008)
  5456. .Case("mips64", NanLegacy)
  5457. .Case("mips64r2", NanLegacy | Nan2008)
  5458. .Case("mips64r3", NanLegacy | Nan2008)
  5459. .Case("mips64r5", NanLegacy | Nan2008)
  5460. .Case("mips64r6", Nan2008)
  5461. .Default(NanLegacy);
  5462. }
  5463. bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
  5464. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  5465. return A && (A->getValue() == StringRef(Value));
  5466. }
  5467. bool mips::isUCLibc(const ArgList &Args) {
  5468. Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
  5469. return A && A->getOption().matches(options::OPT_muclibc);
  5470. }
  5471. bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
  5472. if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
  5473. return llvm::StringSwitch<bool>(NaNArg->getValue())
  5474. .Case("2008", true)
  5475. .Case("legacy", false)
  5476. .Default(false);
  5477. // NaN2008 is the default for MIPS32r6/MIPS64r6.
  5478. return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
  5479. .Cases("mips32r6", "mips64r6", true)
  5480. .Default(false);
  5481. return false;
  5482. }
  5483. bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
  5484. StringRef ABIName, mips::FloatABI FloatABI) {
  5485. if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
  5486. Triple.getVendor() != llvm::Triple::MipsTechnologies)
  5487. return false;
  5488. if (ABIName != "32")
  5489. return false;
  5490. // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
  5491. // present.
  5492. if (FloatABI == mips::FloatABI::Soft)
  5493. return false;
  5494. return llvm::StringSwitch<bool>(CPUName)
  5495. .Cases("mips2", "mips3", "mips4", "mips5", true)
  5496. .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
  5497. .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
  5498. .Default(false);
  5499. }
  5500. bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
  5501. StringRef CPUName, StringRef ABIName,
  5502. mips::FloatABI FloatABI) {
  5503. bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
  5504. // FPXX shouldn't be used if -msingle-float is present.
  5505. if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
  5506. options::OPT_mdouble_float))
  5507. if (A->getOption().matches(options::OPT_msingle_float))
  5508. UseFPXX = false;
  5509. return UseFPXX;
  5510. }
  5511. llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
  5512. // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
  5513. // archs which Darwin doesn't use.
  5514. // The matching this routine does is fairly pointless, since it is neither the
  5515. // complete architecture list, nor a reasonable subset. The problem is that
  5516. // historically the driver driver accepts this and also ties its -march=
  5517. // handling to the architecture name, so we need to be careful before removing
  5518. // support for it.
  5519. // This code must be kept in sync with Clang's Darwin specific argument
  5520. // translation.
  5521. return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
  5522. .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
  5523. .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
  5524. .Case("ppc64", llvm::Triple::ppc64)
  5525. .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
  5526. .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
  5527. llvm::Triple::x86)
  5528. .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
  5529. // This is derived from the driver driver.
  5530. .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
  5531. .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
  5532. .Cases("armv7s", "xscale", llvm::Triple::arm)
  5533. .Case("arm64", llvm::Triple::aarch64)
  5534. .Case("r600", llvm::Triple::r600)
  5535. .Case("amdgcn", llvm::Triple::amdgcn)
  5536. .Case("nvptx", llvm::Triple::nvptx)
  5537. .Case("nvptx64", llvm::Triple::nvptx64)
  5538. .Case("amdil", llvm::Triple::amdil)
  5539. .Case("spir", llvm::Triple::spir)
  5540. .Default(llvm::Triple::UnknownArch);
  5541. }
  5542. void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
  5543. const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
  5544. T.setArch(Arch);
  5545. if (Str == "x86_64h")
  5546. T.setArchName(Str);
  5547. else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
  5548. T.setOS(llvm::Triple::UnknownOS);
  5549. T.setObjectFormat(llvm::Triple::MachO);
  5550. }
  5551. }
  5552. const char *Clang::getBaseInputName(const ArgList &Args,
  5553. const InputInfo &Input) {
  5554. return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
  5555. }
  5556. const char *Clang::getBaseInputStem(const ArgList &Args,
  5557. const InputInfoList &Inputs) {
  5558. const char *Str = getBaseInputName(Args, Inputs[0]);
  5559. if (const char *End = strrchr(Str, '.'))
  5560. return Args.MakeArgString(std::string(Str, End));
  5561. return Str;
  5562. }
  5563. const char *Clang::getDependencyFileName(const ArgList &Args,
  5564. const InputInfoList &Inputs) {
  5565. // FIXME: Think about this more.
  5566. std::string Res;
  5567. if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
  5568. std::string Str(OutputOpt->getValue());
  5569. Res = Str.substr(0, Str.rfind('.'));
  5570. } else {
  5571. Res = getBaseInputStem(Args, Inputs);
  5572. }
  5573. return Args.MakeArgString(Res + ".d");
  5574. }
  5575. void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5576. const InputInfo &Output,
  5577. const InputInfoList &Inputs,
  5578. const ArgList &Args,
  5579. const char *LinkingOutput) const {
  5580. const ToolChain &ToolChain = getToolChain();
  5581. const Driver &D = ToolChain.getDriver();
  5582. ArgStringList CmdArgs;
  5583. // Silence warning for "clang -g foo.o -o foo"
  5584. Args.ClaimAllArgs(options::OPT_g_Group);
  5585. // and "clang -emit-llvm foo.o -o foo"
  5586. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5587. // and for "clang -w foo.o -o foo". Other warning options are already
  5588. // handled somewhere else.
  5589. Args.ClaimAllArgs(options::OPT_w);
  5590. if (!D.SysRoot.empty())
  5591. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  5592. // CloudABI only supports static linkage.
  5593. CmdArgs.push_back("-Bstatic");
  5594. CmdArgs.push_back("--eh-frame-hdr");
  5595. CmdArgs.push_back("--gc-sections");
  5596. if (Output.isFilename()) {
  5597. CmdArgs.push_back("-o");
  5598. CmdArgs.push_back(Output.getFilename());
  5599. } else {
  5600. assert(Output.isNothing() && "Invalid output.");
  5601. }
  5602. if (!Args.hasArg(options::OPT_nostdlib) &&
  5603. !Args.hasArg(options::OPT_nostartfiles)) {
  5604. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
  5605. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
  5606. }
  5607. Args.AddAllArgs(CmdArgs, options::OPT_L);
  5608. const ToolChain::path_list &Paths = ToolChain.getFilePaths();
  5609. for (const auto &Path : Paths)
  5610. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
  5611. Args.AddAllArgs(CmdArgs,
  5612. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  5613. options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
  5614. if (D.IsUsingLTO(Args))
  5615. AddGoldPlugin(ToolChain, Args, CmdArgs);
  5616. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  5617. if (!Args.hasArg(options::OPT_nostdlib) &&
  5618. !Args.hasArg(options::OPT_nodefaultlibs)) {
  5619. if (D.CCCIsCXX())
  5620. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  5621. CmdArgs.push_back("-lc");
  5622. CmdArgs.push_back("-lcompiler_rt");
  5623. }
  5624. if (!Args.hasArg(options::OPT_nostdlib) &&
  5625. !Args.hasArg(options::OPT_nostartfiles))
  5626. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  5627. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  5628. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5629. }
  5630. void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  5631. const InputInfo &Output,
  5632. const InputInfoList &Inputs,
  5633. const ArgList &Args,
  5634. const char *LinkingOutput) const {
  5635. ArgStringList CmdArgs;
  5636. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  5637. const InputInfo &Input = Inputs[0];
  5638. // Determine the original source input.
  5639. const Action *SourceAction = &JA;
  5640. while (SourceAction->getKind() != Action::InputClass) {
  5641. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  5642. SourceAction = SourceAction->getInputs()[0];
  5643. }
  5644. // If -fno_integrated_as is used add -Q to the darwin assember driver to make
  5645. // sure it runs its system assembler not clang's integrated assembler.
  5646. // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
  5647. // FIXME: at run-time detect assembler capabilities or rely on version
  5648. // information forwarded by -target-assembler-version (future)
  5649. if (Args.hasArg(options::OPT_fno_integrated_as)) {
  5650. const llvm::Triple &T(getToolChain().getTriple());
  5651. if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
  5652. CmdArgs.push_back("-Q");
  5653. }
  5654. // Forward -g, assuming we are dealing with an actual assembly file.
  5655. if (SourceAction->getType() == types::TY_Asm ||
  5656. SourceAction->getType() == types::TY_PP_Asm) {
  5657. if (Args.hasArg(options::OPT_gstabs))
  5658. CmdArgs.push_back("--gstabs");
  5659. else if (Args.hasArg(options::OPT_g_Group))
  5660. CmdArgs.push_back("-g");
  5661. }
  5662. // Derived from asm spec.
  5663. AddMachOArch(Args, CmdArgs);
  5664. // Use -force_cpusubtype_ALL on x86 by default.
  5665. if (getToolChain().getArch() == llvm::Triple::x86 ||
  5666. getToolChain().getArch() == llvm::Triple::x86_64 ||
  5667. Args.hasArg(options::OPT_force__cpusubtype__ALL))
  5668. CmdArgs.push_back("-force_cpusubtype_ALL");
  5669. if (getToolChain().getArch() != llvm::Triple::x86_64 &&
  5670. (((Args.hasArg(options::OPT_mkernel) ||
  5671. Args.hasArg(options::OPT_fapple_kext)) &&
  5672. getMachOToolChain().isKernelStatic()) ||
  5673. Args.hasArg(options::OPT_static)))
  5674. CmdArgs.push_back("-static");
  5675. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5676. assert(Output.isFilename() && "Unexpected lipo output.");
  5677. CmdArgs.push_back("-o");
  5678. CmdArgs.push_back(Output.getFilename());
  5679. assert(Input.isFilename() && "Invalid input.");
  5680. CmdArgs.push_back(Input.getFilename());
  5681. // asm_final spec is empty.
  5682. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  5683. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5684. }
  5685. void darwin::MachOTool::anchor() {}
  5686. void darwin::MachOTool::AddMachOArch(const ArgList &Args,
  5687. ArgStringList &CmdArgs) const {
  5688. StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
  5689. // Derived from darwin_arch spec.
  5690. CmdArgs.push_back("-arch");
  5691. CmdArgs.push_back(Args.MakeArgString(ArchName));
  5692. // FIXME: Is this needed anymore?
  5693. if (ArchName == "arm")
  5694. CmdArgs.push_back("-force_cpusubtype_ALL");
  5695. }
  5696. bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
  5697. // We only need to generate a temp path for LTO if we aren't compiling object
  5698. // files. When compiling source files, we run 'dsymutil' after linking. We
  5699. // don't run 'dsymutil' when compiling object files.
  5700. for (const auto &Input : Inputs)
  5701. if (Input.getType() != types::TY_Object)
  5702. return true;
  5703. return false;
  5704. }
  5705. void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
  5706. ArgStringList &CmdArgs,
  5707. const InputInfoList &Inputs) const {
  5708. const Driver &D = getToolChain().getDriver();
  5709. const toolchains::MachO &MachOTC = getMachOToolChain();
  5710. unsigned Version[3] = {0, 0, 0};
  5711. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  5712. bool HadExtra;
  5713. if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
  5714. Version[2], HadExtra) ||
  5715. HadExtra)
  5716. D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
  5717. }
  5718. // Newer linkers support -demangle. Pass it if supported and not disabled by
  5719. // the user.
  5720. if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  5721. CmdArgs.push_back("-demangle");
  5722. if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
  5723. CmdArgs.push_back("-export_dynamic");
  5724. // If we are using App Extension restrictions, pass a flag to the linker
  5725. // telling it that the compiled code has been audited.
  5726. if (Args.hasFlag(options::OPT_fapplication_extension,
  5727. options::OPT_fno_application_extension, false))
  5728. CmdArgs.push_back("-application_extension");
  5729. if (D.IsUsingLTO(Args)) {
  5730. // If we are using LTO, then automatically create a temporary file path for
  5731. // the linker to use, so that it's lifetime will extend past a possible
  5732. // dsymutil step.
  5733. if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
  5734. const char *TmpPath = C.getArgs().MakeArgString(
  5735. D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
  5736. C.addTempFile(TmpPath);
  5737. CmdArgs.push_back("-object_path_lto");
  5738. CmdArgs.push_back(TmpPath);
  5739. }
  5740. // Use -lto_library option to specify the libLTO.dylib path. Try to find
  5741. // it in clang installed libraries. If not found, the option is not used
  5742. // and 'ld' will use its default mechanism to search for libLTO.dylib.
  5743. if (Version[0] >= 133) {
  5744. // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
  5745. StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
  5746. SmallString<128> LibLTOPath(P);
  5747. llvm::sys::path::append(LibLTOPath, "lib");
  5748. llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
  5749. if (llvm::sys::fs::exists(LibLTOPath)) {
  5750. CmdArgs.push_back("-lto_library");
  5751. CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
  5752. } else {
  5753. D.Diag(diag::warn_drv_lto_libpath);
  5754. }
  5755. }
  5756. }
  5757. // Derived from the "link" spec.
  5758. Args.AddAllArgs(CmdArgs, options::OPT_static);
  5759. if (!Args.hasArg(options::OPT_static))
  5760. CmdArgs.push_back("-dynamic");
  5761. if (Args.hasArg(options::OPT_fgnu_runtime)) {
  5762. // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
  5763. // here. How do we wish to handle such things?
  5764. }
  5765. if (!Args.hasArg(options::OPT_dynamiclib)) {
  5766. AddMachOArch(Args, CmdArgs);
  5767. // FIXME: Why do this only on this path?
  5768. Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
  5769. Args.AddLastArg(CmdArgs, options::OPT_bundle);
  5770. Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
  5771. Args.AddAllArgs(CmdArgs, options::OPT_client__name);
  5772. Arg *A;
  5773. if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
  5774. (A = Args.getLastArg(options::OPT_current__version)) ||
  5775. (A = Args.getLastArg(options::OPT_install__name)))
  5776. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  5777. << "-dynamiclib";
  5778. Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
  5779. Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
  5780. Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
  5781. } else {
  5782. CmdArgs.push_back("-dylib");
  5783. Arg *A;
  5784. if ((A = Args.getLastArg(options::OPT_bundle)) ||
  5785. (A = Args.getLastArg(options::OPT_bundle__loader)) ||
  5786. (A = Args.getLastArg(options::OPT_client__name)) ||
  5787. (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
  5788. (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
  5789. (A = Args.getLastArg(options::OPT_private__bundle)))
  5790. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  5791. << "-dynamiclib";
  5792. Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
  5793. "-dylib_compatibility_version");
  5794. Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
  5795. "-dylib_current_version");
  5796. AddMachOArch(Args, CmdArgs);
  5797. Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
  5798. "-dylib_install_name");
  5799. }
  5800. Args.AddLastArg(CmdArgs, options::OPT_all__load);
  5801. Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
  5802. Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
  5803. if (MachOTC.isTargetIOSBased())
  5804. Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
  5805. Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
  5806. Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
  5807. Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
  5808. Args.AddLastArg(CmdArgs, options::OPT_dynamic);
  5809. Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
  5810. Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
  5811. Args.AddAllArgs(CmdArgs, options::OPT_force__load);
  5812. Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
  5813. Args.AddAllArgs(CmdArgs, options::OPT_image__base);
  5814. Args.AddAllArgs(CmdArgs, options::OPT_init);
  5815. // Add the deployment target.
  5816. MachOTC.addMinVersionArgs(Args, CmdArgs);
  5817. Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
  5818. Args.AddLastArg(CmdArgs, options::OPT_multi__module);
  5819. Args.AddLastArg(CmdArgs, options::OPT_single__module);
  5820. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
  5821. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
  5822. if (const Arg *A =
  5823. Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
  5824. options::OPT_fno_pie, options::OPT_fno_PIE)) {
  5825. if (A->getOption().matches(options::OPT_fpie) ||
  5826. A->getOption().matches(options::OPT_fPIE))
  5827. CmdArgs.push_back("-pie");
  5828. else
  5829. CmdArgs.push_back("-no_pie");
  5830. }
  5831. Args.AddLastArg(CmdArgs, options::OPT_prebind);
  5832. Args.AddLastArg(CmdArgs, options::OPT_noprebind);
  5833. Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
  5834. Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
  5835. Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
  5836. Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
  5837. Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
  5838. Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
  5839. Args.AddAllArgs(CmdArgs, options::OPT_segprot);
  5840. Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
  5841. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
  5842. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
  5843. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
  5844. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
  5845. Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
  5846. Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
  5847. // Give --sysroot= preference, over the Apple specific behavior to also use
  5848. // --isysroot as the syslibroot.
  5849. StringRef sysroot = C.getSysRoot();
  5850. if (sysroot != "") {
  5851. CmdArgs.push_back("-syslibroot");
  5852. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  5853. } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  5854. CmdArgs.push_back("-syslibroot");
  5855. CmdArgs.push_back(A->getValue());
  5856. }
  5857. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
  5858. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
  5859. Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
  5860. Args.AddAllArgs(CmdArgs, options::OPT_undefined);
  5861. Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
  5862. Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
  5863. Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
  5864. Args.AddAllArgs(CmdArgs, options::OPT_y);
  5865. Args.AddLastArg(CmdArgs, options::OPT_w);
  5866. Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
  5867. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
  5868. Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
  5869. Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
  5870. Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
  5871. Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
  5872. Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
  5873. Args.AddLastArg(CmdArgs, options::OPT_whyload);
  5874. Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
  5875. Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
  5876. Args.AddLastArg(CmdArgs, options::OPT_dylinker);
  5877. Args.AddLastArg(CmdArgs, options::OPT_Mach);
  5878. }
  5879. void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5880. const InputInfo &Output,
  5881. const InputInfoList &Inputs,
  5882. const ArgList &Args,
  5883. const char *LinkingOutput) const {
  5884. assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
  5885. // If the number of arguments surpasses the system limits, we will encode the
  5886. // input files in a separate file, shortening the command line. To this end,
  5887. // build a list of input file names that can be passed via a file with the
  5888. // -filelist linker option.
  5889. llvm::opt::ArgStringList InputFileList;
  5890. // The logic here is derived from gcc's behavior; most of which
  5891. // comes from specs (starting with link_command). Consult gcc for
  5892. // more information.
  5893. ArgStringList CmdArgs;
  5894. /// Hack(tm) to ignore linking errors when we are doing ARC migration.
  5895. if (Args.hasArg(options::OPT_ccc_arcmt_check,
  5896. options::OPT_ccc_arcmt_migrate)) {
  5897. for (const auto &Arg : Args)
  5898. Arg->claim();
  5899. const char *Exec =
  5900. Args.MakeArgString(getToolChain().GetProgramPath("touch"));
  5901. CmdArgs.push_back(Output.getFilename());
  5902. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
  5903. return;
  5904. }
  5905. // I'm not sure why this particular decomposition exists in gcc, but
  5906. // we follow suite for ease of comparison.
  5907. AddLinkArgs(C, Args, CmdArgs, Inputs);
  5908. // It seems that the 'e' option is completely ignored for dynamic executables
  5909. // (the default), and with static executables, the last one wins, as expected.
  5910. Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
  5911. options::OPT_Z_Flag, options::OPT_u_Group,
  5912. options::OPT_e, options::OPT_r});
  5913. // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
  5914. // members of static archive libraries which implement Objective-C classes or
  5915. // categories.
  5916. if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
  5917. CmdArgs.push_back("-ObjC");
  5918. CmdArgs.push_back("-o");
  5919. CmdArgs.push_back(Output.getFilename());
  5920. if (!Args.hasArg(options::OPT_nostdlib) &&
  5921. !Args.hasArg(options::OPT_nostartfiles))
  5922. getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
  5923. // SafeStack requires its own runtime libraries
  5924. // These libraries should be linked first, to make sure the
  5925. // __safestack_init constructor executes before everything else
  5926. if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
  5927. getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
  5928. "libclang_rt.safestack_osx.a",
  5929. /*AlwaysLink=*/true);
  5930. }
  5931. Args.AddAllArgs(CmdArgs, options::OPT_L);
  5932. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  5933. // Build the input file for -filelist (list of linker input files) in case we
  5934. // need it later
  5935. for (const auto &II : Inputs) {
  5936. if (!II.isFilename()) {
  5937. // This is a linker input argument.
  5938. // We cannot mix input arguments and file names in a -filelist input, thus
  5939. // we prematurely stop our list (remaining files shall be passed as
  5940. // arguments).
  5941. if (InputFileList.size() > 0)
  5942. break;
  5943. continue;
  5944. }
  5945. InputFileList.push_back(II.getFilename());
  5946. }
  5947. if (!Args.hasArg(options::OPT_nostdlib) &&
  5948. !Args.hasArg(options::OPT_nodefaultlibs))
  5949. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  5950. if (isObjCRuntimeLinked(Args) && !Args.hasArg(options::OPT_nostdlib) &&
  5951. !Args.hasArg(options::OPT_nodefaultlibs)) {
  5952. // We use arclite library for both ARC and subscripting support.
  5953. getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
  5954. CmdArgs.push_back("-framework");
  5955. CmdArgs.push_back("Foundation");
  5956. // Link libobj.
  5957. CmdArgs.push_back("-lobjc");
  5958. }
  5959. if (LinkingOutput) {
  5960. CmdArgs.push_back("-arch_multiple");
  5961. CmdArgs.push_back("-final_output");
  5962. CmdArgs.push_back(LinkingOutput);
  5963. }
  5964. if (Args.hasArg(options::OPT_fnested_functions))
  5965. CmdArgs.push_back("-allow_stack_execute");
  5966. // TODO: It would be nice to use addProfileRT() here, but darwin's compiler-rt
  5967. // paths are different enough from other toolchains that this needs a fair
  5968. // amount of refactoring done first.
  5969. getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
  5970. if (!Args.hasArg(options::OPT_nostdlib) &&
  5971. !Args.hasArg(options::OPT_nodefaultlibs)) {
  5972. if (getToolChain().getDriver().CCCIsCXX())
  5973. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  5974. // link_ssp spec is empty.
  5975. // Let the tool chain choose which runtime library to link.
  5976. getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
  5977. }
  5978. if (!Args.hasArg(options::OPT_nostdlib) &&
  5979. !Args.hasArg(options::OPT_nostartfiles)) {
  5980. // endfile_spec is empty.
  5981. }
  5982. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  5983. Args.AddAllArgs(CmdArgs, options::OPT_F);
  5984. // -iframework should be forwarded as -F.
  5985. for (const Arg *A : Args.filtered(options::OPT_iframework))
  5986. CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
  5987. if (!Args.hasArg(options::OPT_nostdlib) &&
  5988. !Args.hasArg(options::OPT_nodefaultlibs)) {
  5989. if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
  5990. if (A->getValue() == StringRef("Accelerate")) {
  5991. CmdArgs.push_back("-framework");
  5992. CmdArgs.push_back("Accelerate");
  5993. }
  5994. }
  5995. }
  5996. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  5997. std::unique_ptr<Command> Cmd =
  5998. llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
  5999. Cmd->setInputFileList(std::move(InputFileList));
  6000. C.addCommand(std::move(Cmd));
  6001. }
  6002. void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
  6003. const InputInfo &Output,
  6004. const InputInfoList &Inputs,
  6005. const ArgList &Args,
  6006. const char *LinkingOutput) const {
  6007. ArgStringList CmdArgs;
  6008. CmdArgs.push_back("-create");
  6009. assert(Output.isFilename() && "Unexpected lipo output.");
  6010. CmdArgs.push_back("-output");
  6011. CmdArgs.push_back(Output.getFilename());
  6012. for (const auto &II : Inputs) {
  6013. assert(II.isFilename() && "Unexpected lipo input.");
  6014. CmdArgs.push_back(II.getFilename());
  6015. }
  6016. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
  6017. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6018. }
  6019. void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
  6020. const InputInfo &Output,
  6021. const InputInfoList &Inputs,
  6022. const ArgList &Args,
  6023. const char *LinkingOutput) const {
  6024. ArgStringList CmdArgs;
  6025. CmdArgs.push_back("-o");
  6026. CmdArgs.push_back(Output.getFilename());
  6027. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6028. const InputInfo &Input = Inputs[0];
  6029. assert(Input.isFilename() && "Unexpected dsymutil input.");
  6030. CmdArgs.push_back(Input.getFilename());
  6031. const char *Exec =
  6032. Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
  6033. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6034. }
  6035. void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
  6036. const InputInfo &Output,
  6037. const InputInfoList &Inputs,
  6038. const ArgList &Args,
  6039. const char *LinkingOutput) const {
  6040. ArgStringList CmdArgs;
  6041. CmdArgs.push_back("--verify");
  6042. CmdArgs.push_back("--debug-info");
  6043. CmdArgs.push_back("--eh-frame");
  6044. CmdArgs.push_back("--quiet");
  6045. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6046. const InputInfo &Input = Inputs[0];
  6047. assert(Input.isFilename() && "Unexpected verify input");
  6048. // Grabbing the output of the earlier dsymutil run.
  6049. CmdArgs.push_back(Input.getFilename());
  6050. const char *Exec =
  6051. Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
  6052. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6053. }
  6054. void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6055. const InputInfo &Output,
  6056. const InputInfoList &Inputs,
  6057. const ArgList &Args,
  6058. const char *LinkingOutput) const {
  6059. claimNoWarnArgs(Args);
  6060. ArgStringList CmdArgs;
  6061. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6062. CmdArgs.push_back("-o");
  6063. CmdArgs.push_back(Output.getFilename());
  6064. for (const auto &II : Inputs)
  6065. CmdArgs.push_back(II.getFilename());
  6066. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6067. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6068. }
  6069. void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6070. const InputInfo &Output,
  6071. const InputInfoList &Inputs,
  6072. const ArgList &Args,
  6073. const char *LinkingOutput) const {
  6074. ArgStringList CmdArgs;
  6075. // Demangle C++ names in errors
  6076. CmdArgs.push_back("-C");
  6077. if ((!Args.hasArg(options::OPT_nostdlib)) &&
  6078. (!Args.hasArg(options::OPT_shared))) {
  6079. CmdArgs.push_back("-e");
  6080. CmdArgs.push_back("_start");
  6081. }
  6082. if (Args.hasArg(options::OPT_static)) {
  6083. CmdArgs.push_back("-Bstatic");
  6084. CmdArgs.push_back("-dn");
  6085. } else {
  6086. CmdArgs.push_back("-Bdynamic");
  6087. if (Args.hasArg(options::OPT_shared)) {
  6088. CmdArgs.push_back("-shared");
  6089. } else {
  6090. CmdArgs.push_back("--dynamic-linker");
  6091. CmdArgs.push_back(
  6092. Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
  6093. }
  6094. }
  6095. if (Output.isFilename()) {
  6096. CmdArgs.push_back("-o");
  6097. CmdArgs.push_back(Output.getFilename());
  6098. } else {
  6099. assert(Output.isNothing() && "Invalid output.");
  6100. }
  6101. if (!Args.hasArg(options::OPT_nostdlib) &&
  6102. !Args.hasArg(options::OPT_nostartfiles)) {
  6103. if (!Args.hasArg(options::OPT_shared))
  6104. CmdArgs.push_back(
  6105. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  6106. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  6107. CmdArgs.push_back(
  6108. Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
  6109. CmdArgs.push_back(
  6110. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6111. }
  6112. const ToolChain::path_list &Paths = getToolChain().getFilePaths();
  6113. for (const auto &Path : Paths)
  6114. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
  6115. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  6116. options::OPT_e, options::OPT_r});
  6117. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6118. if (!Args.hasArg(options::OPT_nostdlib) &&
  6119. !Args.hasArg(options::OPT_nodefaultlibs)) {
  6120. if (getToolChain().getDriver().CCCIsCXX())
  6121. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6122. CmdArgs.push_back("-lgcc_s");
  6123. CmdArgs.push_back("-lc");
  6124. if (!Args.hasArg(options::OPT_shared)) {
  6125. CmdArgs.push_back("-lgcc");
  6126. CmdArgs.push_back("-lm");
  6127. }
  6128. }
  6129. if (!Args.hasArg(options::OPT_nostdlib) &&
  6130. !Args.hasArg(options::OPT_nostartfiles)) {
  6131. CmdArgs.push_back(
  6132. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6133. }
  6134. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  6135. addProfileRT(getToolChain(), Args, CmdArgs);
  6136. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6137. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6138. }
  6139. void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6140. const InputInfo &Output,
  6141. const InputInfoList &Inputs,
  6142. const ArgList &Args,
  6143. const char *LinkingOutput) const {
  6144. claimNoWarnArgs(Args);
  6145. ArgStringList CmdArgs;
  6146. bool NeedsKPIC = false;
  6147. switch (getToolChain().getArch()) {
  6148. case llvm::Triple::x86:
  6149. // When building 32-bit code on OpenBSD/amd64, we have to explicitly
  6150. // instruct as in the base system to assemble 32-bit code.
  6151. CmdArgs.push_back("--32");
  6152. break;
  6153. case llvm::Triple::ppc:
  6154. CmdArgs.push_back("-mppc");
  6155. CmdArgs.push_back("-many");
  6156. break;
  6157. case llvm::Triple::sparc:
  6158. case llvm::Triple::sparcel:
  6159. CmdArgs.push_back("-32");
  6160. NeedsKPIC = true;
  6161. break;
  6162. case llvm::Triple::sparcv9:
  6163. CmdArgs.push_back("-64");
  6164. CmdArgs.push_back("-Av9a");
  6165. NeedsKPIC = true;
  6166. break;
  6167. case llvm::Triple::mips64:
  6168. case llvm::Triple::mips64el: {
  6169. StringRef CPUName;
  6170. StringRef ABIName;
  6171. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6172. CmdArgs.push_back("-mabi");
  6173. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6174. if (getToolChain().getArch() == llvm::Triple::mips64)
  6175. CmdArgs.push_back("-EB");
  6176. else
  6177. CmdArgs.push_back("-EL");
  6178. NeedsKPIC = true;
  6179. break;
  6180. }
  6181. default:
  6182. break;
  6183. }
  6184. if (NeedsKPIC)
  6185. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6186. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6187. CmdArgs.push_back("-o");
  6188. CmdArgs.push_back(Output.getFilename());
  6189. for (const auto &II : Inputs)
  6190. CmdArgs.push_back(II.getFilename());
  6191. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6192. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6193. }
  6194. void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6195. const InputInfo &Output,
  6196. const InputInfoList &Inputs,
  6197. const ArgList &Args,
  6198. const char *LinkingOutput) const {
  6199. const Driver &D = getToolChain().getDriver();
  6200. ArgStringList CmdArgs;
  6201. // Silence warning for "clang -g foo.o -o foo"
  6202. Args.ClaimAllArgs(options::OPT_g_Group);
  6203. // and "clang -emit-llvm foo.o -o foo"
  6204. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6205. // and for "clang -w foo.o -o foo". Other warning options are already
  6206. // handled somewhere else.
  6207. Args.ClaimAllArgs(options::OPT_w);
  6208. if (getToolChain().getArch() == llvm::Triple::mips64)
  6209. CmdArgs.push_back("-EB");
  6210. else if (getToolChain().getArch() == llvm::Triple::mips64el)
  6211. CmdArgs.push_back("-EL");
  6212. if ((!Args.hasArg(options::OPT_nostdlib)) &&
  6213. (!Args.hasArg(options::OPT_shared))) {
  6214. CmdArgs.push_back("-e");
  6215. CmdArgs.push_back("__start");
  6216. }
  6217. if (Args.hasArg(options::OPT_static)) {
  6218. CmdArgs.push_back("-Bstatic");
  6219. } else {
  6220. if (Args.hasArg(options::OPT_rdynamic))
  6221. CmdArgs.push_back("-export-dynamic");
  6222. CmdArgs.push_back("--eh-frame-hdr");
  6223. CmdArgs.push_back("-Bdynamic");
  6224. if (Args.hasArg(options::OPT_shared)) {
  6225. CmdArgs.push_back("-shared");
  6226. } else {
  6227. CmdArgs.push_back("-dynamic-linker");
  6228. CmdArgs.push_back("/usr/libexec/ld.so");
  6229. }
  6230. }
  6231. if (Args.hasArg(options::OPT_nopie))
  6232. CmdArgs.push_back("-nopie");
  6233. if (Output.isFilename()) {
  6234. CmdArgs.push_back("-o");
  6235. CmdArgs.push_back(Output.getFilename());
  6236. } else {
  6237. assert(Output.isNothing() && "Invalid output.");
  6238. }
  6239. if (!Args.hasArg(options::OPT_nostdlib) &&
  6240. !Args.hasArg(options::OPT_nostartfiles)) {
  6241. if (!Args.hasArg(options::OPT_shared)) {
  6242. if (Args.hasArg(options::OPT_pg))
  6243. CmdArgs.push_back(
  6244. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  6245. else
  6246. CmdArgs.push_back(
  6247. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  6248. CmdArgs.push_back(
  6249. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6250. } else {
  6251. CmdArgs.push_back(
  6252. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  6253. }
  6254. }
  6255. std::string Triple = getToolChain().getTripleString();
  6256. if (Triple.substr(0, 6) == "x86_64")
  6257. Triple.replace(0, 6, "amd64");
  6258. CmdArgs.push_back(
  6259. Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
  6260. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  6261. options::OPT_e, options::OPT_s, options::OPT_t,
  6262. options::OPT_Z_Flag, options::OPT_r});
  6263. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6264. if (!Args.hasArg(options::OPT_nostdlib) &&
  6265. !Args.hasArg(options::OPT_nodefaultlibs)) {
  6266. if (D.CCCIsCXX()) {
  6267. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6268. if (Args.hasArg(options::OPT_pg))
  6269. CmdArgs.push_back("-lm_p");
  6270. else
  6271. CmdArgs.push_back("-lm");
  6272. }
  6273. // FIXME: For some reason GCC passes -lgcc before adding
  6274. // the default system libraries. Just mimic this for now.
  6275. CmdArgs.push_back("-lgcc");
  6276. if (Args.hasArg(options::OPT_pthread)) {
  6277. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  6278. CmdArgs.push_back("-lpthread_p");
  6279. else
  6280. CmdArgs.push_back("-lpthread");
  6281. }
  6282. if (!Args.hasArg(options::OPT_shared)) {
  6283. if (Args.hasArg(options::OPT_pg))
  6284. CmdArgs.push_back("-lc_p");
  6285. else
  6286. CmdArgs.push_back("-lc");
  6287. }
  6288. CmdArgs.push_back("-lgcc");
  6289. }
  6290. if (!Args.hasArg(options::OPT_nostdlib) &&
  6291. !Args.hasArg(options::OPT_nostartfiles)) {
  6292. if (!Args.hasArg(options::OPT_shared))
  6293. CmdArgs.push_back(
  6294. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6295. else
  6296. CmdArgs.push_back(
  6297. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  6298. }
  6299. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6300. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6301. }
  6302. void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6303. const InputInfo &Output,
  6304. const InputInfoList &Inputs,
  6305. const ArgList &Args,
  6306. const char *LinkingOutput) const {
  6307. claimNoWarnArgs(Args);
  6308. ArgStringList CmdArgs;
  6309. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6310. CmdArgs.push_back("-o");
  6311. CmdArgs.push_back(Output.getFilename());
  6312. for (const auto &II : Inputs)
  6313. CmdArgs.push_back(II.getFilename());
  6314. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6315. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6316. }
  6317. void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6318. const InputInfo &Output,
  6319. const InputInfoList &Inputs,
  6320. const ArgList &Args,
  6321. const char *LinkingOutput) const {
  6322. const Driver &D = getToolChain().getDriver();
  6323. ArgStringList CmdArgs;
  6324. if ((!Args.hasArg(options::OPT_nostdlib)) &&
  6325. (!Args.hasArg(options::OPT_shared))) {
  6326. CmdArgs.push_back("-e");
  6327. CmdArgs.push_back("__start");
  6328. }
  6329. if (Args.hasArg(options::OPT_static)) {
  6330. CmdArgs.push_back("-Bstatic");
  6331. } else {
  6332. if (Args.hasArg(options::OPT_rdynamic))
  6333. CmdArgs.push_back("-export-dynamic");
  6334. CmdArgs.push_back("--eh-frame-hdr");
  6335. CmdArgs.push_back("-Bdynamic");
  6336. if (Args.hasArg(options::OPT_shared)) {
  6337. CmdArgs.push_back("-shared");
  6338. } else {
  6339. CmdArgs.push_back("-dynamic-linker");
  6340. CmdArgs.push_back("/usr/libexec/ld.so");
  6341. }
  6342. }
  6343. if (Output.isFilename()) {
  6344. CmdArgs.push_back("-o");
  6345. CmdArgs.push_back(Output.getFilename());
  6346. } else {
  6347. assert(Output.isNothing() && "Invalid output.");
  6348. }
  6349. if (!Args.hasArg(options::OPT_nostdlib) &&
  6350. !Args.hasArg(options::OPT_nostartfiles)) {
  6351. if (!Args.hasArg(options::OPT_shared)) {
  6352. if (Args.hasArg(options::OPT_pg))
  6353. CmdArgs.push_back(
  6354. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  6355. else
  6356. CmdArgs.push_back(
  6357. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  6358. CmdArgs.push_back(
  6359. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6360. } else {
  6361. CmdArgs.push_back(
  6362. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  6363. }
  6364. }
  6365. Args.AddAllArgs(CmdArgs,
  6366. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  6367. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6368. if (!Args.hasArg(options::OPT_nostdlib) &&
  6369. !Args.hasArg(options::OPT_nodefaultlibs)) {
  6370. if (D.CCCIsCXX()) {
  6371. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6372. if (Args.hasArg(options::OPT_pg))
  6373. CmdArgs.push_back("-lm_p");
  6374. else
  6375. CmdArgs.push_back("-lm");
  6376. }
  6377. if (Args.hasArg(options::OPT_pthread)) {
  6378. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  6379. CmdArgs.push_back("-lpthread_p");
  6380. else
  6381. CmdArgs.push_back("-lpthread");
  6382. }
  6383. if (!Args.hasArg(options::OPT_shared)) {
  6384. if (Args.hasArg(options::OPT_pg))
  6385. CmdArgs.push_back("-lc_p");
  6386. else
  6387. CmdArgs.push_back("-lc");
  6388. }
  6389. StringRef MyArch;
  6390. switch (getToolChain().getArch()) {
  6391. case llvm::Triple::arm:
  6392. MyArch = "arm";
  6393. break;
  6394. case llvm::Triple::x86:
  6395. MyArch = "i386";
  6396. break;
  6397. case llvm::Triple::x86_64:
  6398. MyArch = "amd64";
  6399. break;
  6400. default:
  6401. llvm_unreachable("Unsupported architecture");
  6402. }
  6403. CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
  6404. }
  6405. if (!Args.hasArg(options::OPT_nostdlib) &&
  6406. !Args.hasArg(options::OPT_nostartfiles)) {
  6407. if (!Args.hasArg(options::OPT_shared))
  6408. CmdArgs.push_back(
  6409. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6410. else
  6411. CmdArgs.push_back(
  6412. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  6413. }
  6414. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6415. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6416. }
  6417. void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6418. const InputInfo &Output,
  6419. const InputInfoList &Inputs,
  6420. const ArgList &Args,
  6421. const char *LinkingOutput) const {
  6422. claimNoWarnArgs(Args);
  6423. ArgStringList CmdArgs;
  6424. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  6425. // instruct as in the base system to assemble 32-bit code.
  6426. if (getToolChain().getArch() == llvm::Triple::x86)
  6427. CmdArgs.push_back("--32");
  6428. else if (getToolChain().getArch() == llvm::Triple::ppc)
  6429. CmdArgs.push_back("-a32");
  6430. else if (getToolChain().getArch() == llvm::Triple::mips ||
  6431. getToolChain().getArch() == llvm::Triple::mipsel ||
  6432. getToolChain().getArch() == llvm::Triple::mips64 ||
  6433. getToolChain().getArch() == llvm::Triple::mips64el) {
  6434. StringRef CPUName;
  6435. StringRef ABIName;
  6436. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6437. CmdArgs.push_back("-march");
  6438. CmdArgs.push_back(CPUName.data());
  6439. CmdArgs.push_back("-mabi");
  6440. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6441. if (getToolChain().getArch() == llvm::Triple::mips ||
  6442. getToolChain().getArch() == llvm::Triple::mips64)
  6443. CmdArgs.push_back("-EB");
  6444. else
  6445. CmdArgs.push_back("-EL");
  6446. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6447. } else if (getToolChain().getArch() == llvm::Triple::arm ||
  6448. getToolChain().getArch() == llvm::Triple::armeb ||
  6449. getToolChain().getArch() == llvm::Triple::thumb ||
  6450. getToolChain().getArch() == llvm::Triple::thumbeb) {
  6451. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  6452. if (ABI == arm::FloatABI::Hard)
  6453. CmdArgs.push_back("-mfpu=vfp");
  6454. else
  6455. CmdArgs.push_back("-mfpu=softvfp");
  6456. switch (getToolChain().getTriple().getEnvironment()) {
  6457. case llvm::Triple::GNUEABIHF:
  6458. case llvm::Triple::GNUEABI:
  6459. case llvm::Triple::EABI:
  6460. CmdArgs.push_back("-meabi=5");
  6461. break;
  6462. default:
  6463. CmdArgs.push_back("-matpcs");
  6464. }
  6465. } else if (getToolChain().getArch() == llvm::Triple::sparc ||
  6466. getToolChain().getArch() == llvm::Triple::sparcel ||
  6467. getToolChain().getArch() == llvm::Triple::sparcv9) {
  6468. if (getToolChain().getArch() == llvm::Triple::sparc)
  6469. CmdArgs.push_back("-Av8plusa");
  6470. else
  6471. CmdArgs.push_back("-Av9a");
  6472. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6473. }
  6474. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6475. CmdArgs.push_back("-o");
  6476. CmdArgs.push_back(Output.getFilename());
  6477. for (const auto &II : Inputs)
  6478. CmdArgs.push_back(II.getFilename());
  6479. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6480. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6481. }
  6482. void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6483. const InputInfo &Output,
  6484. const InputInfoList &Inputs,
  6485. const ArgList &Args,
  6486. const char *LinkingOutput) const {
  6487. const toolchains::FreeBSD &ToolChain =
  6488. static_cast<const toolchains::FreeBSD &>(getToolChain());
  6489. const Driver &D = ToolChain.getDriver();
  6490. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  6491. const bool IsPIE =
  6492. !Args.hasArg(options::OPT_shared) &&
  6493. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  6494. ArgStringList CmdArgs;
  6495. // Silence warning for "clang -g foo.o -o foo"
  6496. Args.ClaimAllArgs(options::OPT_g_Group);
  6497. // and "clang -emit-llvm foo.o -o foo"
  6498. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6499. // and for "clang -w foo.o -o foo". Other warning options are already
  6500. // handled somewhere else.
  6501. Args.ClaimAllArgs(options::OPT_w);
  6502. if (!D.SysRoot.empty())
  6503. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  6504. if (IsPIE)
  6505. CmdArgs.push_back("-pie");
  6506. if (Args.hasArg(options::OPT_static)) {
  6507. CmdArgs.push_back("-Bstatic");
  6508. } else {
  6509. if (Args.hasArg(options::OPT_rdynamic))
  6510. CmdArgs.push_back("-export-dynamic");
  6511. CmdArgs.push_back("--eh-frame-hdr");
  6512. if (Args.hasArg(options::OPT_shared)) {
  6513. CmdArgs.push_back("-Bshareable");
  6514. } else {
  6515. CmdArgs.push_back("-dynamic-linker");
  6516. CmdArgs.push_back("/libexec/ld-elf.so.1");
  6517. }
  6518. if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
  6519. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
  6520. Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
  6521. CmdArgs.push_back("--hash-style=both");
  6522. }
  6523. }
  6524. CmdArgs.push_back("--enable-new-dtags");
  6525. }
  6526. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  6527. // instruct ld in the base system to link 32-bit code.
  6528. if (Arch == llvm::Triple::x86) {
  6529. CmdArgs.push_back("-m");
  6530. CmdArgs.push_back("elf_i386_fbsd");
  6531. }
  6532. if (Arch == llvm::Triple::ppc) {
  6533. CmdArgs.push_back("-m");
  6534. CmdArgs.push_back("elf32ppc_fbsd");
  6535. }
  6536. if (Output.isFilename()) {
  6537. CmdArgs.push_back("-o");
  6538. CmdArgs.push_back(Output.getFilename());
  6539. } else {
  6540. assert(Output.isNothing() && "Invalid output.");
  6541. }
  6542. if (!Args.hasArg(options::OPT_nostdlib) &&
  6543. !Args.hasArg(options::OPT_nostartfiles)) {
  6544. const char *crt1 = nullptr;
  6545. if (!Args.hasArg(options::OPT_shared)) {
  6546. if (Args.hasArg(options::OPT_pg))
  6547. crt1 = "gcrt1.o";
  6548. else if (IsPIE)
  6549. crt1 = "Scrt1.o";
  6550. else
  6551. crt1 = "crt1.o";
  6552. }
  6553. if (crt1)
  6554. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  6555. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  6556. const char *crtbegin = nullptr;
  6557. if (Args.hasArg(options::OPT_static))
  6558. crtbegin = "crtbeginT.o";
  6559. else if (Args.hasArg(options::OPT_shared) || IsPIE)
  6560. crtbegin = "crtbeginS.o";
  6561. else
  6562. crtbegin = "crtbegin.o";
  6563. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  6564. }
  6565. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6566. const ToolChain::path_list &Paths = ToolChain.getFilePaths();
  6567. for (const auto &Path : Paths)
  6568. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
  6569. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  6570. Args.AddAllArgs(CmdArgs, options::OPT_e);
  6571. Args.AddAllArgs(CmdArgs, options::OPT_s);
  6572. Args.AddAllArgs(CmdArgs, options::OPT_t);
  6573. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  6574. Args.AddAllArgs(CmdArgs, options::OPT_r);
  6575. if (D.IsUsingLTO(Args))
  6576. AddGoldPlugin(ToolChain, Args, CmdArgs);
  6577. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  6578. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  6579. if (!Args.hasArg(options::OPT_nostdlib) &&
  6580. !Args.hasArg(options::OPT_nodefaultlibs)) {
  6581. if (D.CCCIsCXX()) {
  6582. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  6583. if (Args.hasArg(options::OPT_pg))
  6584. CmdArgs.push_back("-lm_p");
  6585. else
  6586. CmdArgs.push_back("-lm");
  6587. }
  6588. if (NeedsSanitizerDeps)
  6589. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  6590. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  6591. // the default system libraries. Just mimic this for now.
  6592. if (Args.hasArg(options::OPT_pg))
  6593. CmdArgs.push_back("-lgcc_p");
  6594. else
  6595. CmdArgs.push_back("-lgcc");
  6596. if (Args.hasArg(options::OPT_static)) {
  6597. CmdArgs.push_back("-lgcc_eh");
  6598. } else if (Args.hasArg(options::OPT_pg)) {
  6599. CmdArgs.push_back("-lgcc_eh_p");
  6600. } else {
  6601. CmdArgs.push_back("--as-needed");
  6602. CmdArgs.push_back("-lgcc_s");
  6603. CmdArgs.push_back("--no-as-needed");
  6604. }
  6605. if (Args.hasArg(options::OPT_pthread)) {
  6606. if (Args.hasArg(options::OPT_pg))
  6607. CmdArgs.push_back("-lpthread_p");
  6608. else
  6609. CmdArgs.push_back("-lpthread");
  6610. }
  6611. if (Args.hasArg(options::OPT_pg)) {
  6612. if (Args.hasArg(options::OPT_shared))
  6613. CmdArgs.push_back("-lc");
  6614. else
  6615. CmdArgs.push_back("-lc_p");
  6616. CmdArgs.push_back("-lgcc_p");
  6617. } else {
  6618. CmdArgs.push_back("-lc");
  6619. CmdArgs.push_back("-lgcc");
  6620. }
  6621. if (Args.hasArg(options::OPT_static)) {
  6622. CmdArgs.push_back("-lgcc_eh");
  6623. } else if (Args.hasArg(options::OPT_pg)) {
  6624. CmdArgs.push_back("-lgcc_eh_p");
  6625. } else {
  6626. CmdArgs.push_back("--as-needed");
  6627. CmdArgs.push_back("-lgcc_s");
  6628. CmdArgs.push_back("--no-as-needed");
  6629. }
  6630. }
  6631. if (!Args.hasArg(options::OPT_nostdlib) &&
  6632. !Args.hasArg(options::OPT_nostartfiles)) {
  6633. if (Args.hasArg(options::OPT_shared) || IsPIE)
  6634. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  6635. else
  6636. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  6637. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  6638. }
  6639. addProfileRT(ToolChain, Args, CmdArgs);
  6640. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6641. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6642. }
  6643. void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6644. const InputInfo &Output,
  6645. const InputInfoList &Inputs,
  6646. const ArgList &Args,
  6647. const char *LinkingOutput) const {
  6648. claimNoWarnArgs(Args);
  6649. ArgStringList CmdArgs;
  6650. // GNU as needs different flags for creating the correct output format
  6651. // on architectures with different ABIs or optional feature sets.
  6652. switch (getToolChain().getArch()) {
  6653. case llvm::Triple::x86:
  6654. CmdArgs.push_back("--32");
  6655. break;
  6656. case llvm::Triple::arm:
  6657. case llvm::Triple::armeb:
  6658. case llvm::Triple::thumb:
  6659. case llvm::Triple::thumbeb: {
  6660. StringRef MArch, MCPU;
  6661. getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
  6662. std::string Arch =
  6663. arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
  6664. CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
  6665. break;
  6666. }
  6667. case llvm::Triple::mips:
  6668. case llvm::Triple::mipsel:
  6669. case llvm::Triple::mips64:
  6670. case llvm::Triple::mips64el: {
  6671. StringRef CPUName;
  6672. StringRef ABIName;
  6673. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6674. CmdArgs.push_back("-march");
  6675. CmdArgs.push_back(CPUName.data());
  6676. CmdArgs.push_back("-mabi");
  6677. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6678. if (getToolChain().getArch() == llvm::Triple::mips ||
  6679. getToolChain().getArch() == llvm::Triple::mips64)
  6680. CmdArgs.push_back("-EB");
  6681. else
  6682. CmdArgs.push_back("-EL");
  6683. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6684. break;
  6685. }
  6686. case llvm::Triple::sparc:
  6687. case llvm::Triple::sparcel:
  6688. CmdArgs.push_back("-32");
  6689. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6690. break;
  6691. case llvm::Triple::sparcv9:
  6692. CmdArgs.push_back("-64");
  6693. CmdArgs.push_back("-Av9");
  6694. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6695. break;
  6696. default:
  6697. break;
  6698. }
  6699. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6700. CmdArgs.push_back("-o");
  6701. CmdArgs.push_back(Output.getFilename());
  6702. for (const auto &II : Inputs)
  6703. CmdArgs.push_back(II.getFilename());
  6704. const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
  6705. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6706. }
  6707. void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6708. const InputInfo &Output,
  6709. const InputInfoList &Inputs,
  6710. const ArgList &Args,
  6711. const char *LinkingOutput) const {
  6712. const Driver &D = getToolChain().getDriver();
  6713. ArgStringList CmdArgs;
  6714. if (!D.SysRoot.empty())
  6715. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  6716. CmdArgs.push_back("--eh-frame-hdr");
  6717. if (Args.hasArg(options::OPT_static)) {
  6718. CmdArgs.push_back("-Bstatic");
  6719. } else {
  6720. if (Args.hasArg(options::OPT_rdynamic))
  6721. CmdArgs.push_back("-export-dynamic");
  6722. if (Args.hasArg(options::OPT_shared)) {
  6723. CmdArgs.push_back("-Bshareable");
  6724. } else {
  6725. CmdArgs.push_back("-dynamic-linker");
  6726. CmdArgs.push_back("/libexec/ld.elf_so");
  6727. }
  6728. }
  6729. // Many NetBSD architectures support more than one ABI.
  6730. // Determine the correct emulation for ld.
  6731. switch (getToolChain().getArch()) {
  6732. case llvm::Triple::x86:
  6733. CmdArgs.push_back("-m");
  6734. CmdArgs.push_back("elf_i386");
  6735. break;
  6736. case llvm::Triple::arm:
  6737. case llvm::Triple::thumb:
  6738. CmdArgs.push_back("-m");
  6739. switch (getToolChain().getTriple().getEnvironment()) {
  6740. case llvm::Triple::EABI:
  6741. case llvm::Triple::GNUEABI:
  6742. CmdArgs.push_back("armelf_nbsd_eabi");
  6743. break;
  6744. case llvm::Triple::EABIHF:
  6745. case llvm::Triple::GNUEABIHF:
  6746. CmdArgs.push_back("armelf_nbsd_eabihf");
  6747. break;
  6748. default:
  6749. CmdArgs.push_back("armelf_nbsd");
  6750. break;
  6751. }
  6752. break;
  6753. case llvm::Triple::armeb:
  6754. case llvm::Triple::thumbeb:
  6755. arm::appendEBLinkFlags(
  6756. Args, CmdArgs,
  6757. llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
  6758. CmdArgs.push_back("-m");
  6759. switch (getToolChain().getTriple().getEnvironment()) {
  6760. case llvm::Triple::EABI:
  6761. case llvm::Triple::GNUEABI:
  6762. CmdArgs.push_back("armelfb_nbsd_eabi");
  6763. break;
  6764. case llvm::Triple::EABIHF:
  6765. case llvm::Triple::GNUEABIHF:
  6766. CmdArgs.push_back("armelfb_nbsd_eabihf");
  6767. break;
  6768. default:
  6769. CmdArgs.push_back("armelfb_nbsd");
  6770. break;
  6771. }
  6772. break;
  6773. case llvm::Triple::mips64:
  6774. case llvm::Triple::mips64el:
  6775. if (mips::hasMipsAbiArg(Args, "32")) {
  6776. CmdArgs.push_back("-m");
  6777. if (getToolChain().getArch() == llvm::Triple::mips64)
  6778. CmdArgs.push_back("elf32btsmip");
  6779. else
  6780. CmdArgs.push_back("elf32ltsmip");
  6781. } else if (mips::hasMipsAbiArg(Args, "64")) {
  6782. CmdArgs.push_back("-m");
  6783. if (getToolChain().getArch() == llvm::Triple::mips64)
  6784. CmdArgs.push_back("elf64btsmip");
  6785. else
  6786. CmdArgs.push_back("elf64ltsmip");
  6787. }
  6788. break;
  6789. case llvm::Triple::ppc:
  6790. CmdArgs.push_back("-m");
  6791. CmdArgs.push_back("elf32ppc_nbsd");
  6792. break;
  6793. case llvm::Triple::ppc64:
  6794. case llvm::Triple::ppc64le:
  6795. CmdArgs.push_back("-m");
  6796. CmdArgs.push_back("elf64ppc");
  6797. break;
  6798. case llvm::Triple::sparc:
  6799. CmdArgs.push_back("-m");
  6800. CmdArgs.push_back("elf32_sparc");
  6801. break;
  6802. case llvm::Triple::sparcv9:
  6803. CmdArgs.push_back("-m");
  6804. CmdArgs.push_back("elf64_sparc");
  6805. break;
  6806. default:
  6807. break;
  6808. }
  6809. if (Output.isFilename()) {
  6810. CmdArgs.push_back("-o");
  6811. CmdArgs.push_back(Output.getFilename());
  6812. } else {
  6813. assert(Output.isNothing() && "Invalid output.");
  6814. }
  6815. if (!Args.hasArg(options::OPT_nostdlib) &&
  6816. !Args.hasArg(options::OPT_nostartfiles)) {
  6817. if (!Args.hasArg(options::OPT_shared)) {
  6818. CmdArgs.push_back(
  6819. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  6820. CmdArgs.push_back(
  6821. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  6822. CmdArgs.push_back(
  6823. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6824. } else {
  6825. CmdArgs.push_back(
  6826. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  6827. CmdArgs.push_back(
  6828. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  6829. }
  6830. }
  6831. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6832. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  6833. Args.AddAllArgs(CmdArgs, options::OPT_e);
  6834. Args.AddAllArgs(CmdArgs, options::OPT_s);
  6835. Args.AddAllArgs(CmdArgs, options::OPT_t);
  6836. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  6837. Args.AddAllArgs(CmdArgs, options::OPT_r);
  6838. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6839. unsigned Major, Minor, Micro;
  6840. getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
  6841. bool useLibgcc = true;
  6842. if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
  6843. switch (getToolChain().getArch()) {
  6844. case llvm::Triple::aarch64:
  6845. case llvm::Triple::arm:
  6846. case llvm::Triple::armeb:
  6847. case llvm::Triple::thumb:
  6848. case llvm::Triple::thumbeb:
  6849. case llvm::Triple::ppc:
  6850. case llvm::Triple::ppc64:
  6851. case llvm::Triple::ppc64le:
  6852. case llvm::Triple::x86:
  6853. case llvm::Triple::x86_64:
  6854. useLibgcc = false;
  6855. break;
  6856. default:
  6857. break;
  6858. }
  6859. }
  6860. if (!Args.hasArg(options::OPT_nostdlib) &&
  6861. !Args.hasArg(options::OPT_nodefaultlibs)) {
  6862. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  6863. if (D.CCCIsCXX()) {
  6864. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6865. CmdArgs.push_back("-lm");
  6866. }
  6867. if (Args.hasArg(options::OPT_pthread))
  6868. CmdArgs.push_back("-lpthread");
  6869. CmdArgs.push_back("-lc");
  6870. if (useLibgcc) {
  6871. if (Args.hasArg(options::OPT_static)) {
  6872. // libgcc_eh depends on libc, so resolve as much as possible,
  6873. // pull in any new requirements from libc and then get the rest
  6874. // of libgcc.
  6875. CmdArgs.push_back("-lgcc_eh");
  6876. CmdArgs.push_back("-lc");
  6877. CmdArgs.push_back("-lgcc");
  6878. } else {
  6879. CmdArgs.push_back("-lgcc");
  6880. CmdArgs.push_back("--as-needed");
  6881. CmdArgs.push_back("-lgcc_s");
  6882. CmdArgs.push_back("--no-as-needed");
  6883. }
  6884. }
  6885. }
  6886. if (!Args.hasArg(options::OPT_nostdlib) &&
  6887. !Args.hasArg(options::OPT_nostartfiles)) {
  6888. if (!Args.hasArg(options::OPT_shared))
  6889. CmdArgs.push_back(
  6890. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6891. else
  6892. CmdArgs.push_back(
  6893. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  6894. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  6895. }
  6896. addProfileRT(getToolChain(), Args, CmdArgs);
  6897. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6898. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6899. }
  6900. void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6901. const InputInfo &Output,
  6902. const InputInfoList &Inputs,
  6903. const ArgList &Args,
  6904. const char *LinkingOutput) const {
  6905. claimNoWarnArgs(Args);
  6906. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  6907. llvm::Triple Triple = llvm::Triple(TripleStr);
  6908. ArgStringList CmdArgs;
  6909. bool NeedsKPIC = false;
  6910. llvm::Reloc::Model RelocationModel;
  6911. unsigned PICLevel;
  6912. bool IsPIE;
  6913. std::tie(RelocationModel, PICLevel, IsPIE) =
  6914. ParsePICArgs(getToolChain(), Triple, Args);
  6915. switch (getToolChain().getArch()) {
  6916. default:
  6917. break;
  6918. // Add --32/--64 to make sure we get the format we want.
  6919. // This is incomplete
  6920. case llvm::Triple::x86:
  6921. CmdArgs.push_back("--32");
  6922. break;
  6923. case llvm::Triple::x86_64:
  6924. if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
  6925. CmdArgs.push_back("--x32");
  6926. else
  6927. CmdArgs.push_back("--64");
  6928. break;
  6929. case llvm::Triple::ppc:
  6930. CmdArgs.push_back("-a32");
  6931. CmdArgs.push_back("-mppc");
  6932. CmdArgs.push_back("-many");
  6933. break;
  6934. case llvm::Triple::ppc64:
  6935. CmdArgs.push_back("-a64");
  6936. CmdArgs.push_back("-mppc64");
  6937. CmdArgs.push_back("-many");
  6938. break;
  6939. case llvm::Triple::ppc64le:
  6940. CmdArgs.push_back("-a64");
  6941. CmdArgs.push_back("-mppc64");
  6942. CmdArgs.push_back("-many");
  6943. CmdArgs.push_back("-mlittle-endian");
  6944. break;
  6945. case llvm::Triple::sparc:
  6946. case llvm::Triple::sparcel:
  6947. CmdArgs.push_back("-32");
  6948. CmdArgs.push_back("-Av8plusa");
  6949. NeedsKPIC = true;
  6950. break;
  6951. case llvm::Triple::sparcv9:
  6952. CmdArgs.push_back("-64");
  6953. CmdArgs.push_back("-Av9a");
  6954. NeedsKPIC = true;
  6955. break;
  6956. case llvm::Triple::arm:
  6957. case llvm::Triple::armeb:
  6958. case llvm::Triple::thumb:
  6959. case llvm::Triple::thumbeb: {
  6960. const llvm::Triple &Triple2 = getToolChain().getTriple();
  6961. switch (Triple2.getSubArch()) {
  6962. case llvm::Triple::ARMSubArch_v7:
  6963. CmdArgs.push_back("-mfpu=neon");
  6964. break;
  6965. case llvm::Triple::ARMSubArch_v8:
  6966. CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
  6967. break;
  6968. default:
  6969. break;
  6970. }
  6971. switch (arm::getARMFloatABI(getToolChain(), Args)) {
  6972. case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
  6973. case arm::FloatABI::Soft:
  6974. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
  6975. break;
  6976. case arm::FloatABI::SoftFP:
  6977. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
  6978. break;
  6979. case arm::FloatABI::Hard:
  6980. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
  6981. break;
  6982. }
  6983. Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
  6984. // FIXME: remove krait check when GNU tools support krait cpu
  6985. // for now replace it with -march=armv7-a to avoid a lower
  6986. // march from being picked in the absence of a cpu flag.
  6987. Arg *A;
  6988. if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
  6989. StringRef(A->getValue()).lower() == "krait")
  6990. CmdArgs.push_back("-march=armv7-a");
  6991. else
  6992. Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
  6993. Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
  6994. break;
  6995. }
  6996. case llvm::Triple::mips:
  6997. case llvm::Triple::mipsel:
  6998. case llvm::Triple::mips64:
  6999. case llvm::Triple::mips64el: {
  7000. StringRef CPUName;
  7001. StringRef ABIName;
  7002. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7003. ABIName = getGnuCompatibleMipsABIName(ABIName);
  7004. CmdArgs.push_back("-march");
  7005. CmdArgs.push_back(CPUName.data());
  7006. CmdArgs.push_back("-mabi");
  7007. CmdArgs.push_back(ABIName.data());
  7008. // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
  7009. // or -mshared (not implemented) is in effect.
  7010. if (RelocationModel == llvm::Reloc::Static)
  7011. CmdArgs.push_back("-mno-shared");
  7012. // LLVM doesn't support -mplt yet and acts as if it is always given.
  7013. // However, -mplt has no effect with the N64 ABI.
  7014. CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
  7015. if (getToolChain().getArch() == llvm::Triple::mips ||
  7016. getToolChain().getArch() == llvm::Triple::mips64)
  7017. CmdArgs.push_back("-EB");
  7018. else
  7019. CmdArgs.push_back("-EL");
  7020. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  7021. if (StringRef(A->getValue()) == "2008")
  7022. CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
  7023. }
  7024. // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
  7025. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  7026. options::OPT_mfp64)) {
  7027. A->claim();
  7028. A->render(Args, CmdArgs);
  7029. } else if (mips::shouldUseFPXX(
  7030. Args, getToolChain().getTriple(), CPUName, ABIName,
  7031. getMipsFloatABI(getToolChain().getDriver(), Args)))
  7032. CmdArgs.push_back("-mfpxx");
  7033. // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
  7034. // -mno-mips16 is actually -no-mips16.
  7035. if (Arg *A =
  7036. Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
  7037. if (A->getOption().matches(options::OPT_mips16)) {
  7038. A->claim();
  7039. A->render(Args, CmdArgs);
  7040. } else {
  7041. A->claim();
  7042. CmdArgs.push_back("-no-mips16");
  7043. }
  7044. }
  7045. Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
  7046. options::OPT_mno_micromips);
  7047. Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
  7048. Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
  7049. if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
  7050. // Do not use AddLastArg because not all versions of MIPS assembler
  7051. // support -mmsa / -mno-msa options.
  7052. if (A->getOption().matches(options::OPT_mmsa))
  7053. CmdArgs.push_back(Args.MakeArgString("-mmsa"));
  7054. }
  7055. Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
  7056. options::OPT_msoft_float);
  7057. Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
  7058. options::OPT_msingle_float);
  7059. Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
  7060. options::OPT_mno_odd_spreg);
  7061. NeedsKPIC = true;
  7062. break;
  7063. }
  7064. case llvm::Triple::systemz: {
  7065. // Always pass an -march option, since our default of z10 is later
  7066. // than the GNU assembler's default.
  7067. StringRef CPUName = getSystemZTargetCPU(Args);
  7068. CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
  7069. break;
  7070. }
  7071. }
  7072. if (NeedsKPIC) {
  7073. if (RelocationModel != llvm::Reloc::Static)
  7074. CmdArgs.push_back("-KPIC");
  7075. }
  7076. Args.AddAllArgs(CmdArgs, options::OPT_I);
  7077. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7078. CmdArgs.push_back("-o");
  7079. CmdArgs.push_back(Output.getFilename());
  7080. for (const auto &II : Inputs)
  7081. CmdArgs.push_back(II.getFilename());
  7082. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7083. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7084. // Handle the debug info splitting at object creation time if we're
  7085. // creating an object.
  7086. // TODO: Currently only works on linux with newer objcopy.
  7087. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  7088. getToolChain().getTriple().isOSLinux())
  7089. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  7090. SplitDebugName(Args, Inputs[0]));
  7091. }
  7092. static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
  7093. ArgStringList &CmdArgs, const ArgList &Args) {
  7094. bool isAndroid = Triple.isAndroid();
  7095. bool isCygMing = Triple.isOSCygMing();
  7096. bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
  7097. Args.hasArg(options::OPT_static);
  7098. if (!D.CCCIsCXX())
  7099. CmdArgs.push_back("-lgcc");
  7100. if (StaticLibgcc || isAndroid) {
  7101. if (D.CCCIsCXX())
  7102. CmdArgs.push_back("-lgcc");
  7103. } else {
  7104. if (!D.CCCIsCXX() && !isCygMing)
  7105. CmdArgs.push_back("--as-needed");
  7106. CmdArgs.push_back("-lgcc_s");
  7107. if (!D.CCCIsCXX() && !isCygMing)
  7108. CmdArgs.push_back("--no-as-needed");
  7109. }
  7110. if (StaticLibgcc && !isAndroid)
  7111. CmdArgs.push_back("-lgcc_eh");
  7112. else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
  7113. CmdArgs.push_back("-lgcc");
  7114. // According to Android ABI, we have to link with libdl if we are
  7115. // linking with non-static libgcc.
  7116. //
  7117. // NOTE: This fixes a link error on Android MIPS as well. The non-static
  7118. // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
  7119. if (isAndroid && !StaticLibgcc)
  7120. CmdArgs.push_back("-ldl");
  7121. }
  7122. static std::string getLinuxDynamicLinker(const ArgList &Args,
  7123. const toolchains::Linux &ToolChain) {
  7124. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7125. if (ToolChain.getTriple().isAndroid()) {
  7126. if (ToolChain.getTriple().isArch64Bit())
  7127. return "/system/bin/linker64";
  7128. else
  7129. return "/system/bin/linker";
  7130. } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
  7131. Arch == llvm::Triple::sparcel)
  7132. return "/lib/ld-linux.so.2";
  7133. else if (Arch == llvm::Triple::aarch64)
  7134. return "/lib/ld-linux-aarch64.so.1";
  7135. else if (Arch == llvm::Triple::aarch64_be)
  7136. return "/lib/ld-linux-aarch64_be.so.1";
  7137. else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
  7138. if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
  7139. arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
  7140. return "/lib/ld-linux-armhf.so.3";
  7141. else
  7142. return "/lib/ld-linux.so.3";
  7143. } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
  7144. // TODO: check which dynamic linker name.
  7145. if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
  7146. arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
  7147. return "/lib/ld-linux-armhf.so.3";
  7148. else
  7149. return "/lib/ld-linux.so.3";
  7150. } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
  7151. Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
  7152. StringRef CPUName;
  7153. StringRef ABIName;
  7154. mips::getMipsCPUAndABI(Args, ToolChain.getTriple(), CPUName, ABIName);
  7155. bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
  7156. StringRef LibDir = llvm::StringSwitch<llvm::StringRef>(ABIName)
  7157. .Case("o32", "/lib")
  7158. .Case("n32", "/lib32")
  7159. .Case("n64", "/lib64")
  7160. .Default("/lib");
  7161. StringRef LibName;
  7162. if (mips::isUCLibc(Args))
  7163. LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
  7164. else
  7165. LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
  7166. return (LibDir + "/" + LibName).str();
  7167. } else if (Arch == llvm::Triple::ppc)
  7168. return "/lib/ld.so.1";
  7169. else if (Arch == llvm::Triple::ppc64) {
  7170. if (ppc::hasPPCAbiArg(Args, "elfv2"))
  7171. return "/lib64/ld64.so.2";
  7172. return "/lib64/ld64.so.1";
  7173. } else if (Arch == llvm::Triple::ppc64le) {
  7174. if (ppc::hasPPCAbiArg(Args, "elfv1"))
  7175. return "/lib64/ld64.so.1";
  7176. return "/lib64/ld64.so.2";
  7177. } else if (Arch == llvm::Triple::systemz)
  7178. return "/lib/ld64.so.1";
  7179. else if (Arch == llvm::Triple::sparcv9)
  7180. return "/lib64/ld-linux.so.2";
  7181. else if (Arch == llvm::Triple::x86_64 &&
  7182. ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
  7183. return "/libx32/ld-linux-x32.so.2";
  7184. else
  7185. return "/lib64/ld-linux-x86-64.so.2";
  7186. }
  7187. static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
  7188. ArgStringList &CmdArgs, const ArgList &Args) {
  7189. // Make use of compiler-rt if --rtlib option is used
  7190. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
  7191. switch (RLT) {
  7192. case ToolChain::RLT_CompilerRT:
  7193. switch (TC.getTriple().getOS()) {
  7194. default:
  7195. llvm_unreachable("unsupported OS");
  7196. case llvm::Triple::Win32:
  7197. case llvm::Triple::Linux:
  7198. addClangRT(TC, Args, CmdArgs);
  7199. break;
  7200. }
  7201. break;
  7202. case ToolChain::RLT_Libgcc:
  7203. AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
  7204. break;
  7205. }
  7206. }
  7207. static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
  7208. switch (T.getArch()) {
  7209. case llvm::Triple::x86:
  7210. return "elf_i386";
  7211. case llvm::Triple::aarch64:
  7212. return "aarch64linux";
  7213. case llvm::Triple::aarch64_be:
  7214. return "aarch64_be_linux";
  7215. case llvm::Triple::arm:
  7216. case llvm::Triple::thumb:
  7217. return "armelf_linux_eabi";
  7218. case llvm::Triple::armeb:
  7219. case llvm::Triple::thumbeb:
  7220. return "armebelf_linux_eabi"; /* TODO: check which NAME. */
  7221. case llvm::Triple::ppc:
  7222. return "elf32ppclinux";
  7223. case llvm::Triple::ppc64:
  7224. return "elf64ppc";
  7225. case llvm::Triple::ppc64le:
  7226. return "elf64lppc";
  7227. case llvm::Triple::sparc:
  7228. case llvm::Triple::sparcel:
  7229. return "elf32_sparc";
  7230. case llvm::Triple::sparcv9:
  7231. return "elf64_sparc";
  7232. case llvm::Triple::mips:
  7233. return "elf32btsmip";
  7234. case llvm::Triple::mipsel:
  7235. return "elf32ltsmip";
  7236. case llvm::Triple::mips64:
  7237. if (mips::hasMipsAbiArg(Args, "n32"))
  7238. return "elf32btsmipn32";
  7239. return "elf64btsmip";
  7240. case llvm::Triple::mips64el:
  7241. if (mips::hasMipsAbiArg(Args, "n32"))
  7242. return "elf32ltsmipn32";
  7243. return "elf64ltsmip";
  7244. case llvm::Triple::systemz:
  7245. return "elf64_s390";
  7246. case llvm::Triple::x86_64:
  7247. if (T.getEnvironment() == llvm::Triple::GNUX32)
  7248. return "elf32_x86_64";
  7249. return "elf_x86_64";
  7250. default:
  7251. llvm_unreachable("Unexpected arch");
  7252. }
  7253. }
  7254. void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7255. const InputInfo &Output,
  7256. const InputInfoList &Inputs,
  7257. const ArgList &Args,
  7258. const char *LinkingOutput) const {
  7259. const toolchains::Linux &ToolChain =
  7260. static_cast<const toolchains::Linux &>(getToolChain());
  7261. const Driver &D = ToolChain.getDriver();
  7262. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  7263. llvm::Triple Triple = llvm::Triple(TripleStr);
  7264. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7265. const bool isAndroid = ToolChain.getTriple().isAndroid();
  7266. const bool IsPIE =
  7267. !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
  7268. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  7269. ArgStringList CmdArgs;
  7270. // Silence warning for "clang -g foo.o -o foo"
  7271. Args.ClaimAllArgs(options::OPT_g_Group);
  7272. // and "clang -emit-llvm foo.o -o foo"
  7273. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7274. // and for "clang -w foo.o -o foo". Other warning options are already
  7275. // handled somewhere else.
  7276. Args.ClaimAllArgs(options::OPT_w);
  7277. if (!D.SysRoot.empty())
  7278. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7279. if (IsPIE)
  7280. CmdArgs.push_back("-pie");
  7281. if (Args.hasArg(options::OPT_rdynamic))
  7282. CmdArgs.push_back("-export-dynamic");
  7283. if (Args.hasArg(options::OPT_s))
  7284. CmdArgs.push_back("-s");
  7285. if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
  7286. arm::appendEBLinkFlags(Args, CmdArgs, Triple);
  7287. for (const auto &Opt : ToolChain.ExtraOpts)
  7288. CmdArgs.push_back(Opt.c_str());
  7289. if (!Args.hasArg(options::OPT_static)) {
  7290. CmdArgs.push_back("--eh-frame-hdr");
  7291. }
  7292. CmdArgs.push_back("-m");
  7293. CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
  7294. if (Args.hasArg(options::OPT_static)) {
  7295. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  7296. Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
  7297. CmdArgs.push_back("-Bstatic");
  7298. else
  7299. CmdArgs.push_back("-static");
  7300. } else if (Args.hasArg(options::OPT_shared)) {
  7301. CmdArgs.push_back("-shared");
  7302. }
  7303. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  7304. Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
  7305. (!Args.hasArg(options::OPT_static) &&
  7306. !Args.hasArg(options::OPT_shared))) {
  7307. CmdArgs.push_back("-dynamic-linker");
  7308. CmdArgs.push_back(Args.MakeArgString(
  7309. D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
  7310. }
  7311. CmdArgs.push_back("-o");
  7312. CmdArgs.push_back(Output.getFilename());
  7313. if (!Args.hasArg(options::OPT_nostdlib) &&
  7314. !Args.hasArg(options::OPT_nostartfiles)) {
  7315. if (!isAndroid) {
  7316. const char *crt1 = nullptr;
  7317. if (!Args.hasArg(options::OPT_shared)) {
  7318. if (Args.hasArg(options::OPT_pg))
  7319. crt1 = "gcrt1.o";
  7320. else if (IsPIE)
  7321. crt1 = "Scrt1.o";
  7322. else
  7323. crt1 = "crt1.o";
  7324. }
  7325. if (crt1)
  7326. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  7327. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  7328. }
  7329. const char *crtbegin;
  7330. if (Args.hasArg(options::OPT_static))
  7331. crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
  7332. else if (Args.hasArg(options::OPT_shared))
  7333. crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
  7334. else if (IsPIE)
  7335. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
  7336. else
  7337. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
  7338. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  7339. // Add crtfastmath.o if available and fast math is enabled.
  7340. ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  7341. }
  7342. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7343. Args.AddAllArgs(CmdArgs, options::OPT_u);
  7344. const ToolChain::path_list &Paths = ToolChain.getFilePaths();
  7345. for (const auto &Path : Paths)
  7346. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
  7347. if (D.IsUsingLTO(Args))
  7348. AddGoldPlugin(ToolChain, Args, CmdArgs);
  7349. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  7350. CmdArgs.push_back("--no-demangle");
  7351. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  7352. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  7353. // The profile runtime also needs access to system libraries.
  7354. addProfileRT(getToolChain(), Args, CmdArgs);
  7355. if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
  7356. !Args.hasArg(options::OPT_nodefaultlibs)) {
  7357. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  7358. !Args.hasArg(options::OPT_static);
  7359. if (OnlyLibstdcxxStatic)
  7360. CmdArgs.push_back("-Bstatic");
  7361. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7362. if (OnlyLibstdcxxStatic)
  7363. CmdArgs.push_back("-Bdynamic");
  7364. CmdArgs.push_back("-lm");
  7365. }
  7366. // Silence warnings when linking C code with a C++ '-stdlib' argument.
  7367. Args.ClaimAllArgs(options::OPT_stdlib_EQ);
  7368. if (!Args.hasArg(options::OPT_nostdlib)) {
  7369. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  7370. if (Args.hasArg(options::OPT_static))
  7371. CmdArgs.push_back("--start-group");
  7372. if (NeedsSanitizerDeps)
  7373. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  7374. bool WantPthread = Args.hasArg(options::OPT_pthread) ||
  7375. Args.hasArg(options::OPT_pthreads);
  7376. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  7377. options::OPT_fno_openmp, false)) {
  7378. // OpenMP runtimes implies pthreads when using the GNU toolchain.
  7379. // FIXME: Does this really make sense for all GNU toolchains?
  7380. WantPthread = true;
  7381. // Also link the particular OpenMP runtimes.
  7382. switch (getOpenMPRuntime(ToolChain, Args)) {
  7383. case OMPRT_OMP:
  7384. CmdArgs.push_back("-lomp");
  7385. break;
  7386. case OMPRT_GOMP:
  7387. CmdArgs.push_back("-lgomp");
  7388. // FIXME: Exclude this for platforms with libgomp that don't require
  7389. // librt. Most modern Linux platforms require it, but some may not.
  7390. CmdArgs.push_back("-lrt");
  7391. break;
  7392. case OMPRT_IOMP5:
  7393. CmdArgs.push_back("-liomp5");
  7394. break;
  7395. case OMPRT_Unknown:
  7396. // Already diagnosed.
  7397. break;
  7398. }
  7399. }
  7400. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  7401. if (WantPthread && !isAndroid)
  7402. CmdArgs.push_back("-lpthread");
  7403. CmdArgs.push_back("-lc");
  7404. if (Args.hasArg(options::OPT_static))
  7405. CmdArgs.push_back("--end-group");
  7406. else
  7407. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  7408. }
  7409. if (!Args.hasArg(options::OPT_nostartfiles)) {
  7410. const char *crtend;
  7411. if (Args.hasArg(options::OPT_shared))
  7412. crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
  7413. else if (IsPIE)
  7414. crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
  7415. else
  7416. crtend = isAndroid ? "crtend_android.o" : "crtend.o";
  7417. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  7418. if (!isAndroid)
  7419. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  7420. }
  7421. }
  7422. C.addCommand(llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(),
  7423. CmdArgs, Inputs));
  7424. }
  7425. // NaCl ARM assembly (inline or standalone) can be written with a set of macros
  7426. // for the various SFI requirements like register masking. The assembly tool
  7427. // inserts the file containing the macros as an input into all the assembly
  7428. // jobs.
  7429. void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
  7430. const InputInfo &Output,
  7431. const InputInfoList &Inputs,
  7432. const ArgList &Args,
  7433. const char *LinkingOutput) const {
  7434. const toolchains::NaClToolChain &ToolChain =
  7435. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  7436. InputInfo NaClMacros(ToolChain.GetNaClArmMacrosPath(), types::TY_PP_Asm,
  7437. "nacl-arm-macros.s");
  7438. InputInfoList NewInputs;
  7439. NewInputs.push_back(NaClMacros);
  7440. NewInputs.append(Inputs.begin(), Inputs.end());
  7441. gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
  7442. LinkingOutput);
  7443. }
  7444. // This is quite similar to gnutools::Linker::ConstructJob with changes that
  7445. // we use static by default, do not yet support sanitizers or LTO, and a few
  7446. // others. Eventually we can support more of that and hopefully migrate back
  7447. // to gnutools::Linker.
  7448. void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7449. const InputInfo &Output,
  7450. const InputInfoList &Inputs,
  7451. const ArgList &Args,
  7452. const char *LinkingOutput) const {
  7453. const toolchains::NaClToolChain &ToolChain =
  7454. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  7455. const Driver &D = ToolChain.getDriver();
  7456. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7457. const bool IsStatic =
  7458. !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
  7459. ArgStringList CmdArgs;
  7460. // Silence warning for "clang -g foo.o -o foo"
  7461. Args.ClaimAllArgs(options::OPT_g_Group);
  7462. // and "clang -emit-llvm foo.o -o foo"
  7463. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7464. // and for "clang -w foo.o -o foo". Other warning options are already
  7465. // handled somewhere else.
  7466. Args.ClaimAllArgs(options::OPT_w);
  7467. if (!D.SysRoot.empty())
  7468. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7469. if (Args.hasArg(options::OPT_rdynamic))
  7470. CmdArgs.push_back("-export-dynamic");
  7471. if (Args.hasArg(options::OPT_s))
  7472. CmdArgs.push_back("-s");
  7473. // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
  7474. // from there is --build-id, which we do want.
  7475. CmdArgs.push_back("--build-id");
  7476. if (!IsStatic)
  7477. CmdArgs.push_back("--eh-frame-hdr");
  7478. CmdArgs.push_back("-m");
  7479. if (Arch == llvm::Triple::x86)
  7480. CmdArgs.push_back("elf_i386_nacl");
  7481. else if (Arch == llvm::Triple::arm)
  7482. CmdArgs.push_back("armelf_nacl");
  7483. else if (Arch == llvm::Triple::x86_64)
  7484. CmdArgs.push_back("elf_x86_64_nacl");
  7485. else if (Arch == llvm::Triple::mipsel)
  7486. CmdArgs.push_back("mipselelf_nacl");
  7487. else
  7488. D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
  7489. << "Native Client";
  7490. if (IsStatic)
  7491. CmdArgs.push_back("-static");
  7492. else if (Args.hasArg(options::OPT_shared))
  7493. CmdArgs.push_back("-shared");
  7494. CmdArgs.push_back("-o");
  7495. CmdArgs.push_back(Output.getFilename());
  7496. if (!Args.hasArg(options::OPT_nostdlib) &&
  7497. !Args.hasArg(options::OPT_nostartfiles)) {
  7498. if (!Args.hasArg(options::OPT_shared))
  7499. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  7500. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  7501. const char *crtbegin;
  7502. if (IsStatic)
  7503. crtbegin = "crtbeginT.o";
  7504. else if (Args.hasArg(options::OPT_shared))
  7505. crtbegin = "crtbeginS.o";
  7506. else
  7507. crtbegin = "crtbegin.o";
  7508. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  7509. }
  7510. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7511. Args.AddAllArgs(CmdArgs, options::OPT_u);
  7512. const ToolChain::path_list &Paths = ToolChain.getFilePaths();
  7513. for (const auto &Path : Paths)
  7514. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
  7515. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  7516. CmdArgs.push_back("--no-demangle");
  7517. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  7518. if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
  7519. !Args.hasArg(options::OPT_nodefaultlibs)) {
  7520. bool OnlyLibstdcxxStatic =
  7521. Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
  7522. if (OnlyLibstdcxxStatic)
  7523. CmdArgs.push_back("-Bstatic");
  7524. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7525. if (OnlyLibstdcxxStatic)
  7526. CmdArgs.push_back("-Bdynamic");
  7527. CmdArgs.push_back("-lm");
  7528. }
  7529. if (!Args.hasArg(options::OPT_nostdlib)) {
  7530. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  7531. // Always use groups, since it has no effect on dynamic libraries.
  7532. CmdArgs.push_back("--start-group");
  7533. CmdArgs.push_back("-lc");
  7534. // NaCl's libc++ currently requires libpthread, so just always include it
  7535. // in the group for C++.
  7536. if (Args.hasArg(options::OPT_pthread) ||
  7537. Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
  7538. // Gold, used by Mips, handles nested groups differently than ld, and
  7539. // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
  7540. // which is not a desired behaviour here.
  7541. // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
  7542. if (getToolChain().getArch() == llvm::Triple::mipsel)
  7543. CmdArgs.push_back("-lnacl");
  7544. CmdArgs.push_back("-lpthread");
  7545. }
  7546. CmdArgs.push_back("-lgcc");
  7547. CmdArgs.push_back("--as-needed");
  7548. if (IsStatic)
  7549. CmdArgs.push_back("-lgcc_eh");
  7550. else
  7551. CmdArgs.push_back("-lgcc_s");
  7552. CmdArgs.push_back("--no-as-needed");
  7553. // Mips needs to create and use pnacl_legacy library that contains
  7554. // definitions from bitcode/pnaclmm.c and definitions for
  7555. // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
  7556. if (getToolChain().getArch() == llvm::Triple::mipsel)
  7557. CmdArgs.push_back("-lpnacl_legacy");
  7558. CmdArgs.push_back("--end-group");
  7559. }
  7560. if (!Args.hasArg(options::OPT_nostartfiles)) {
  7561. const char *crtend;
  7562. if (Args.hasArg(options::OPT_shared))
  7563. crtend = "crtendS.o";
  7564. else
  7565. crtend = "crtend.o";
  7566. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  7567. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  7568. }
  7569. }
  7570. C.addCommand(llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(),
  7571. CmdArgs, Inputs));
  7572. }
  7573. void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7574. const InputInfo &Output,
  7575. const InputInfoList &Inputs,
  7576. const ArgList &Args,
  7577. const char *LinkingOutput) const {
  7578. claimNoWarnArgs(Args);
  7579. ArgStringList CmdArgs;
  7580. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7581. CmdArgs.push_back("-o");
  7582. CmdArgs.push_back(Output.getFilename());
  7583. for (const auto &II : Inputs)
  7584. CmdArgs.push_back(II.getFilename());
  7585. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7586. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7587. }
  7588. void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7589. const InputInfo &Output,
  7590. const InputInfoList &Inputs,
  7591. const ArgList &Args,
  7592. const char *LinkingOutput) const {
  7593. const Driver &D = getToolChain().getDriver();
  7594. ArgStringList CmdArgs;
  7595. if (Output.isFilename()) {
  7596. CmdArgs.push_back("-o");
  7597. CmdArgs.push_back(Output.getFilename());
  7598. } else {
  7599. assert(Output.isNothing() && "Invalid output.");
  7600. }
  7601. if (!Args.hasArg(options::OPT_nostdlib) &&
  7602. !Args.hasArg(options::OPT_nostartfiles)) {
  7603. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  7604. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7605. CmdArgs.push_back(
  7606. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7607. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  7608. }
  7609. Args.AddAllArgs(CmdArgs,
  7610. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  7611. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7612. addProfileRT(getToolChain(), Args, CmdArgs);
  7613. if (!Args.hasArg(options::OPT_nostdlib) &&
  7614. !Args.hasArg(options::OPT_nodefaultlibs)) {
  7615. if (D.CCCIsCXX()) {
  7616. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7617. CmdArgs.push_back("-lm");
  7618. }
  7619. }
  7620. if (!Args.hasArg(options::OPT_nostdlib) &&
  7621. !Args.hasArg(options::OPT_nostartfiles)) {
  7622. if (Args.hasArg(options::OPT_pthread))
  7623. CmdArgs.push_back("-lpthread");
  7624. CmdArgs.push_back("-lc");
  7625. CmdArgs.push_back("-lCompilerRT-Generic");
  7626. CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
  7627. CmdArgs.push_back(
  7628. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7629. }
  7630. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7631. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7632. }
  7633. /// DragonFly Tools
  7634. // For now, DragonFly Assemble does just about the same as for
  7635. // FreeBSD, but this may change soon.
  7636. void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7637. const InputInfo &Output,
  7638. const InputInfoList &Inputs,
  7639. const ArgList &Args,
  7640. const char *LinkingOutput) const {
  7641. claimNoWarnArgs(Args);
  7642. ArgStringList CmdArgs;
  7643. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  7644. // instruct as in the base system to assemble 32-bit code.
  7645. if (getToolChain().getArch() == llvm::Triple::x86)
  7646. CmdArgs.push_back("--32");
  7647. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7648. CmdArgs.push_back("-o");
  7649. CmdArgs.push_back(Output.getFilename());
  7650. for (const auto &II : Inputs)
  7651. CmdArgs.push_back(II.getFilename());
  7652. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7653. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7654. }
  7655. void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7656. const InputInfo &Output,
  7657. const InputInfoList &Inputs,
  7658. const ArgList &Args,
  7659. const char *LinkingOutput) const {
  7660. const Driver &D = getToolChain().getDriver();
  7661. ArgStringList CmdArgs;
  7662. bool UseGCC47 = llvm::sys::fs::exists("/usr/lib/gcc47");
  7663. if (!D.SysRoot.empty())
  7664. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7665. CmdArgs.push_back("--eh-frame-hdr");
  7666. if (Args.hasArg(options::OPT_static)) {
  7667. CmdArgs.push_back("-Bstatic");
  7668. } else {
  7669. if (Args.hasArg(options::OPT_rdynamic))
  7670. CmdArgs.push_back("-export-dynamic");
  7671. if (Args.hasArg(options::OPT_shared))
  7672. CmdArgs.push_back("-Bshareable");
  7673. else {
  7674. CmdArgs.push_back("-dynamic-linker");
  7675. CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
  7676. }
  7677. CmdArgs.push_back("--hash-style=both");
  7678. }
  7679. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  7680. // instruct ld in the base system to link 32-bit code.
  7681. if (getToolChain().getArch() == llvm::Triple::x86) {
  7682. CmdArgs.push_back("-m");
  7683. CmdArgs.push_back("elf_i386");
  7684. }
  7685. if (Output.isFilename()) {
  7686. CmdArgs.push_back("-o");
  7687. CmdArgs.push_back(Output.getFilename());
  7688. } else {
  7689. assert(Output.isNothing() && "Invalid output.");
  7690. }
  7691. if (!Args.hasArg(options::OPT_nostdlib) &&
  7692. !Args.hasArg(options::OPT_nostartfiles)) {
  7693. if (!Args.hasArg(options::OPT_shared)) {
  7694. if (Args.hasArg(options::OPT_pg))
  7695. CmdArgs.push_back(
  7696. Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
  7697. else {
  7698. if (Args.hasArg(options::OPT_pie))
  7699. CmdArgs.push_back(
  7700. Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
  7701. else
  7702. CmdArgs.push_back(
  7703. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  7704. }
  7705. }
  7706. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7707. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  7708. CmdArgs.push_back(
  7709. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7710. else
  7711. CmdArgs.push_back(
  7712. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7713. }
  7714. Args.AddAllArgs(CmdArgs,
  7715. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  7716. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7717. if (!Args.hasArg(options::OPT_nostdlib) &&
  7718. !Args.hasArg(options::OPT_nodefaultlibs)) {
  7719. // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
  7720. // rpaths
  7721. if (UseGCC47)
  7722. CmdArgs.push_back("-L/usr/lib/gcc47");
  7723. else
  7724. CmdArgs.push_back("-L/usr/lib/gcc44");
  7725. if (!Args.hasArg(options::OPT_static)) {
  7726. if (UseGCC47) {
  7727. CmdArgs.push_back("-rpath");
  7728. CmdArgs.push_back("/usr/lib/gcc47");
  7729. } else {
  7730. CmdArgs.push_back("-rpath");
  7731. CmdArgs.push_back("/usr/lib/gcc44");
  7732. }
  7733. }
  7734. if (D.CCCIsCXX()) {
  7735. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7736. CmdArgs.push_back("-lm");
  7737. }
  7738. if (Args.hasArg(options::OPT_pthread))
  7739. CmdArgs.push_back("-lpthread");
  7740. if (!Args.hasArg(options::OPT_nolibc)) {
  7741. CmdArgs.push_back("-lc");
  7742. }
  7743. if (UseGCC47) {
  7744. if (Args.hasArg(options::OPT_static) ||
  7745. Args.hasArg(options::OPT_static_libgcc)) {
  7746. CmdArgs.push_back("-lgcc");
  7747. CmdArgs.push_back("-lgcc_eh");
  7748. } else {
  7749. if (Args.hasArg(options::OPT_shared_libgcc)) {
  7750. CmdArgs.push_back("-lgcc_pic");
  7751. if (!Args.hasArg(options::OPT_shared))
  7752. CmdArgs.push_back("-lgcc");
  7753. } else {
  7754. CmdArgs.push_back("-lgcc");
  7755. CmdArgs.push_back("--as-needed");
  7756. CmdArgs.push_back("-lgcc_pic");
  7757. CmdArgs.push_back("--no-as-needed");
  7758. }
  7759. }
  7760. } else {
  7761. if (Args.hasArg(options::OPT_shared)) {
  7762. CmdArgs.push_back("-lgcc_pic");
  7763. } else {
  7764. CmdArgs.push_back("-lgcc");
  7765. }
  7766. }
  7767. }
  7768. if (!Args.hasArg(options::OPT_nostdlib) &&
  7769. !Args.hasArg(options::OPT_nostartfiles)) {
  7770. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  7771. CmdArgs.push_back(
  7772. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7773. else
  7774. CmdArgs.push_back(
  7775. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7776. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  7777. }
  7778. addProfileRT(getToolChain(), Args, CmdArgs);
  7779. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7780. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7781. }
  7782. // Try to find Exe from a Visual Studio distribution. This first tries to find
  7783. // an installed copy of Visual Studio and, failing that, looks in the PATH,
  7784. // making sure that whatever executable that's found is not a same-named exe
  7785. // from clang itself to prevent clang from falling back to itself.
  7786. static std::string FindVisualStudioExecutable(const ToolChain &TC,
  7787. const char *Exe,
  7788. const char *ClangProgramPath) {
  7789. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  7790. std::string visualStudioBinDir;
  7791. if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
  7792. visualStudioBinDir)) {
  7793. SmallString<128> FilePath(visualStudioBinDir);
  7794. llvm::sys::path::append(FilePath, Exe);
  7795. if (llvm::sys::fs::can_execute(FilePath.c_str()))
  7796. return FilePath.str();
  7797. }
  7798. return Exe;
  7799. }
  7800. void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7801. const InputInfo &Output,
  7802. const InputInfoList &Inputs,
  7803. const ArgList &Args,
  7804. const char *LinkingOutput) const {
  7805. ArgStringList CmdArgs;
  7806. const ToolChain &TC = getToolChain();
  7807. assert((Output.isFilename() || Output.isNothing()) && "invalid output");
  7808. if (Output.isFilename())
  7809. CmdArgs.push_back(
  7810. Args.MakeArgString(std::string("-out:") + Output.getFilename()));
  7811. if (!Args.hasArg(options::OPT_nostdlib) &&
  7812. !Args.hasArg(options::OPT_nostartfiles) && !C.getDriver().IsCLMode())
  7813. CmdArgs.push_back("-defaultlib:libcmt");
  7814. if (!llvm::sys::Process::GetEnv("LIB")) {
  7815. // If the VC environment hasn't been configured (perhaps because the user
  7816. // did not run vcvarsall), try to build a consistent link environment. If
  7817. // the environment variable is set however, assume the user knows what
  7818. // they're doing.
  7819. std::string VisualStudioDir;
  7820. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  7821. if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
  7822. SmallString<128> LibDir(VisualStudioDir);
  7823. llvm::sys::path::append(LibDir, "VC", "lib");
  7824. switch (MSVC.getArch()) {
  7825. case llvm::Triple::x86:
  7826. // x86 just puts the libraries directly in lib
  7827. break;
  7828. case llvm::Triple::x86_64:
  7829. llvm::sys::path::append(LibDir, "amd64");
  7830. break;
  7831. case llvm::Triple::arm:
  7832. llvm::sys::path::append(LibDir, "arm");
  7833. break;
  7834. default:
  7835. break;
  7836. }
  7837. CmdArgs.push_back(
  7838. Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
  7839. if (MSVC.useUniversalCRT(VisualStudioDir)) {
  7840. std::string UniversalCRTLibPath;
  7841. if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
  7842. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  7843. UniversalCRTLibPath.c_str()));
  7844. }
  7845. }
  7846. std::string WindowsSdkLibPath;
  7847. if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
  7848. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  7849. WindowsSdkLibPath.c_str()));
  7850. }
  7851. CmdArgs.push_back("-nologo");
  7852. if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
  7853. CmdArgs.push_back("-debug");
  7854. bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
  7855. options::OPT_shared);
  7856. if (DLL) {
  7857. CmdArgs.push_back(Args.MakeArgString("-dll"));
  7858. SmallString<128> ImplibName(Output.getFilename());
  7859. llvm::sys::path::replace_extension(ImplibName, "lib");
  7860. CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
  7861. }
  7862. if (TC.getSanitizerArgs().needsAsanRt()) {
  7863. CmdArgs.push_back(Args.MakeArgString("-debug"));
  7864. CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
  7865. if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
  7866. static const char *CompilerRTComponents[] = {
  7867. "asan_dynamic", "asan_dynamic_runtime_thunk",
  7868. };
  7869. for (const auto &Component : CompilerRTComponents)
  7870. CmdArgs.push_back(getCompilerRTArgString(TC, Args, Component));
  7871. // Make sure the dynamic runtime thunk is not optimized out at link time
  7872. // to ensure proper SEH handling.
  7873. CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
  7874. } else if (DLL) {
  7875. CmdArgs.push_back(getCompilerRTArgString(TC, Args, "asan_dll_thunk"));
  7876. } else {
  7877. static const char *CompilerRTComponents[] = {
  7878. "asan", "asan_cxx",
  7879. };
  7880. for (const auto &Component : CompilerRTComponents)
  7881. CmdArgs.push_back(getCompilerRTArgString(TC, Args, Component));
  7882. }
  7883. }
  7884. Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
  7885. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  7886. options::OPT_fno_openmp, false)) {
  7887. CmdArgs.push_back("-nodefaultlib:vcomp.lib");
  7888. CmdArgs.push_back("-nodefaultlib:vcompd.lib");
  7889. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  7890. TC.getDriver().Dir + "/../lib"));
  7891. switch (getOpenMPRuntime(getToolChain(), Args)) {
  7892. case OMPRT_OMP:
  7893. CmdArgs.push_back("-defaultlib:libomp.lib");
  7894. break;
  7895. case OMPRT_IOMP5:
  7896. CmdArgs.push_back("-defaultlib:libiomp5md.lib");
  7897. break;
  7898. case OMPRT_GOMP:
  7899. break;
  7900. case OMPRT_Unknown:
  7901. // Already diagnosed.
  7902. break;
  7903. }
  7904. }
  7905. // Add filenames, libraries, and other linker inputs.
  7906. for (const auto &Input : Inputs) {
  7907. if (Input.isFilename()) {
  7908. CmdArgs.push_back(Input.getFilename());
  7909. continue;
  7910. }
  7911. const Arg &A = Input.getInputArg();
  7912. // Render -l options differently for the MSVC linker.
  7913. if (A.getOption().matches(options::OPT_l)) {
  7914. StringRef Lib = A.getValue();
  7915. const char *LinkLibArg;
  7916. if (Lib.endswith(".lib"))
  7917. LinkLibArg = Args.MakeArgString(Lib);
  7918. else
  7919. LinkLibArg = Args.MakeArgString(Lib + ".lib");
  7920. CmdArgs.push_back(LinkLibArg);
  7921. continue;
  7922. }
  7923. // Otherwise, this is some other kind of linker input option like -Wl, -z,
  7924. // or -L. Render it, even if MSVC doesn't understand it.
  7925. A.renderAsInput(Args, CmdArgs);
  7926. }
  7927. // We need to special case some linker paths. In the case of lld, we need to
  7928. // translate 'lld' into 'lld-link', and in the case of the regular msvc
  7929. // linker, we need to use a special search algorithm.
  7930. llvm::SmallString<128> linkPath;
  7931. StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
  7932. if (Linker.equals_lower("lld"))
  7933. Linker = "lld-link";
  7934. if (Linker.equals_lower("link")) {
  7935. // If we're using the MSVC linker, it's not sufficient to just use link
  7936. // from the program PATH, because other environments like GnuWin32 install
  7937. // their own link.exe which may come first.
  7938. linkPath = FindVisualStudioExecutable(TC, "link.exe",
  7939. C.getDriver().getClangProgramPath());
  7940. } else {
  7941. linkPath = Linker;
  7942. llvm::sys::path::replace_extension(linkPath, "exe");
  7943. linkPath = TC.GetProgramPath(linkPath.c_str());
  7944. }
  7945. const char *Exec = Args.MakeArgString(linkPath);
  7946. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7947. }
  7948. void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  7949. const InputInfo &Output,
  7950. const InputInfoList &Inputs,
  7951. const ArgList &Args,
  7952. const char *LinkingOutput) const {
  7953. C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
  7954. }
  7955. std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
  7956. Compilation &C, const JobAction &JA, const InputInfo &Output,
  7957. const InputInfoList &Inputs, const ArgList &Args,
  7958. const char *LinkingOutput) const {
  7959. ArgStringList CmdArgs;
  7960. CmdArgs.push_back("/nologo");
  7961. CmdArgs.push_back("/c"); // Compile only.
  7962. CmdArgs.push_back("/W0"); // No warnings.
  7963. // The goal is to be able to invoke this tool correctly based on
  7964. // any flag accepted by clang-cl.
  7965. // These are spelled the same way in clang and cl.exe,.
  7966. Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
  7967. // Optimization level.
  7968. if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
  7969. CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
  7970. : "/Oi-");
  7971. if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
  7972. if (A->getOption().getID() == options::OPT_O0) {
  7973. CmdArgs.push_back("/Od");
  7974. } else {
  7975. CmdArgs.push_back("/Og");
  7976. StringRef OptLevel = A->getValue();
  7977. if (OptLevel == "s" || OptLevel == "z")
  7978. CmdArgs.push_back("/Os");
  7979. else
  7980. CmdArgs.push_back("/Ot");
  7981. CmdArgs.push_back("/Ob2");
  7982. }
  7983. }
  7984. if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
  7985. options::OPT_fno_omit_frame_pointer))
  7986. CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
  7987. ? "/Oy"
  7988. : "/Oy-");
  7989. if (!Args.hasArg(options::OPT_fwritable_strings))
  7990. CmdArgs.push_back("/GF");
  7991. // Flags for which clang-cl has an alias.
  7992. // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
  7993. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  7994. /*default=*/false))
  7995. CmdArgs.push_back("/GR-");
  7996. if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
  7997. options::OPT_fno_function_sections))
  7998. CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
  7999. ? "/Gy"
  8000. : "/Gy-");
  8001. if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
  8002. options::OPT_fno_data_sections))
  8003. CmdArgs.push_back(
  8004. A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
  8005. if (Args.hasArg(options::OPT_fsyntax_only))
  8006. CmdArgs.push_back("/Zs");
  8007. if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
  8008. options::OPT__SLASH_Z7))
  8009. CmdArgs.push_back("/Z7");
  8010. std::vector<std::string> Includes =
  8011. Args.getAllArgValues(options::OPT_include);
  8012. for (const auto &Include : Includes)
  8013. CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
  8014. // Flags that can simply be passed through.
  8015. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
  8016. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
  8017. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
  8018. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
  8019. // The order of these flags is relevant, so pick the last one.
  8020. if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
  8021. options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
  8022. A->render(Args, CmdArgs);
  8023. // Input filename.
  8024. assert(Inputs.size() == 1);
  8025. const InputInfo &II = Inputs[0];
  8026. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
  8027. CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
  8028. if (II.isFilename())
  8029. CmdArgs.push_back(II.getFilename());
  8030. else
  8031. II.getInputArg().renderAsInput(Args, CmdArgs);
  8032. // Output filename.
  8033. assert(Output.getType() == types::TY_Object);
  8034. const char *Fo =
  8035. Args.MakeArgString(std::string("/Fo") + Output.getFilename());
  8036. CmdArgs.push_back(Fo);
  8037. const Driver &D = getToolChain().getDriver();
  8038. std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
  8039. D.getClangProgramPath());
  8040. return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8041. CmdArgs, Inputs);
  8042. }
  8043. /// MinGW Tools
  8044. void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8045. const InputInfo &Output,
  8046. const InputInfoList &Inputs,
  8047. const ArgList &Args,
  8048. const char *LinkingOutput) const {
  8049. claimNoWarnArgs(Args);
  8050. ArgStringList CmdArgs;
  8051. if (getToolChain().getArch() == llvm::Triple::x86) {
  8052. CmdArgs.push_back("--32");
  8053. } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
  8054. CmdArgs.push_back("--64");
  8055. }
  8056. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8057. CmdArgs.push_back("-o");
  8058. CmdArgs.push_back(Output.getFilename());
  8059. for (const auto &II : Inputs)
  8060. CmdArgs.push_back(II.getFilename());
  8061. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8062. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8063. if (Args.hasArg(options::OPT_gsplit_dwarf))
  8064. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  8065. SplitDebugName(Args, Inputs[0]));
  8066. }
  8067. void MinGW::Linker::AddLibGCC(const ArgList &Args,
  8068. ArgStringList &CmdArgs) const {
  8069. if (Args.hasArg(options::OPT_mthreads))
  8070. CmdArgs.push_back("-lmingwthrd");
  8071. CmdArgs.push_back("-lmingw32");
  8072. // Make use of compiler-rt if --rtlib option is used
  8073. ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
  8074. if (RLT == ToolChain::RLT_Libgcc) {
  8075. bool Static = Args.hasArg(options::OPT_static_libgcc) ||
  8076. Args.hasArg(options::OPT_static);
  8077. bool Shared = Args.hasArg(options::OPT_shared);
  8078. bool CXX = getToolChain().getDriver().CCCIsCXX();
  8079. if (Static || (!CXX && !Shared)) {
  8080. CmdArgs.push_back("-lgcc");
  8081. CmdArgs.push_back("-lgcc_eh");
  8082. } else {
  8083. CmdArgs.push_back("-lgcc_s");
  8084. CmdArgs.push_back("-lgcc");
  8085. }
  8086. } else {
  8087. AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
  8088. }
  8089. CmdArgs.push_back("-lmoldname");
  8090. CmdArgs.push_back("-lmingwex");
  8091. CmdArgs.push_back("-lmsvcrt");
  8092. }
  8093. void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8094. const InputInfo &Output,
  8095. const InputInfoList &Inputs,
  8096. const ArgList &Args,
  8097. const char *LinkingOutput) const {
  8098. const ToolChain &TC = getToolChain();
  8099. const Driver &D = TC.getDriver();
  8100. // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
  8101. ArgStringList CmdArgs;
  8102. // Silence warning for "clang -g foo.o -o foo"
  8103. Args.ClaimAllArgs(options::OPT_g_Group);
  8104. // and "clang -emit-llvm foo.o -o foo"
  8105. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8106. // and for "clang -w foo.o -o foo". Other warning options are already
  8107. // handled somewhere else.
  8108. Args.ClaimAllArgs(options::OPT_w);
  8109. StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
  8110. if (LinkerName.equals_lower("lld")) {
  8111. CmdArgs.push_back("-flavor");
  8112. CmdArgs.push_back("gnu");
  8113. }
  8114. if (!D.SysRoot.empty())
  8115. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8116. if (Args.hasArg(options::OPT_s))
  8117. CmdArgs.push_back("-s");
  8118. CmdArgs.push_back("-m");
  8119. if (TC.getArch() == llvm::Triple::x86)
  8120. CmdArgs.push_back("i386pe");
  8121. if (TC.getArch() == llvm::Triple::x86_64)
  8122. CmdArgs.push_back("i386pep");
  8123. if (TC.getArch() == llvm::Triple::arm)
  8124. CmdArgs.push_back("thumb2pe");
  8125. if (Args.hasArg(options::OPT_mwindows)) {
  8126. CmdArgs.push_back("--subsystem");
  8127. CmdArgs.push_back("windows");
  8128. } else if (Args.hasArg(options::OPT_mconsole)) {
  8129. CmdArgs.push_back("--subsystem");
  8130. CmdArgs.push_back("console");
  8131. }
  8132. if (Args.hasArg(options::OPT_static))
  8133. CmdArgs.push_back("-Bstatic");
  8134. else {
  8135. if (Args.hasArg(options::OPT_mdll))
  8136. CmdArgs.push_back("--dll");
  8137. else if (Args.hasArg(options::OPT_shared))
  8138. CmdArgs.push_back("--shared");
  8139. CmdArgs.push_back("-Bdynamic");
  8140. if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
  8141. CmdArgs.push_back("-e");
  8142. if (TC.getArch() == llvm::Triple::x86)
  8143. CmdArgs.push_back("_DllMainCRTStartup@12");
  8144. else
  8145. CmdArgs.push_back("DllMainCRTStartup");
  8146. CmdArgs.push_back("--enable-auto-image-base");
  8147. }
  8148. }
  8149. CmdArgs.push_back("-o");
  8150. CmdArgs.push_back(Output.getFilename());
  8151. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8152. // FIXME: add -N, -n flags
  8153. Args.AddLastArg(CmdArgs, options::OPT_r);
  8154. Args.AddLastArg(CmdArgs, options::OPT_s);
  8155. Args.AddLastArg(CmdArgs, options::OPT_t);
  8156. Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
  8157. Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
  8158. if (!Args.hasArg(options::OPT_nostdlib) &&
  8159. !Args.hasArg(options::OPT_nostartfiles)) {
  8160. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
  8161. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
  8162. } else {
  8163. if (Args.hasArg(options::OPT_municode))
  8164. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
  8165. else
  8166. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
  8167. }
  8168. if (Args.hasArg(options::OPT_pg))
  8169. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
  8170. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  8171. }
  8172. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8173. const ToolChain::path_list Paths = TC.getFilePaths();
  8174. for (const auto &Path : Paths)
  8175. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
  8176. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  8177. // TODO: Add ASan stuff here
  8178. // TODO: Add profile stuff here
  8179. if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
  8180. !Args.hasArg(options::OPT_nodefaultlibs)) {
  8181. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  8182. !Args.hasArg(options::OPT_static);
  8183. if (OnlyLibstdcxxStatic)
  8184. CmdArgs.push_back("-Bstatic");
  8185. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  8186. if (OnlyLibstdcxxStatic)
  8187. CmdArgs.push_back("-Bdynamic");
  8188. }
  8189. if (!Args.hasArg(options::OPT_nostdlib)) {
  8190. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8191. if (Args.hasArg(options::OPT_static))
  8192. CmdArgs.push_back("--start-group");
  8193. if (Args.hasArg(options::OPT_fstack_protector) ||
  8194. Args.hasArg(options::OPT_fstack_protector_strong) ||
  8195. Args.hasArg(options::OPT_fstack_protector_all)) {
  8196. CmdArgs.push_back("-lssp_nonshared");
  8197. CmdArgs.push_back("-lssp");
  8198. }
  8199. if (Args.hasArg(options::OPT_fopenmp))
  8200. CmdArgs.push_back("-lgomp");
  8201. AddLibGCC(Args, CmdArgs);
  8202. if (Args.hasArg(options::OPT_pg))
  8203. CmdArgs.push_back("-lgmon");
  8204. if (Args.hasArg(options::OPT_pthread))
  8205. CmdArgs.push_back("-lpthread");
  8206. // add system libraries
  8207. if (Args.hasArg(options::OPT_mwindows)) {
  8208. CmdArgs.push_back("-lgdi32");
  8209. CmdArgs.push_back("-lcomdlg32");
  8210. }
  8211. CmdArgs.push_back("-ladvapi32");
  8212. CmdArgs.push_back("-lshell32");
  8213. CmdArgs.push_back("-luser32");
  8214. CmdArgs.push_back("-lkernel32");
  8215. if (Args.hasArg(options::OPT_static))
  8216. CmdArgs.push_back("--end-group");
  8217. else if (!LinkerName.equals_lower("lld"))
  8218. AddLibGCC(Args, CmdArgs);
  8219. }
  8220. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8221. // Add crtfastmath.o if available and fast math is enabled.
  8222. TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  8223. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  8224. }
  8225. }
  8226. const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
  8227. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8228. }
  8229. /// XCore Tools
  8230. // We pass assemble and link construction to the xcc tool.
  8231. void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8232. const InputInfo &Output,
  8233. const InputInfoList &Inputs,
  8234. const ArgList &Args,
  8235. const char *LinkingOutput) const {
  8236. claimNoWarnArgs(Args);
  8237. ArgStringList CmdArgs;
  8238. CmdArgs.push_back("-o");
  8239. CmdArgs.push_back(Output.getFilename());
  8240. CmdArgs.push_back("-c");
  8241. if (Args.hasArg(options::OPT_v))
  8242. CmdArgs.push_back("-v");
  8243. if (Arg *A = Args.getLastArg(options::OPT_g_Group))
  8244. if (!A->getOption().matches(options::OPT_g0))
  8245. CmdArgs.push_back("-g");
  8246. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  8247. false))
  8248. CmdArgs.push_back("-fverbose-asm");
  8249. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8250. for (const auto &II : Inputs)
  8251. CmdArgs.push_back(II.getFilename());
  8252. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8253. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8254. }
  8255. void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8256. const InputInfo &Output,
  8257. const InputInfoList &Inputs,
  8258. const ArgList &Args,
  8259. const char *LinkingOutput) const {
  8260. ArgStringList CmdArgs;
  8261. if (Output.isFilename()) {
  8262. CmdArgs.push_back("-o");
  8263. CmdArgs.push_back(Output.getFilename());
  8264. } else {
  8265. assert(Output.isNothing() && "Invalid output.");
  8266. }
  8267. if (Args.hasArg(options::OPT_v))
  8268. CmdArgs.push_back("-v");
  8269. // Pass -fexceptions through to the linker if it was present.
  8270. if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  8271. false))
  8272. CmdArgs.push_back("-fexceptions");
  8273. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8274. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8275. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8276. }
  8277. void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8278. const InputInfo &Output,
  8279. const InputInfoList &Inputs,
  8280. const ArgList &Args,
  8281. const char *LinkingOutput) const {
  8282. claimNoWarnArgs(Args);
  8283. const auto &TC =
  8284. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  8285. ArgStringList CmdArgs;
  8286. const char *Exec;
  8287. switch (TC.getArch()) {
  8288. default:
  8289. llvm_unreachable("unsupported architecture");
  8290. case llvm::Triple::arm:
  8291. case llvm::Triple::thumb:
  8292. break;
  8293. case llvm::Triple::x86:
  8294. CmdArgs.push_back("--32");
  8295. break;
  8296. case llvm::Triple::x86_64:
  8297. CmdArgs.push_back("--64");
  8298. break;
  8299. }
  8300. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8301. CmdArgs.push_back("-o");
  8302. CmdArgs.push_back(Output.getFilename());
  8303. for (const auto &Input : Inputs)
  8304. CmdArgs.push_back(Input.getFilename());
  8305. const std::string Assembler = TC.GetProgramPath("as");
  8306. Exec = Args.MakeArgString(Assembler);
  8307. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8308. }
  8309. void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8310. const InputInfo &Output,
  8311. const InputInfoList &Inputs,
  8312. const ArgList &Args,
  8313. const char *LinkingOutput) const {
  8314. const auto &TC =
  8315. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  8316. const llvm::Triple &T = TC.getTriple();
  8317. const Driver &D = TC.getDriver();
  8318. SmallString<128> EntryPoint;
  8319. ArgStringList CmdArgs;
  8320. const char *Exec;
  8321. // Silence warning for "clang -g foo.o -o foo"
  8322. Args.ClaimAllArgs(options::OPT_g_Group);
  8323. // and "clang -emit-llvm foo.o -o foo"
  8324. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8325. // and for "clang -w foo.o -o foo"
  8326. Args.ClaimAllArgs(options::OPT_w);
  8327. // Other warning options are already handled somewhere else.
  8328. if (!D.SysRoot.empty())
  8329. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8330. if (Args.hasArg(options::OPT_pie))
  8331. CmdArgs.push_back("-pie");
  8332. if (Args.hasArg(options::OPT_rdynamic))
  8333. CmdArgs.push_back("-export-dynamic");
  8334. if (Args.hasArg(options::OPT_s))
  8335. CmdArgs.push_back("--strip-all");
  8336. CmdArgs.push_back("-m");
  8337. switch (TC.getArch()) {
  8338. default:
  8339. llvm_unreachable("unsupported architecture");
  8340. case llvm::Triple::arm:
  8341. case llvm::Triple::thumb:
  8342. // FIXME: this is incorrect for WinCE
  8343. CmdArgs.push_back("thumb2pe");
  8344. break;
  8345. case llvm::Triple::x86:
  8346. CmdArgs.push_back("i386pe");
  8347. EntryPoint.append("_");
  8348. break;
  8349. case llvm::Triple::x86_64:
  8350. CmdArgs.push_back("i386pep");
  8351. break;
  8352. }
  8353. if (Args.hasArg(options::OPT_shared)) {
  8354. switch (T.getArch()) {
  8355. default:
  8356. llvm_unreachable("unsupported architecture");
  8357. case llvm::Triple::arm:
  8358. case llvm::Triple::thumb:
  8359. case llvm::Triple::x86_64:
  8360. EntryPoint.append("_DllMainCRTStartup");
  8361. break;
  8362. case llvm::Triple::x86:
  8363. EntryPoint.append("_DllMainCRTStartup@12");
  8364. break;
  8365. }
  8366. CmdArgs.push_back("-shared");
  8367. CmdArgs.push_back("-Bdynamic");
  8368. CmdArgs.push_back("--enable-auto-image-base");
  8369. CmdArgs.push_back("--entry");
  8370. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  8371. } else {
  8372. EntryPoint.append("mainCRTStartup");
  8373. CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
  8374. : "-Bdynamic");
  8375. if (!Args.hasArg(options::OPT_nostdlib) &&
  8376. !Args.hasArg(options::OPT_nostartfiles)) {
  8377. CmdArgs.push_back("--entry");
  8378. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  8379. }
  8380. // FIXME: handle subsystem
  8381. }
  8382. // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
  8383. CmdArgs.push_back("--allow-multiple-definition");
  8384. CmdArgs.push_back("-o");
  8385. CmdArgs.push_back(Output.getFilename());
  8386. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
  8387. SmallString<261> ImpLib(Output.getFilename());
  8388. llvm::sys::path::replace_extension(ImpLib, ".lib");
  8389. CmdArgs.push_back("--out-implib");
  8390. CmdArgs.push_back(Args.MakeArgString(ImpLib));
  8391. }
  8392. if (!Args.hasArg(options::OPT_nostdlib) &&
  8393. !Args.hasArg(options::OPT_nostartfiles)) {
  8394. const std::string CRTPath(D.SysRoot + "/usr/lib/");
  8395. const char *CRTBegin;
  8396. CRTBegin =
  8397. Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
  8398. CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
  8399. }
  8400. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8401. const auto &Paths = TC.getFilePaths();
  8402. for (const auto &Path : Paths)
  8403. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
  8404. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  8405. if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
  8406. !Args.hasArg(options::OPT_nodefaultlibs)) {
  8407. bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
  8408. !Args.hasArg(options::OPT_static);
  8409. if (StaticCXX)
  8410. CmdArgs.push_back("-Bstatic");
  8411. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  8412. if (StaticCXX)
  8413. CmdArgs.push_back("-Bdynamic");
  8414. }
  8415. if (!Args.hasArg(options::OPT_nostdlib)) {
  8416. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8417. // TODO handle /MT[d] /MD[d]
  8418. CmdArgs.push_back("-lmsvcrt");
  8419. AddRunTimeLibs(TC, D, CmdArgs, Args);
  8420. }
  8421. }
  8422. const std::string Linker = TC.GetProgramPath("ld");
  8423. Exec = Args.MakeArgString(Linker);
  8424. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8425. }
  8426. void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  8427. const InputInfo &Output,
  8428. const InputInfoList &Inputs,
  8429. const ArgList &Args,
  8430. const char *LinkingOutput) const {
  8431. ArgStringList CmdArgs;
  8432. assert(Inputs.size() == 1);
  8433. const InputInfo &II = Inputs[0];
  8434. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
  8435. assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
  8436. CmdArgs.push_back("-DMYRIAD2");
  8437. CmdArgs.push_back("-mcpu=myriad2");
  8438. CmdArgs.push_back("-S");
  8439. // Append all -I, -iquote, -isystem paths, defines/undefines,
  8440. // 'f' flags, optimize flags, and warning options.
  8441. // These are spelled the same way in clang and moviCompile.
  8442. Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
  8443. options::OPT_D, options::OPT_U,
  8444. options::OPT_f_Group, options::OPT_f_clang_Group,
  8445. options::OPT_g_Group, options::OPT_M_Group,
  8446. options::OPT_O_Group, options::OPT_W_Group});
  8447. // If we're producing a dependency file, and assembly is the final action,
  8448. // then the name of the target in the dependency file should be the '.o'
  8449. // file, not the '.s' file produced by this step. For example, instead of
  8450. // /tmp/mumble.s: mumble.c .../someheader.h
  8451. // the filename on the lefthand side should be "mumble.o"
  8452. if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
  8453. C.getActions().size() == 1 &&
  8454. C.getActions()[0]->getKind() == Action::AssembleJobClass) {
  8455. Arg *A = Args.getLastArg(options::OPT_o);
  8456. if (A) {
  8457. CmdArgs.push_back("-MT");
  8458. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  8459. }
  8460. }
  8461. CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
  8462. CmdArgs.push_back(II.getFilename());
  8463. CmdArgs.push_back("-o");
  8464. CmdArgs.push_back(Output.getFilename());
  8465. std::string Exec =
  8466. Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
  8467. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8468. CmdArgs, Inputs));
  8469. }
  8470. void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8471. const InputInfo &Output,
  8472. const InputInfoList &Inputs,
  8473. const ArgList &Args,
  8474. const char *LinkingOutput) const {
  8475. ArgStringList CmdArgs;
  8476. assert(Inputs.size() == 1);
  8477. const InputInfo &II = Inputs[0];
  8478. assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
  8479. assert(Output.getType() == types::TY_Object);
  8480. CmdArgs.push_back("-no6thSlotCompression");
  8481. CmdArgs.push_back("-cv:myriad2"); // Chip Version
  8482. CmdArgs.push_back("-noSPrefixing");
  8483. CmdArgs.push_back("-a"); // Mystery option.
  8484. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8485. for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
  8486. A->claim();
  8487. CmdArgs.push_back(
  8488. Args.MakeArgString(std::string("-i:") + A->getValue(0)));
  8489. }
  8490. CmdArgs.push_back("-elf"); // Output format.
  8491. CmdArgs.push_back(II.getFilename());
  8492. CmdArgs.push_back(
  8493. Args.MakeArgString(std::string("-o:") + Output.getFilename()));
  8494. std::string Exec =
  8495. Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
  8496. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8497. CmdArgs, Inputs));
  8498. }
  8499. void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8500. const InputInfo &Output,
  8501. const InputInfoList &Inputs,
  8502. const ArgList &Args,
  8503. const char *LinkingOutput) const {
  8504. const auto &TC =
  8505. static_cast<const toolchains::MyriadToolChain &>(getToolChain());
  8506. const llvm::Triple &T = TC.getTriple();
  8507. ArgStringList CmdArgs;
  8508. bool UseStartfiles = !Args.hasArg(options::OPT_nostartfiles);
  8509. bool UseDefaultLibs = !Args.hasArg(options::OPT_nostdlib) &&
  8510. !Args.hasArg(options::OPT_nodefaultlibs);
  8511. std::string StartFilesDir, BuiltinLibDir;
  8512. TC.getCompilerSupportDir(StartFilesDir);
  8513. TC.getBuiltinLibDir(BuiltinLibDir);
  8514. if (T.getArch() == llvm::Triple::sparc)
  8515. CmdArgs.push_back("-EB");
  8516. else // SHAVE assumes little-endian, and sparcel is expressly so.
  8517. CmdArgs.push_back("-EL");
  8518. // The remaining logic is mostly like gnutools::Linker::ConstructJob,
  8519. // but we never pass through a --sysroot option and various other bits.
  8520. // For example, there are no sanitizers (yet) nor gold linker.
  8521. // Eat some arguments that may be present but have no effect.
  8522. Args.ClaimAllArgs(options::OPT_g_Group);
  8523. Args.ClaimAllArgs(options::OPT_w);
  8524. Args.ClaimAllArgs(options::OPT_static_libgcc);
  8525. if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
  8526. CmdArgs.push_back("-s");
  8527. CmdArgs.push_back("-o");
  8528. CmdArgs.push_back(Output.getFilename());
  8529. if (UseStartfiles) {
  8530. // If you want startfiles, it means you want the builtin crti and crtbegin,
  8531. // but not crt0. Myriad link commands provide their own crt0.o as needed.
  8532. CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crti.o"));
  8533. CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crtbegin.o"));
  8534. }
  8535. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  8536. options::OPT_e, options::OPT_s, options::OPT_t,
  8537. options::OPT_Z_Flag, options::OPT_r});
  8538. if (UseDefaultLibs) {
  8539. // The linker doesn't use these builtin paths unless directed to,
  8540. // because it was not compiled for support with sysroots, nor does
  8541. // it have a default of little-endian with FPU.
  8542. CmdArgs.push_back(Args.MakeArgString("-L" + BuiltinLibDir));
  8543. CmdArgs.push_back(Args.MakeArgString("-L" + StartFilesDir));
  8544. }
  8545. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8546. if (UseDefaultLibs) {
  8547. if (C.getDriver().CCCIsCXX())
  8548. CmdArgs.push_back("-lstdc++");
  8549. if (T.getOS() == llvm::Triple::RTEMS) {
  8550. CmdArgs.push_back("--start-group");
  8551. CmdArgs.push_back("-lc");
  8552. // You must provide your own "-L" option to enable finding these.
  8553. CmdArgs.push_back("-lrtemscpu");
  8554. CmdArgs.push_back("-lrtemsbsp");
  8555. CmdArgs.push_back("--end-group");
  8556. } else {
  8557. CmdArgs.push_back("-lc");
  8558. }
  8559. CmdArgs.push_back("-lgcc");
  8560. }
  8561. if (UseStartfiles) {
  8562. CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crtend.o"));
  8563. CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crtn.o"));
  8564. }
  8565. std::string Exec =
  8566. Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
  8567. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8568. CmdArgs, Inputs));
  8569. }