Tools.cpp 375 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354
  1. //===--- Tools.cpp - Tools Implementations ----------------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "Tools.h"
  10. #include "InputInfo.h"
  11. #include "ToolChains.h"
  12. #include "clang/Basic/CharInfo.h"
  13. #include "clang/Basic/LangOptions.h"
  14. #include "clang/Basic/ObjCRuntime.h"
  15. #include "clang/Basic/Version.h"
  16. #include "clang/Config/config.h"
  17. #include "clang/Driver/Action.h"
  18. #include "clang/Driver/Compilation.h"
  19. #include "clang/Driver/Driver.h"
  20. #include "clang/Driver/DriverDiagnostic.h"
  21. #include "clang/Driver/Job.h"
  22. #include "clang/Driver/Options.h"
  23. #include "clang/Driver/SanitizerArgs.h"
  24. #include "clang/Driver/ToolChain.h"
  25. #include "clang/Driver/Util.h"
  26. #include "llvm/ADT/STLExtras.h"
  27. #include "llvm/ADT/SmallString.h"
  28. #include "llvm/ADT/StringExtras.h"
  29. #include "llvm/ADT/StringSwitch.h"
  30. #include "llvm/ADT/Twine.h"
  31. #include "llvm/Option/Arg.h"
  32. #include "llvm/Option/ArgList.h"
  33. #include "llvm/Option/Option.h"
  34. #include "llvm/Support/CodeGen.h"
  35. #include "llvm/Support/Compression.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/FileSystem.h"
  38. #include "llvm/Support/Host.h"
  39. #include "llvm/Support/Path.h"
  40. #include "llvm/Support/Process.h"
  41. #include "llvm/Support/Program.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include "llvm/Support/TargetParser.h"
  44. #ifdef LLVM_ON_UNIX
  45. #include <unistd.h> // For getuid().
  46. #endif
  47. using namespace clang::driver;
  48. using namespace clang::driver::tools;
  49. using namespace clang;
  50. using namespace llvm::opt;
  51. static const char *getSparcAsmModeForCPU(StringRef Name,
  52. const llvm::Triple &Triple) {
  53. if (Triple.getArch() == llvm::Triple::sparcv9) {
  54. return llvm::StringSwitch<const char *>(Name)
  55. .Case("niagara", "-Av9b")
  56. .Case("niagara2", "-Av9b")
  57. .Case("niagara3", "-Av9d")
  58. .Case("niagara4", "-Av9d")
  59. .Default("-Av9");
  60. } else {
  61. return llvm::StringSwitch<const char *>(Name)
  62. .Case("v8", "-Av8")
  63. .Case("supersparc", "-Av8")
  64. .Case("sparclite", "-Asparclite")
  65. .Case("f934", "-Asparclite")
  66. .Case("hypersparc", "-Av8")
  67. .Case("sparclite86x", "-Asparclite")
  68. .Case("sparclet", "-Asparclet")
  69. .Case("tsc701", "-Asparclet")
  70. .Case("v9", "-Av8plus")
  71. .Case("ultrasparc", "-Av8plus")
  72. .Case("ultrasparc3", "-Av8plus")
  73. .Case("niagara", "-Av8plusb")
  74. .Case("niagara2", "-Av8plusb")
  75. .Case("niagara3", "-Av8plusd")
  76. .Case("niagara4", "-Av8plusd")
  77. .Default("-Av8");
  78. }
  79. }
  80. /// CheckPreprocessingOptions - Perform some validation of preprocessing
  81. /// arguments that is shared with gcc.
  82. static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
  83. if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
  84. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
  85. !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
  86. D.Diag(diag::err_drv_argument_only_allowed_with)
  87. << A->getBaseArg().getAsString(Args)
  88. << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
  89. }
  90. }
  91. }
  92. /// CheckCodeGenerationOptions - Perform some validation of code generation
  93. /// arguments that is shared with gcc.
  94. static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
  95. // In gcc, only ARM checks this, but it seems reasonable to check universally.
  96. if (Args.hasArg(options::OPT_static))
  97. if (const Arg *A =
  98. Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
  99. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  100. << "-static";
  101. }
  102. // Add backslashes to escape spaces and other backslashes.
  103. // This is used for the space-separated argument list specified with
  104. // the -dwarf-debug-flags option.
  105. static void EscapeSpacesAndBackslashes(const char *Arg,
  106. SmallVectorImpl<char> &Res) {
  107. for (; *Arg; ++Arg) {
  108. switch (*Arg) {
  109. default:
  110. break;
  111. case ' ':
  112. case '\\':
  113. Res.push_back('\\');
  114. break;
  115. }
  116. Res.push_back(*Arg);
  117. }
  118. }
  119. // Quote target names for inclusion in GNU Make dependency files.
  120. // Only the characters '$', '#', ' ', '\t' are quoted.
  121. static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
  122. for (unsigned i = 0, e = Target.size(); i != e; ++i) {
  123. switch (Target[i]) {
  124. case ' ':
  125. case '\t':
  126. // Escape the preceding backslashes
  127. for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
  128. Res.push_back('\\');
  129. // Escape the space/tab
  130. Res.push_back('\\');
  131. break;
  132. case '$':
  133. Res.push_back('$');
  134. break;
  135. case '#':
  136. Res.push_back('\\');
  137. break;
  138. default:
  139. break;
  140. }
  141. Res.push_back(Target[i]);
  142. }
  143. }
  144. static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
  145. const char *ArgName, const char *EnvVar) {
  146. const char *DirList = ::getenv(EnvVar);
  147. bool CombinedArg = false;
  148. if (!DirList)
  149. return; // Nothing to do.
  150. StringRef Name(ArgName);
  151. if (Name.equals("-I") || Name.equals("-L"))
  152. CombinedArg = true;
  153. StringRef Dirs(DirList);
  154. if (Dirs.empty()) // Empty string should not add '.'.
  155. return;
  156. StringRef::size_type Delim;
  157. while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
  158. if (Delim == 0) { // Leading colon.
  159. if (CombinedArg) {
  160. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  161. } else {
  162. CmdArgs.push_back(ArgName);
  163. CmdArgs.push_back(".");
  164. }
  165. } else {
  166. if (CombinedArg) {
  167. CmdArgs.push_back(
  168. Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
  169. } else {
  170. CmdArgs.push_back(ArgName);
  171. CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
  172. }
  173. }
  174. Dirs = Dirs.substr(Delim + 1);
  175. }
  176. if (Dirs.empty()) { // Trailing colon.
  177. if (CombinedArg) {
  178. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  179. } else {
  180. CmdArgs.push_back(ArgName);
  181. CmdArgs.push_back(".");
  182. }
  183. } else { // Add the last path.
  184. if (CombinedArg) {
  185. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
  186. } else {
  187. CmdArgs.push_back(ArgName);
  188. CmdArgs.push_back(Args.MakeArgString(Dirs));
  189. }
  190. }
  191. }
  192. static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
  193. const ArgList &Args, ArgStringList &CmdArgs) {
  194. const Driver &D = TC.getDriver();
  195. // Add extra linker input arguments which are not treated as inputs
  196. // (constructed via -Xarch_).
  197. Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
  198. for (const auto &II : Inputs) {
  199. if (!TC.HasNativeLLVMSupport()) {
  200. // Don't try to pass LLVM inputs unless we have native support.
  201. if (II.getType() == types::TY_LLVM_IR ||
  202. II.getType() == types::TY_LTO_IR ||
  203. II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
  204. D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
  205. }
  206. // Add filenames immediately.
  207. if (II.isFilename()) {
  208. CmdArgs.push_back(II.getFilename());
  209. continue;
  210. }
  211. // Otherwise, this is a linker input argument.
  212. const Arg &A = II.getInputArg();
  213. // Handle reserved library options.
  214. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
  215. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  216. else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
  217. TC.AddCCKextLibArgs(Args, CmdArgs);
  218. else if (A.getOption().matches(options::OPT_z)) {
  219. // Pass -z prefix for gcc linker compatibility.
  220. A.claim();
  221. A.render(Args, CmdArgs);
  222. } else {
  223. A.renderAsInput(Args, CmdArgs);
  224. }
  225. }
  226. // LIBRARY_PATH - included following the user specified library paths.
  227. // and only supported on native toolchains.
  228. if (!TC.isCrossCompiling())
  229. addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
  230. }
  231. /// \brief Determine whether Objective-C automated reference counting is
  232. /// enabled.
  233. static bool isObjCAutoRefCount(const ArgList &Args) {
  234. return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
  235. }
  236. /// \brief Determine whether we are linking the ObjC runtime.
  237. static bool isObjCRuntimeLinked(const ArgList &Args) {
  238. if (isObjCAutoRefCount(Args)) {
  239. Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
  240. return true;
  241. }
  242. return Args.hasArg(options::OPT_fobjc_link_runtime);
  243. }
  244. static bool forwardToGCC(const Option &O) {
  245. // Don't forward inputs from the original command line. They are added from
  246. // InputInfoList.
  247. return O.getKind() != Option::InputClass &&
  248. !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
  249. }
  250. void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
  251. const Driver &D, const ArgList &Args,
  252. ArgStringList &CmdArgs,
  253. const InputInfo &Output,
  254. const InputInfoList &Inputs,
  255. const ToolChain *AuxToolChain) const {
  256. Arg *A;
  257. CheckPreprocessingOptions(D, Args);
  258. Args.AddLastArg(CmdArgs, options::OPT_C);
  259. Args.AddLastArg(CmdArgs, options::OPT_CC);
  260. // Handle dependency file generation.
  261. if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
  262. (A = Args.getLastArg(options::OPT_MD)) ||
  263. (A = Args.getLastArg(options::OPT_MMD))) {
  264. // Determine the output location.
  265. const char *DepFile;
  266. if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
  267. DepFile = MF->getValue();
  268. C.addFailureResultFile(DepFile, &JA);
  269. } else if (Output.getType() == types::TY_Dependencies) {
  270. DepFile = Output.getFilename();
  271. } else if (A->getOption().matches(options::OPT_M) ||
  272. A->getOption().matches(options::OPT_MM)) {
  273. DepFile = "-";
  274. } else {
  275. DepFile = getDependencyFileName(Args, Inputs);
  276. C.addFailureResultFile(DepFile, &JA);
  277. }
  278. CmdArgs.push_back("-dependency-file");
  279. CmdArgs.push_back(DepFile);
  280. // Add a default target if one wasn't specified.
  281. if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
  282. const char *DepTarget;
  283. // If user provided -o, that is the dependency target, except
  284. // when we are only generating a dependency file.
  285. Arg *OutputOpt = Args.getLastArg(options::OPT_o);
  286. if (OutputOpt && Output.getType() != types::TY_Dependencies) {
  287. DepTarget = OutputOpt->getValue();
  288. } else {
  289. // Otherwise derive from the base input.
  290. //
  291. // FIXME: This should use the computed output file location.
  292. SmallString<128> P(Inputs[0].getBaseInput());
  293. llvm::sys::path::replace_extension(P, "o");
  294. DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
  295. }
  296. CmdArgs.push_back("-MT");
  297. SmallString<128> Quoted;
  298. QuoteTarget(DepTarget, Quoted);
  299. CmdArgs.push_back(Args.MakeArgString(Quoted));
  300. }
  301. if (A->getOption().matches(options::OPT_M) ||
  302. A->getOption().matches(options::OPT_MD))
  303. CmdArgs.push_back("-sys-header-deps");
  304. if ((isa<PrecompileJobAction>(JA) &&
  305. !Args.hasArg(options::OPT_fno_module_file_deps)) ||
  306. Args.hasArg(options::OPT_fmodule_file_deps))
  307. CmdArgs.push_back("-module-file-deps");
  308. }
  309. if (Args.hasArg(options::OPT_MG)) {
  310. if (!A || A->getOption().matches(options::OPT_MD) ||
  311. A->getOption().matches(options::OPT_MMD))
  312. D.Diag(diag::err_drv_mg_requires_m_or_mm);
  313. CmdArgs.push_back("-MG");
  314. }
  315. Args.AddLastArg(CmdArgs, options::OPT_MP);
  316. Args.AddLastArg(CmdArgs, options::OPT_MV);
  317. // Convert all -MQ <target> args to -MT <quoted target>
  318. for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
  319. A->claim();
  320. if (A->getOption().matches(options::OPT_MQ)) {
  321. CmdArgs.push_back("-MT");
  322. SmallString<128> Quoted;
  323. QuoteTarget(A->getValue(), Quoted);
  324. CmdArgs.push_back(Args.MakeArgString(Quoted));
  325. // -MT flag - no change
  326. } else {
  327. A->render(Args, CmdArgs);
  328. }
  329. }
  330. // Add -i* options, and automatically translate to
  331. // -include-pch/-include-pth for transparent PCH support. It's
  332. // wonky, but we include looking for .gch so we can support seamless
  333. // replacement into a build system already set up to be generating
  334. // .gch files.
  335. bool RenderedImplicitInclude = false;
  336. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  337. if (A->getOption().matches(options::OPT_include)) {
  338. bool IsFirstImplicitInclude = !RenderedImplicitInclude;
  339. RenderedImplicitInclude = true;
  340. // Use PCH if the user requested it.
  341. bool UsePCH = D.CCCUsePCH;
  342. bool FoundPTH = false;
  343. bool FoundPCH = false;
  344. SmallString<128> P(A->getValue());
  345. // We want the files to have a name like foo.h.pch. Add a dummy extension
  346. // so that replace_extension does the right thing.
  347. P += ".dummy";
  348. if (UsePCH) {
  349. llvm::sys::path::replace_extension(P, "pch");
  350. if (llvm::sys::fs::exists(P))
  351. FoundPCH = true;
  352. }
  353. if (!FoundPCH) {
  354. llvm::sys::path::replace_extension(P, "pth");
  355. if (llvm::sys::fs::exists(P))
  356. FoundPTH = true;
  357. }
  358. if (!FoundPCH && !FoundPTH) {
  359. llvm::sys::path::replace_extension(P, "gch");
  360. if (llvm::sys::fs::exists(P)) {
  361. FoundPCH = UsePCH;
  362. FoundPTH = !UsePCH;
  363. }
  364. }
  365. if (FoundPCH || FoundPTH) {
  366. if (IsFirstImplicitInclude) {
  367. A->claim();
  368. if (UsePCH)
  369. CmdArgs.push_back("-include-pch");
  370. else
  371. CmdArgs.push_back("-include-pth");
  372. CmdArgs.push_back(Args.MakeArgString(P));
  373. continue;
  374. } else {
  375. // Ignore the PCH if not first on command line and emit warning.
  376. D.Diag(diag::warn_drv_pch_not_first_include) << P
  377. << A->getAsString(Args);
  378. }
  379. }
  380. }
  381. // Not translated, render as usual.
  382. A->claim();
  383. A->render(Args, CmdArgs);
  384. }
  385. Args.AddAllArgs(CmdArgs,
  386. {options::OPT_D, options::OPT_U, options::OPT_I_Group,
  387. options::OPT_F, options::OPT_index_header_map});
  388. // Add -Wp, and -Xpreprocessor if using the preprocessor.
  389. // FIXME: There is a very unfortunate problem here, some troubled
  390. // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
  391. // really support that we would have to parse and then translate
  392. // those options. :(
  393. Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
  394. options::OPT_Xpreprocessor);
  395. // -I- is a deprecated GCC feature, reject it.
  396. if (Arg *A = Args.getLastArg(options::OPT_I_))
  397. D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
  398. // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
  399. // -isysroot to the CC1 invocation.
  400. StringRef sysroot = C.getSysRoot();
  401. if (sysroot != "") {
  402. if (!Args.hasArg(options::OPT_isysroot)) {
  403. CmdArgs.push_back("-isysroot");
  404. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  405. }
  406. }
  407. // Parse additional include paths from environment variables.
  408. // FIXME: We should probably sink the logic for handling these from the
  409. // frontend into the driver. It will allow deleting 4 otherwise unused flags.
  410. // CPATH - included following the user specified includes (but prior to
  411. // builtin and standard includes).
  412. addDirectoryList(Args, CmdArgs, "-I", "CPATH");
  413. // C_INCLUDE_PATH - system includes enabled when compiling C.
  414. addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
  415. // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
  416. addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
  417. // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
  418. addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
  419. // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
  420. addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
  421. // Optional AuxToolChain indicates that we need to include headers
  422. // for more than one target. If that's the case, add include paths
  423. // from AuxToolChain right after include paths of the same kind for
  424. // the current target.
  425. // Add C++ include arguments, if needed.
  426. if (types::isCXX(Inputs[0].getType())) {
  427. getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  428. if (AuxToolChain)
  429. AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  430. }
  431. // Add system include arguments.
  432. getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
  433. if (AuxToolChain)
  434. AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  435. // Add CUDA include arguments, if needed.
  436. if (types::isCuda(Inputs[0].getType()))
  437. getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
  438. }
  439. // FIXME: Move to target hook.
  440. static bool isSignedCharDefault(const llvm::Triple &Triple) {
  441. switch (Triple.getArch()) {
  442. default:
  443. return true;
  444. case llvm::Triple::aarch64:
  445. case llvm::Triple::aarch64_be:
  446. case llvm::Triple::arm:
  447. case llvm::Triple::armeb:
  448. case llvm::Triple::thumb:
  449. case llvm::Triple::thumbeb:
  450. if (Triple.isOSDarwin() || Triple.isOSWindows())
  451. return true;
  452. return false;
  453. case llvm::Triple::ppc:
  454. case llvm::Triple::ppc64:
  455. if (Triple.isOSDarwin())
  456. return true;
  457. return false;
  458. case llvm::Triple::hexagon:
  459. case llvm::Triple::ppc64le:
  460. case llvm::Triple::systemz:
  461. case llvm::Triple::xcore:
  462. return false;
  463. }
  464. }
  465. static bool isNoCommonDefault(const llvm::Triple &Triple) {
  466. switch (Triple.getArch()) {
  467. default:
  468. return false;
  469. case llvm::Triple::xcore:
  470. case llvm::Triple::wasm32:
  471. case llvm::Triple::wasm64:
  472. return true;
  473. }
  474. }
  475. // ARM tools start.
  476. // Get SubArch (vN).
  477. static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
  478. llvm::StringRef Arch = Triple.getArchName();
  479. return llvm::ARM::parseArchVersion(Arch);
  480. }
  481. // True if M-profile.
  482. static bool isARMMProfile(const llvm::Triple &Triple) {
  483. llvm::StringRef Arch = Triple.getArchName();
  484. unsigned Profile = llvm::ARM::parseArchProfile(Arch);
  485. return Profile == llvm::ARM::PK_M;
  486. }
  487. // Get Arch/CPU from args.
  488. static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
  489. llvm::StringRef &CPU, bool FromAs = false) {
  490. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  491. CPU = A->getValue();
  492. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  493. Arch = A->getValue();
  494. if (!FromAs)
  495. return;
  496. for (const Arg *A :
  497. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  498. StringRef Value = A->getValue();
  499. if (Value.startswith("-mcpu="))
  500. CPU = Value.substr(6);
  501. if (Value.startswith("-march="))
  502. Arch = Value.substr(7);
  503. }
  504. }
  505. // Handle -mhwdiv=.
  506. // FIXME: Use ARMTargetParser.
  507. static void getARMHWDivFeatures(const Driver &D, const Arg *A,
  508. const ArgList &Args, StringRef HWDiv,
  509. std::vector<const char *> &Features) {
  510. unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
  511. if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
  512. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  513. }
  514. // Handle -mfpu=.
  515. static void getARMFPUFeatures(const Driver &D, const Arg *A,
  516. const ArgList &Args, StringRef FPU,
  517. std::vector<const char *> &Features) {
  518. unsigned FPUID = llvm::ARM::parseFPU(FPU);
  519. if (!llvm::ARM::getFPUFeatures(FPUID, Features))
  520. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  521. }
  522. // Decode ARM features from string like +[no]featureA+[no]featureB+...
  523. static bool DecodeARMFeatures(const Driver &D, StringRef text,
  524. std::vector<const char *> &Features) {
  525. SmallVector<StringRef, 8> Split;
  526. text.split(Split, StringRef("+"), -1, false);
  527. for (StringRef Feature : Split) {
  528. const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
  529. if (FeatureName)
  530. Features.push_back(FeatureName);
  531. else
  532. return false;
  533. }
  534. return true;
  535. }
  536. // Check if -march is valid by checking if it can be canonicalised and parsed.
  537. // getARMArch is used here instead of just checking the -march value in order
  538. // to handle -march=native correctly.
  539. static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
  540. llvm::StringRef ArchName,
  541. std::vector<const char *> &Features,
  542. const llvm::Triple &Triple) {
  543. std::pair<StringRef, StringRef> Split = ArchName.split("+");
  544. std::string MArch = arm::getARMArch(ArchName, Triple);
  545. if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
  546. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  547. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  548. }
  549. // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
  550. static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
  551. llvm::StringRef CPUName, llvm::StringRef ArchName,
  552. std::vector<const char *> &Features,
  553. const llvm::Triple &Triple) {
  554. std::pair<StringRef, StringRef> Split = CPUName.split("+");
  555. std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
  556. if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
  557. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  558. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  559. }
  560. static bool useAAPCSForMachO(const llvm::Triple &T) {
  561. // The backend is hardwired to assume AAPCS for M-class processors, ensure
  562. // the frontend matches that.
  563. return T.getEnvironment() == llvm::Triple::EABI ||
  564. T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
  565. }
  566. // Select the float ABI as determined by -msoft-float, -mhard-float, and
  567. // -mfloat-abi=.
  568. arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
  569. const Driver &D = TC.getDriver();
  570. const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
  571. auto SubArch = getARMSubArchVersionNumber(Triple);
  572. arm::FloatABI ABI = FloatABI::Invalid;
  573. if (Arg *A =
  574. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  575. options::OPT_mfloat_abi_EQ)) {
  576. if (A->getOption().matches(options::OPT_msoft_float)) {
  577. ABI = FloatABI::Soft;
  578. } else if (A->getOption().matches(options::OPT_mhard_float)) {
  579. ABI = FloatABI::Hard;
  580. } else {
  581. ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
  582. .Case("soft", FloatABI::Soft)
  583. .Case("softfp", FloatABI::SoftFP)
  584. .Case("hard", FloatABI::Hard)
  585. .Default(FloatABI::Invalid);
  586. if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  587. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  588. ABI = FloatABI::Soft;
  589. }
  590. }
  591. // It is incorrect to select hard float ABI on MachO platforms if the ABI is
  592. // "apcs-gnu".
  593. if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
  594. ABI == FloatABI::Hard) {
  595. D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
  596. << Triple.getArchName();
  597. }
  598. }
  599. // If unspecified, choose the default based on the platform.
  600. if (ABI == FloatABI::Invalid) {
  601. switch (Triple.getOS()) {
  602. case llvm::Triple::Darwin:
  603. case llvm::Triple::MacOSX:
  604. case llvm::Triple::IOS:
  605. case llvm::Triple::TvOS: {
  606. // Darwin defaults to "softfp" for v6 and v7.
  607. ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  608. break;
  609. }
  610. case llvm::Triple::WatchOS:
  611. ABI = FloatABI::Hard;
  612. break;
  613. // FIXME: this is invalid for WindowsCE
  614. case llvm::Triple::Win32:
  615. ABI = FloatABI::Hard;
  616. break;
  617. case llvm::Triple::FreeBSD:
  618. switch (Triple.getEnvironment()) {
  619. case llvm::Triple::GNUEABIHF:
  620. ABI = FloatABI::Hard;
  621. break;
  622. default:
  623. // FreeBSD defaults to soft float
  624. ABI = FloatABI::Soft;
  625. break;
  626. }
  627. break;
  628. default:
  629. switch (Triple.getEnvironment()) {
  630. case llvm::Triple::GNUEABIHF:
  631. case llvm::Triple::EABIHF:
  632. ABI = FloatABI::Hard;
  633. break;
  634. case llvm::Triple::GNUEABI:
  635. case llvm::Triple::EABI:
  636. // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
  637. ABI = FloatABI::SoftFP;
  638. break;
  639. case llvm::Triple::Android:
  640. ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  641. break;
  642. default:
  643. // Assume "soft", but warn the user we are guessing.
  644. ABI = FloatABI::Soft;
  645. if (Triple.getOS() != llvm::Triple::UnknownOS ||
  646. !Triple.isOSBinFormatMachO())
  647. D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
  648. break;
  649. }
  650. }
  651. }
  652. assert(ABI != FloatABI::Invalid && "must select an ABI");
  653. return ABI;
  654. }
  655. static void getARMTargetFeatures(const ToolChain &TC,
  656. const llvm::Triple &Triple,
  657. const ArgList &Args,
  658. std::vector<const char *> &Features,
  659. bool ForAS) {
  660. const Driver &D = TC.getDriver();
  661. bool KernelOrKext =
  662. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  663. arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
  664. const Arg *WaCPU = nullptr, *WaFPU = nullptr;
  665. const Arg *WaHDiv = nullptr, *WaArch = nullptr;
  666. if (!ForAS) {
  667. // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
  668. // yet (it uses the -mfloat-abi and -msoft-float options), and it is
  669. // stripped out by the ARM target. We should probably pass this a new
  670. // -target-option, which is handled by the -cc1/-cc1as invocation.
  671. //
  672. // FIXME2: For consistency, it would be ideal if we set up the target
  673. // machine state the same when using the frontend or the assembler. We don't
  674. // currently do that for the assembler, we pass the options directly to the
  675. // backend and never even instantiate the frontend TargetInfo. If we did,
  676. // and used its handleTargetFeatures hook, then we could ensure the
  677. // assembler and the frontend behave the same.
  678. // Use software floating point operations?
  679. if (ABI == arm::FloatABI::Soft)
  680. Features.push_back("+soft-float");
  681. // Use software floating point argument passing?
  682. if (ABI != arm::FloatABI::Hard)
  683. Features.push_back("+soft-float-abi");
  684. } else {
  685. // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
  686. // to the assembler correctly.
  687. for (const Arg *A :
  688. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  689. StringRef Value = A->getValue();
  690. if (Value.startswith("-mfpu=")) {
  691. WaFPU = A;
  692. } else if (Value.startswith("-mcpu=")) {
  693. WaCPU = A;
  694. } else if (Value.startswith("-mhwdiv=")) {
  695. WaHDiv = A;
  696. } else if (Value.startswith("-march=")) {
  697. WaArch = A;
  698. }
  699. }
  700. }
  701. // Check -march. ClangAs gives preference to -Wa,-march=.
  702. const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
  703. StringRef ArchName;
  704. if (WaArch) {
  705. if (ArchArg)
  706. D.Diag(clang::diag::warn_drv_unused_argument)
  707. << ArchArg->getAsString(Args);
  708. ArchName = StringRef(WaArch->getValue()).substr(7);
  709. checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
  710. // FIXME: Set Arch.
  711. D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
  712. } else if (ArchArg) {
  713. ArchName = ArchArg->getValue();
  714. checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
  715. }
  716. // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
  717. const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  718. StringRef CPUName;
  719. if (WaCPU) {
  720. if (CPUArg)
  721. D.Diag(clang::diag::warn_drv_unused_argument)
  722. << CPUArg->getAsString(Args);
  723. CPUName = StringRef(WaCPU->getValue()).substr(6);
  724. checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
  725. } else if (CPUArg) {
  726. CPUName = CPUArg->getValue();
  727. checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
  728. }
  729. // Add CPU features for generic CPUs
  730. if (CPUName == "native") {
  731. llvm::StringMap<bool> HostFeatures;
  732. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  733. for (auto &F : HostFeatures)
  734. Features.push_back(
  735. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  736. }
  737. // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
  738. const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
  739. if (WaFPU) {
  740. if (FPUArg)
  741. D.Diag(clang::diag::warn_drv_unused_argument)
  742. << FPUArg->getAsString(Args);
  743. getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
  744. Features);
  745. } else if (FPUArg) {
  746. getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
  747. }
  748. // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
  749. const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
  750. if (WaHDiv) {
  751. if (HDivArg)
  752. D.Diag(clang::diag::warn_drv_unused_argument)
  753. << HDivArg->getAsString(Args);
  754. getARMHWDivFeatures(D, WaHDiv, Args,
  755. StringRef(WaHDiv->getValue()).substr(8), Features);
  756. } else if (HDivArg)
  757. getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
  758. // Setting -msoft-float effectively disables NEON because of the GCC
  759. // implementation, although the same isn't true of VFP or VFP3.
  760. if (ABI == arm::FloatABI::Soft) {
  761. Features.push_back("-neon");
  762. // Also need to explicitly disable features which imply NEON.
  763. Features.push_back("-crypto");
  764. }
  765. // En/disable crc code generation.
  766. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  767. if (A->getOption().matches(options::OPT_mcrc))
  768. Features.push_back("+crc");
  769. else
  770. Features.push_back("-crc");
  771. }
  772. if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
  773. Features.insert(Features.begin(), "+v8.1a");
  774. }
  775. // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
  776. // neither options are specified, see if we are compiling for kernel/kext and
  777. // decide whether to pass "+long-calls" based on the OS and its version.
  778. if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
  779. options::OPT_mno_long_calls)) {
  780. if (A->getOption().matches(options::OPT_mlong_calls))
  781. Features.push_back("+long-calls");
  782. } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  783. !Triple.isWatchOS()) {
  784. Features.push_back("+long-calls");
  785. }
  786. // Kernel code has more strict alignment requirements.
  787. if (KernelOrKext)
  788. Features.push_back("+strict-align");
  789. else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  790. options::OPT_munaligned_access)) {
  791. if (A->getOption().matches(options::OPT_munaligned_access)) {
  792. // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
  793. if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  794. D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
  795. } else
  796. Features.push_back("+strict-align");
  797. } else {
  798. // Assume pre-ARMv6 doesn't support unaligned accesses.
  799. //
  800. // ARMv6 may or may not support unaligned accesses depending on the
  801. // SCTLR.U bit, which is architecture-specific. We assume ARMv6
  802. // Darwin and NetBSD targets support unaligned accesses, and others don't.
  803. //
  804. // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
  805. // which raises an alignment fault on unaligned accesses. Linux
  806. // defaults this bit to 0 and handles it as a system-wide (not
  807. // per-process) setting. It is therefore safe to assume that ARMv7+
  808. // Linux targets support unaligned accesses. The same goes for NaCl.
  809. //
  810. // The above behavior is consistent with GCC.
  811. int VersionNum = getARMSubArchVersionNumber(Triple);
  812. if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
  813. if (VersionNum < 6 ||
  814. Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  815. Features.push_back("+strict-align");
  816. } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
  817. if (VersionNum < 7)
  818. Features.push_back("+strict-align");
  819. } else
  820. Features.push_back("+strict-align");
  821. }
  822. // llvm does not support reserving registers in general. There is support
  823. // for reserving r9 on ARM though (defined as a platform-specific register
  824. // in ARM EABI).
  825. if (Args.hasArg(options::OPT_ffixed_r9))
  826. Features.push_back("+reserve-r9");
  827. // The kext linker doesn't know how to deal with movw/movt.
  828. if (KernelOrKext)
  829. Features.push_back("+no-movt");
  830. }
  831. void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
  832. ArgStringList &CmdArgs, bool KernelOrKext) const {
  833. // Select the ABI to use.
  834. // FIXME: Support -meabi.
  835. // FIXME: Parts of this are duplicated in the backend, unify this somehow.
  836. const char *ABIName = nullptr;
  837. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  838. ABIName = A->getValue();
  839. } else if (Triple.isOSBinFormatMachO()) {
  840. if (useAAPCSForMachO(Triple)) {
  841. ABIName = "aapcs";
  842. } else if (Triple.isWatchOS()) {
  843. ABIName = "aapcs16";
  844. } else {
  845. ABIName = "apcs-gnu";
  846. }
  847. } else if (Triple.isOSWindows()) {
  848. // FIXME: this is invalid for WindowsCE
  849. ABIName = "aapcs";
  850. } else {
  851. // Select the default based on the platform.
  852. switch (Triple.getEnvironment()) {
  853. case llvm::Triple::Android:
  854. case llvm::Triple::GNUEABI:
  855. case llvm::Triple::GNUEABIHF:
  856. ABIName = "aapcs-linux";
  857. break;
  858. case llvm::Triple::EABIHF:
  859. case llvm::Triple::EABI:
  860. ABIName = "aapcs";
  861. break;
  862. default:
  863. if (Triple.getOS() == llvm::Triple::NetBSD)
  864. ABIName = "apcs-gnu";
  865. else
  866. ABIName = "aapcs";
  867. break;
  868. }
  869. }
  870. CmdArgs.push_back("-target-abi");
  871. CmdArgs.push_back(ABIName);
  872. // Determine floating point ABI from the options & target defaults.
  873. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  874. if (ABI == arm::FloatABI::Soft) {
  875. // Floating point operations and argument passing are soft.
  876. // FIXME: This changes CPP defines, we need -target-soft-float.
  877. CmdArgs.push_back("-msoft-float");
  878. CmdArgs.push_back("-mfloat-abi");
  879. CmdArgs.push_back("soft");
  880. } else if (ABI == arm::FloatABI::SoftFP) {
  881. // Floating point operations are hard, but argument passing is soft.
  882. CmdArgs.push_back("-mfloat-abi");
  883. CmdArgs.push_back("soft");
  884. } else {
  885. // Floating point operations and argument passing are hard.
  886. assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
  887. CmdArgs.push_back("-mfloat-abi");
  888. CmdArgs.push_back("hard");
  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("-arm-global-merge=false");
  896. else
  897. CmdArgs.push_back("-arm-global-merge=true");
  898. }
  899. if (!Args.hasFlag(options::OPT_mimplicit_float,
  900. options::OPT_mno_implicit_float, true))
  901. CmdArgs.push_back("-no-implicit-float");
  902. }
  903. // ARM tools end.
  904. /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
  905. /// targeting.
  906. static std::string getAArch64TargetCPU(const ArgList &Args) {
  907. Arg *A;
  908. std::string CPU;
  909. // If we have -mtune or -mcpu, use that.
  910. if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
  911. CPU = StringRef(A->getValue()).lower();
  912. } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
  913. StringRef Mcpu = A->getValue();
  914. CPU = Mcpu.split("+").first.lower();
  915. }
  916. // Handle CPU name is 'native'.
  917. if (CPU == "native")
  918. return llvm::sys::getHostCPUName();
  919. else if (CPU.size())
  920. return CPU;
  921. // Make sure we pick "cyclone" if -arch is used.
  922. // FIXME: Should this be picked by checking the target triple instead?
  923. if (Args.getLastArg(options::OPT_arch))
  924. return "cyclone";
  925. return "generic";
  926. }
  927. void Clang::AddAArch64TargetArgs(const ArgList &Args,
  928. ArgStringList &CmdArgs) const {
  929. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  930. llvm::Triple Triple(TripleStr);
  931. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  932. Args.hasArg(options::OPT_mkernel) ||
  933. Args.hasArg(options::OPT_fapple_kext))
  934. CmdArgs.push_back("-disable-red-zone");
  935. if (!Args.hasFlag(options::OPT_mimplicit_float,
  936. options::OPT_mno_implicit_float, true))
  937. CmdArgs.push_back("-no-implicit-float");
  938. const char *ABIName = nullptr;
  939. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  940. ABIName = A->getValue();
  941. else if (Triple.isOSDarwin())
  942. ABIName = "darwinpcs";
  943. else
  944. ABIName = "aapcs";
  945. CmdArgs.push_back("-target-abi");
  946. CmdArgs.push_back(ABIName);
  947. if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
  948. options::OPT_mno_fix_cortex_a53_835769)) {
  949. CmdArgs.push_back("-backend-option");
  950. if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
  951. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  952. else
  953. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
  954. } else if (Triple.isAndroid()) {
  955. // Enabled A53 errata (835769) workaround by default on android
  956. CmdArgs.push_back("-backend-option");
  957. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  958. }
  959. // Forward the -mglobal-merge option for explicit control over the pass.
  960. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  961. options::OPT_mno_global_merge)) {
  962. CmdArgs.push_back("-backend-option");
  963. if (A->getOption().matches(options::OPT_mno_global_merge))
  964. CmdArgs.push_back("-aarch64-global-merge=false");
  965. else
  966. CmdArgs.push_back("-aarch64-global-merge=true");
  967. }
  968. }
  969. // Get CPU and ABI names. They are not independent
  970. // so we have to calculate them together.
  971. void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
  972. StringRef &CPUName, StringRef &ABIName) {
  973. const char *DefMips32CPU = "mips32r2";
  974. const char *DefMips64CPU = "mips64r2";
  975. // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
  976. // default for mips64(el)?-img-linux-gnu.
  977. if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
  978. Triple.getEnvironment() == llvm::Triple::GNU) {
  979. DefMips32CPU = "mips32r6";
  980. DefMips64CPU = "mips64r6";
  981. }
  982. // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
  983. if (Triple.isAndroid())
  984. DefMips64CPU = "mips64r6";
  985. // MIPS3 is the default for mips64*-unknown-openbsd.
  986. if (Triple.getOS() == llvm::Triple::OpenBSD)
  987. DefMips64CPU = "mips3";
  988. if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
  989. CPUName = A->getValue();
  990. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  991. ABIName = A->getValue();
  992. // Convert a GNU style Mips ABI name to the name
  993. // accepted by LLVM Mips backend.
  994. ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
  995. .Case("32", "o32")
  996. .Case("64", "n64")
  997. .Default(ABIName);
  998. }
  999. // Setup default CPU and ABI names.
  1000. if (CPUName.empty() && ABIName.empty()) {
  1001. switch (Triple.getArch()) {
  1002. default:
  1003. llvm_unreachable("Unexpected triple arch name");
  1004. case llvm::Triple::mips:
  1005. case llvm::Triple::mipsel:
  1006. CPUName = DefMips32CPU;
  1007. break;
  1008. case llvm::Triple::mips64:
  1009. case llvm::Triple::mips64el:
  1010. CPUName = DefMips64CPU;
  1011. break;
  1012. }
  1013. }
  1014. if (ABIName.empty()) {
  1015. // Deduce ABI name from the target triple.
  1016. if (Triple.getArch() == llvm::Triple::mips ||
  1017. Triple.getArch() == llvm::Triple::mipsel)
  1018. ABIName = "o32";
  1019. else
  1020. ABIName = "n64";
  1021. }
  1022. if (CPUName.empty()) {
  1023. // Deduce CPU name from ABI name.
  1024. CPUName = llvm::StringSwitch<const char *>(ABIName)
  1025. .Cases("o32", "eabi", DefMips32CPU)
  1026. .Cases("n32", "n64", DefMips64CPU)
  1027. .Default("");
  1028. }
  1029. // FIXME: Warn on inconsistent use of -march and -mabi.
  1030. }
  1031. std::string mips::getMipsABILibSuffix(const ArgList &Args,
  1032. const llvm::Triple &Triple) {
  1033. StringRef CPUName, ABIName;
  1034. tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1035. return llvm::StringSwitch<std::string>(ABIName)
  1036. .Case("o32", "")
  1037. .Case("n32", "32")
  1038. .Case("n64", "64");
  1039. }
  1040. // Convert ABI name to the GNU tools acceptable variant.
  1041. static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
  1042. return llvm::StringSwitch<llvm::StringRef>(ABI)
  1043. .Case("o32", "32")
  1044. .Case("n64", "64")
  1045. .Default(ABI);
  1046. }
  1047. // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
  1048. // and -mfloat-abi=.
  1049. static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
  1050. mips::FloatABI ABI = mips::FloatABI::Invalid;
  1051. if (Arg *A =
  1052. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1053. options::OPT_mfloat_abi_EQ)) {
  1054. if (A->getOption().matches(options::OPT_msoft_float))
  1055. ABI = mips::FloatABI::Soft;
  1056. else if (A->getOption().matches(options::OPT_mhard_float))
  1057. ABI = mips::FloatABI::Hard;
  1058. else {
  1059. ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
  1060. .Case("soft", mips::FloatABI::Soft)
  1061. .Case("hard", mips::FloatABI::Hard)
  1062. .Default(mips::FloatABI::Invalid);
  1063. if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1064. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1065. ABI = mips::FloatABI::Hard;
  1066. }
  1067. }
  1068. }
  1069. // If unspecified, choose the default based on the platform.
  1070. if (ABI == mips::FloatABI::Invalid) {
  1071. // Assume "hard", because it's a default value used by gcc.
  1072. // When we start to recognize specific target MIPS processors,
  1073. // we will be able to select the default more correctly.
  1074. ABI = mips::FloatABI::Hard;
  1075. }
  1076. assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
  1077. return ABI;
  1078. }
  1079. static void AddTargetFeature(const ArgList &Args,
  1080. std::vector<const char *> &Features,
  1081. OptSpecifier OnOpt, OptSpecifier OffOpt,
  1082. StringRef FeatureName) {
  1083. if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
  1084. if (A->getOption().matches(OnOpt))
  1085. Features.push_back(Args.MakeArgString("+" + FeatureName));
  1086. else
  1087. Features.push_back(Args.MakeArgString("-" + FeatureName));
  1088. }
  1089. }
  1090. static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1091. const ArgList &Args,
  1092. std::vector<const char *> &Features) {
  1093. StringRef CPUName;
  1094. StringRef ABIName;
  1095. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1096. ABIName = getGnuCompatibleMipsABIName(ABIName);
  1097. AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
  1098. options::OPT_mabicalls, "noabicalls");
  1099. mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
  1100. if (FloatABI == mips::FloatABI::Soft) {
  1101. // FIXME: Note, this is a hack. We need to pass the selected float
  1102. // mode to the MipsTargetInfoBase to define appropriate macros there.
  1103. // Now it is the only method.
  1104. Features.push_back("+soft-float");
  1105. }
  1106. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  1107. StringRef Val = StringRef(A->getValue());
  1108. if (Val == "2008") {
  1109. if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
  1110. Features.push_back("+nan2008");
  1111. else {
  1112. Features.push_back("-nan2008");
  1113. D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
  1114. }
  1115. } else if (Val == "legacy") {
  1116. if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
  1117. Features.push_back("-nan2008");
  1118. else {
  1119. Features.push_back("+nan2008");
  1120. D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
  1121. }
  1122. } else
  1123. D.Diag(diag::err_drv_unsupported_option_argument)
  1124. << A->getOption().getName() << Val;
  1125. }
  1126. AddTargetFeature(Args, Features, options::OPT_msingle_float,
  1127. options::OPT_mdouble_float, "single-float");
  1128. AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
  1129. "mips16");
  1130. AddTargetFeature(Args, Features, options::OPT_mmicromips,
  1131. options::OPT_mno_micromips, "micromips");
  1132. AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
  1133. "dsp");
  1134. AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
  1135. "dspr2");
  1136. AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
  1137. "msa");
  1138. // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
  1139. // pass -mfpxx
  1140. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  1141. options::OPT_mfp64)) {
  1142. if (A->getOption().matches(options::OPT_mfp32))
  1143. Features.push_back(Args.MakeArgString("-fp64"));
  1144. else if (A->getOption().matches(options::OPT_mfpxx)) {
  1145. Features.push_back(Args.MakeArgString("+fpxx"));
  1146. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1147. } else
  1148. Features.push_back(Args.MakeArgString("+fp64"));
  1149. } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
  1150. Features.push_back(Args.MakeArgString("+fpxx"));
  1151. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1152. }
  1153. AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
  1154. options::OPT_modd_spreg, "nooddspreg");
  1155. }
  1156. void Clang::AddMIPSTargetArgs(const ArgList &Args,
  1157. ArgStringList &CmdArgs) const {
  1158. const Driver &D = getToolChain().getDriver();
  1159. StringRef CPUName;
  1160. StringRef ABIName;
  1161. const llvm::Triple &Triple = getToolChain().getTriple();
  1162. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1163. CmdArgs.push_back("-target-abi");
  1164. CmdArgs.push_back(ABIName.data());
  1165. mips::FloatABI ABI = getMipsFloatABI(D, Args);
  1166. if (ABI == mips::FloatABI::Soft) {
  1167. // Floating point operations and argument passing are soft.
  1168. CmdArgs.push_back("-msoft-float");
  1169. CmdArgs.push_back("-mfloat-abi");
  1170. CmdArgs.push_back("soft");
  1171. } else {
  1172. // Floating point operations and argument passing are hard.
  1173. assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
  1174. CmdArgs.push_back("-mfloat-abi");
  1175. CmdArgs.push_back("hard");
  1176. }
  1177. if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
  1178. if (A->getOption().matches(options::OPT_mxgot)) {
  1179. CmdArgs.push_back("-mllvm");
  1180. CmdArgs.push_back("-mxgot");
  1181. }
  1182. }
  1183. if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
  1184. options::OPT_mno_ldc1_sdc1)) {
  1185. if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
  1186. CmdArgs.push_back("-mllvm");
  1187. CmdArgs.push_back("-mno-ldc1-sdc1");
  1188. }
  1189. }
  1190. if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
  1191. options::OPT_mno_check_zero_division)) {
  1192. if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
  1193. CmdArgs.push_back("-mllvm");
  1194. CmdArgs.push_back("-mno-check-zero-division");
  1195. }
  1196. }
  1197. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  1198. StringRef v = A->getValue();
  1199. CmdArgs.push_back("-mllvm");
  1200. CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
  1201. A->claim();
  1202. }
  1203. }
  1204. /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
  1205. static std::string getPPCTargetCPU(const ArgList &Args) {
  1206. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1207. StringRef CPUName = A->getValue();
  1208. if (CPUName == "native") {
  1209. std::string CPU = llvm::sys::getHostCPUName();
  1210. if (!CPU.empty() && CPU != "generic")
  1211. return CPU;
  1212. else
  1213. return "";
  1214. }
  1215. return llvm::StringSwitch<const char *>(CPUName)
  1216. .Case("common", "generic")
  1217. .Case("440", "440")
  1218. .Case("440fp", "440")
  1219. .Case("450", "450")
  1220. .Case("601", "601")
  1221. .Case("602", "602")
  1222. .Case("603", "603")
  1223. .Case("603e", "603e")
  1224. .Case("603ev", "603ev")
  1225. .Case("604", "604")
  1226. .Case("604e", "604e")
  1227. .Case("620", "620")
  1228. .Case("630", "pwr3")
  1229. .Case("G3", "g3")
  1230. .Case("7400", "7400")
  1231. .Case("G4", "g4")
  1232. .Case("7450", "7450")
  1233. .Case("G4+", "g4+")
  1234. .Case("750", "750")
  1235. .Case("970", "970")
  1236. .Case("G5", "g5")
  1237. .Case("a2", "a2")
  1238. .Case("a2q", "a2q")
  1239. .Case("e500mc", "e500mc")
  1240. .Case("e5500", "e5500")
  1241. .Case("power3", "pwr3")
  1242. .Case("power4", "pwr4")
  1243. .Case("power5", "pwr5")
  1244. .Case("power5x", "pwr5x")
  1245. .Case("power6", "pwr6")
  1246. .Case("power6x", "pwr6x")
  1247. .Case("power7", "pwr7")
  1248. .Case("power8", "pwr8")
  1249. .Case("pwr3", "pwr3")
  1250. .Case("pwr4", "pwr4")
  1251. .Case("pwr5", "pwr5")
  1252. .Case("pwr5x", "pwr5x")
  1253. .Case("pwr6", "pwr6")
  1254. .Case("pwr6x", "pwr6x")
  1255. .Case("pwr7", "pwr7")
  1256. .Case("pwr8", "pwr8")
  1257. .Case("powerpc", "ppc")
  1258. .Case("powerpc64", "ppc64")
  1259. .Case("powerpc64le", "ppc64le")
  1260. .Default("");
  1261. }
  1262. return "";
  1263. }
  1264. static void getPPCTargetFeatures(const ArgList &Args,
  1265. std::vector<const char *> &Features) {
  1266. for (const Arg *A : Args.filtered(options::OPT_m_ppc_Features_Group)) {
  1267. StringRef Name = A->getOption().getName();
  1268. A->claim();
  1269. // Skip over "-m".
  1270. assert(Name.startswith("m") && "Invalid feature name.");
  1271. Name = Name.substr(1);
  1272. bool IsNegative = Name.startswith("no-");
  1273. if (IsNegative)
  1274. Name = Name.substr(3);
  1275. // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
  1276. // pass the correct option to the backend while calling the frontend
  1277. // option the same.
  1278. // TODO: Change the LLVM backend option maybe?
  1279. if (Name == "mfcrf")
  1280. Name = "mfocrf";
  1281. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  1282. }
  1283. // Altivec is a bit weird, allow overriding of the Altivec feature here.
  1284. AddTargetFeature(Args, Features, options::OPT_faltivec,
  1285. options::OPT_fno_altivec, "altivec");
  1286. }
  1287. void Clang::AddPPCTargetArgs(const ArgList &Args,
  1288. ArgStringList &CmdArgs) const {
  1289. // Select the ABI to use.
  1290. const char *ABIName = nullptr;
  1291. if (getToolChain().getTriple().isOSLinux())
  1292. switch (getToolChain().getArch()) {
  1293. case llvm::Triple::ppc64: {
  1294. // When targeting a processor that supports QPX, or if QPX is
  1295. // specifically enabled, default to using the ABI that supports QPX (so
  1296. // long as it is not specifically disabled).
  1297. bool HasQPX = false;
  1298. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1299. HasQPX = A->getValue() == StringRef("a2q");
  1300. HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
  1301. if (HasQPX) {
  1302. ABIName = "elfv1-qpx";
  1303. break;
  1304. }
  1305. ABIName = "elfv1";
  1306. break;
  1307. }
  1308. case llvm::Triple::ppc64le:
  1309. ABIName = "elfv2";
  1310. break;
  1311. default:
  1312. break;
  1313. }
  1314. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1315. // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
  1316. // the option if given as we don't have backend support for any targets
  1317. // that don't use the altivec abi.
  1318. if (StringRef(A->getValue()) != "altivec")
  1319. ABIName = A->getValue();
  1320. if (ABIName) {
  1321. CmdArgs.push_back("-target-abi");
  1322. CmdArgs.push_back(ABIName);
  1323. }
  1324. }
  1325. bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
  1326. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  1327. return A && (A->getValue() == StringRef(Value));
  1328. }
  1329. /// Get the (LLVM) name of the R600 gpu we are targeting.
  1330. static std::string getR600TargetGPU(const ArgList &Args) {
  1331. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1332. const char *GPUName = A->getValue();
  1333. return llvm::StringSwitch<const char *>(GPUName)
  1334. .Cases("rv630", "rv635", "r600")
  1335. .Cases("rv610", "rv620", "rs780", "rs880")
  1336. .Case("rv740", "rv770")
  1337. .Case("palm", "cedar")
  1338. .Cases("sumo", "sumo2", "sumo")
  1339. .Case("hemlock", "cypress")
  1340. .Case("aruba", "cayman")
  1341. .Default(GPUName);
  1342. }
  1343. return "";
  1344. }
  1345. void Clang::AddSparcTargetArgs(const ArgList &Args,
  1346. ArgStringList &CmdArgs) const {
  1347. const Driver &D = getToolChain().getDriver();
  1348. std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
  1349. bool SoftFloatABI = false;
  1350. if (Arg *A =
  1351. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
  1352. if (A->getOption().matches(options::OPT_msoft_float))
  1353. SoftFloatABI = true;
  1354. }
  1355. // Only the hard-float ABI on Sparc is standardized, and it is the
  1356. // default. GCC also supports a nonstandard soft-float ABI mode, and
  1357. // perhaps LLVM should implement that, too. However, since llvm
  1358. // currently does not support Sparc soft-float, at all, display an
  1359. // error if it's requested.
  1360. if (SoftFloatABI) {
  1361. D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
  1362. << Triple;
  1363. }
  1364. }
  1365. static const char *getSystemZTargetCPU(const ArgList &Args) {
  1366. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1367. return A->getValue();
  1368. return "z10";
  1369. }
  1370. static void getSystemZTargetFeatures(const ArgList &Args,
  1371. std::vector<const char *> &Features) {
  1372. // -m(no-)htm overrides use of the transactional-execution facility.
  1373. if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
  1374. if (A->getOption().matches(options::OPT_mhtm))
  1375. Features.push_back("+transactional-execution");
  1376. else
  1377. Features.push_back("-transactional-execution");
  1378. }
  1379. // -m(no-)vx overrides use of the vector facility.
  1380. if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
  1381. if (A->getOption().matches(options::OPT_mvx))
  1382. Features.push_back("+vector");
  1383. else
  1384. Features.push_back("-vector");
  1385. }
  1386. }
  1387. static const char *getX86TargetCPU(const ArgList &Args,
  1388. const llvm::Triple &Triple) {
  1389. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1390. if (StringRef(A->getValue()) != "native") {
  1391. if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
  1392. return "core-avx2";
  1393. return A->getValue();
  1394. }
  1395. // FIXME: Reject attempts to use -march=native unless the target matches
  1396. // the host.
  1397. //
  1398. // FIXME: We should also incorporate the detected target features for use
  1399. // with -native.
  1400. std::string CPU = llvm::sys::getHostCPUName();
  1401. if (!CPU.empty() && CPU != "generic")
  1402. return Args.MakeArgString(CPU);
  1403. }
  1404. if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1405. // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
  1406. StringRef Arch = A->getValue();
  1407. const char *CPU;
  1408. if (Triple.getArch() == llvm::Triple::x86) {
  1409. CPU = llvm::StringSwitch<const char *>(Arch)
  1410. .Case("IA32", "i386")
  1411. .Case("SSE", "pentium3")
  1412. .Case("SSE2", "pentium4")
  1413. .Case("AVX", "sandybridge")
  1414. .Case("AVX2", "haswell")
  1415. .Default(nullptr);
  1416. } else {
  1417. CPU = llvm::StringSwitch<const char *>(Arch)
  1418. .Case("AVX", "sandybridge")
  1419. .Case("AVX2", "haswell")
  1420. .Default(nullptr);
  1421. }
  1422. if (CPU)
  1423. return CPU;
  1424. }
  1425. // Select the default CPU if none was given (or detection failed).
  1426. if (Triple.getArch() != llvm::Triple::x86_64 &&
  1427. Triple.getArch() != llvm::Triple::x86)
  1428. return nullptr; // This routine is only handling x86 targets.
  1429. bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
  1430. // FIXME: Need target hooks.
  1431. if (Triple.isOSDarwin()) {
  1432. if (Triple.getArchName() == "x86_64h")
  1433. return "core-avx2";
  1434. return Is64Bit ? "core2" : "yonah";
  1435. }
  1436. // Set up default CPU name for PS4 compilers.
  1437. if (Triple.isPS4CPU())
  1438. return "btver2";
  1439. // On Android use targets compatible with gcc
  1440. if (Triple.isAndroid())
  1441. return Is64Bit ? "x86-64" : "i686";
  1442. // Everything else goes to x86-64 in 64-bit mode.
  1443. if (Is64Bit)
  1444. return "x86-64";
  1445. switch (Triple.getOS()) {
  1446. case llvm::Triple::FreeBSD:
  1447. case llvm::Triple::NetBSD:
  1448. case llvm::Triple::OpenBSD:
  1449. return "i486";
  1450. case llvm::Triple::Haiku:
  1451. return "i586";
  1452. case llvm::Triple::Bitrig:
  1453. return "i686";
  1454. default:
  1455. // Fallback to p4.
  1456. return "pentium4";
  1457. }
  1458. }
  1459. /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
  1460. static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
  1461. // If we have -mcpu=, use that.
  1462. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1463. StringRef CPU = A->getValue();
  1464. #ifdef __wasm__
  1465. // Handle "native" by examining the host. "native" isn't meaningful when
  1466. // cross compiling, so only support this when the host is also WebAssembly.
  1467. if (CPU == "native")
  1468. return llvm::sys::getHostCPUName();
  1469. #endif
  1470. return CPU;
  1471. }
  1472. return "generic";
  1473. }
  1474. static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
  1475. bool FromAs = false) {
  1476. switch (T.getArch()) {
  1477. default:
  1478. return "";
  1479. case llvm::Triple::aarch64:
  1480. case llvm::Triple::aarch64_be:
  1481. return getAArch64TargetCPU(Args);
  1482. case llvm::Triple::arm:
  1483. case llvm::Triple::armeb:
  1484. case llvm::Triple::thumb:
  1485. case llvm::Triple::thumbeb: {
  1486. StringRef MArch, MCPU;
  1487. getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
  1488. return arm::getARMTargetCPU(MCPU, MArch, T);
  1489. }
  1490. case llvm::Triple::mips:
  1491. case llvm::Triple::mipsel:
  1492. case llvm::Triple::mips64:
  1493. case llvm::Triple::mips64el: {
  1494. StringRef CPUName;
  1495. StringRef ABIName;
  1496. mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
  1497. return CPUName;
  1498. }
  1499. case llvm::Triple::nvptx:
  1500. case llvm::Triple::nvptx64:
  1501. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1502. return A->getValue();
  1503. return "";
  1504. case llvm::Triple::ppc:
  1505. case llvm::Triple::ppc64:
  1506. case llvm::Triple::ppc64le: {
  1507. std::string TargetCPUName = getPPCTargetCPU(Args);
  1508. // LLVM may default to generating code for the native CPU,
  1509. // but, like gcc, we default to a more generic option for
  1510. // each architecture. (except on Darwin)
  1511. if (TargetCPUName.empty() && !T.isOSDarwin()) {
  1512. if (T.getArch() == llvm::Triple::ppc64)
  1513. TargetCPUName = "ppc64";
  1514. else if (T.getArch() == llvm::Triple::ppc64le)
  1515. TargetCPUName = "ppc64le";
  1516. else
  1517. TargetCPUName = "ppc";
  1518. }
  1519. return TargetCPUName;
  1520. }
  1521. case llvm::Triple::sparc:
  1522. case llvm::Triple::sparcel:
  1523. case llvm::Triple::sparcv9:
  1524. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1525. return A->getValue();
  1526. return "";
  1527. case llvm::Triple::x86:
  1528. case llvm::Triple::x86_64:
  1529. return getX86TargetCPU(Args, T);
  1530. case llvm::Triple::hexagon:
  1531. return "hexagon" + toolchains::HexagonToolChain::GetTargetCPU(Args).str();
  1532. case llvm::Triple::systemz:
  1533. return getSystemZTargetCPU(Args);
  1534. case llvm::Triple::r600:
  1535. case llvm::Triple::amdgcn:
  1536. return getR600TargetGPU(Args);
  1537. case llvm::Triple::wasm32:
  1538. case llvm::Triple::wasm64:
  1539. return getWebAssemblyTargetCPU(Args);
  1540. }
  1541. }
  1542. static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
  1543. ArgStringList &CmdArgs, bool IsThinLTO) {
  1544. // Tell the linker to load the plugin. This has to come before AddLinkerInputs
  1545. // as gold requires -plugin to come before any -plugin-opt that -Wl might
  1546. // forward.
  1547. CmdArgs.push_back("-plugin");
  1548. std::string Plugin =
  1549. ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
  1550. CmdArgs.push_back(Args.MakeArgString(Plugin));
  1551. // Try to pass driver level flags relevant to LTO code generation down to
  1552. // the plugin.
  1553. // Handle flags for selecting CPU variants.
  1554. std::string CPU = getCPUName(Args, ToolChain.getTriple());
  1555. if (!CPU.empty())
  1556. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
  1557. if (IsThinLTO)
  1558. CmdArgs.push_back("-plugin-opt=thinlto");
  1559. }
  1560. /// This is a helper function for validating the optional refinement step
  1561. /// parameter in reciprocal argument strings. Return false if there is an error
  1562. /// parsing the refinement step. Otherwise, return true and set the Position
  1563. /// of the refinement step in the input string.
  1564. static bool getRefinementStep(StringRef In, const Driver &D,
  1565. const Arg &A, size_t &Position) {
  1566. const char RefinementStepToken = ':';
  1567. Position = In.find(RefinementStepToken);
  1568. if (Position != StringRef::npos) {
  1569. StringRef Option = A.getOption().getName();
  1570. StringRef RefStep = In.substr(Position + 1);
  1571. // Allow exactly one numeric character for the additional refinement
  1572. // step parameter. This is reasonable for all currently-supported
  1573. // operations and architectures because we would expect that a larger value
  1574. // of refinement steps would cause the estimate "optimization" to
  1575. // under-perform the native operation. Also, if the estimate does not
  1576. // converge quickly, it probably will not ever converge, so further
  1577. // refinement steps will not produce a better answer.
  1578. if (RefStep.size() != 1) {
  1579. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1580. return false;
  1581. }
  1582. char RefStepChar = RefStep[0];
  1583. if (RefStepChar < '0' || RefStepChar > '9') {
  1584. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1585. return false;
  1586. }
  1587. }
  1588. return true;
  1589. }
  1590. /// The -mrecip flag requires processing of many optional parameters.
  1591. static void ParseMRecip(const Driver &D, const ArgList &Args,
  1592. ArgStringList &OutStrings) {
  1593. StringRef DisabledPrefixIn = "!";
  1594. StringRef DisabledPrefixOut = "!";
  1595. StringRef EnabledPrefixOut = "";
  1596. StringRef Out = "-mrecip=";
  1597. Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
  1598. if (!A)
  1599. return;
  1600. unsigned NumOptions = A->getNumValues();
  1601. if (NumOptions == 0) {
  1602. // No option is the same as "all".
  1603. OutStrings.push_back(Args.MakeArgString(Out + "all"));
  1604. return;
  1605. }
  1606. // Pass through "all", "none", or "default" with an optional refinement step.
  1607. if (NumOptions == 1) {
  1608. StringRef Val = A->getValue(0);
  1609. size_t RefStepLoc;
  1610. if (!getRefinementStep(Val, D, *A, RefStepLoc))
  1611. return;
  1612. StringRef ValBase = Val.slice(0, RefStepLoc);
  1613. if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
  1614. OutStrings.push_back(Args.MakeArgString(Out + Val));
  1615. return;
  1616. }
  1617. }
  1618. // Each reciprocal type may be enabled or disabled individually.
  1619. // Check each input value for validity, concatenate them all back together,
  1620. // and pass through.
  1621. llvm::StringMap<bool> OptionStrings;
  1622. OptionStrings.insert(std::make_pair("divd", false));
  1623. OptionStrings.insert(std::make_pair("divf", false));
  1624. OptionStrings.insert(std::make_pair("vec-divd", false));
  1625. OptionStrings.insert(std::make_pair("vec-divf", false));
  1626. OptionStrings.insert(std::make_pair("sqrtd", false));
  1627. OptionStrings.insert(std::make_pair("sqrtf", false));
  1628. OptionStrings.insert(std::make_pair("vec-sqrtd", false));
  1629. OptionStrings.insert(std::make_pair("vec-sqrtf", false));
  1630. for (unsigned i = 0; i != NumOptions; ++i) {
  1631. StringRef Val = A->getValue(i);
  1632. bool IsDisabled = Val.startswith(DisabledPrefixIn);
  1633. // Ignore the disablement token for string matching.
  1634. if (IsDisabled)
  1635. Val = Val.substr(1);
  1636. size_t RefStep;
  1637. if (!getRefinementStep(Val, D, *A, RefStep))
  1638. return;
  1639. StringRef ValBase = Val.slice(0, RefStep);
  1640. llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
  1641. if (OptionIter == OptionStrings.end()) {
  1642. // Try again specifying float suffix.
  1643. OptionIter = OptionStrings.find(ValBase.str() + 'f');
  1644. if (OptionIter == OptionStrings.end()) {
  1645. // The input name did not match any known option string.
  1646. D.Diag(diag::err_drv_unknown_argument) << Val;
  1647. return;
  1648. }
  1649. // The option was specified without a float or double suffix.
  1650. // Make sure that the double entry was not already specified.
  1651. // The float entry will be checked below.
  1652. if (OptionStrings[ValBase.str() + 'd']) {
  1653. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1654. return;
  1655. }
  1656. }
  1657. if (OptionIter->second == true) {
  1658. // Duplicate option specified.
  1659. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1660. return;
  1661. }
  1662. // Mark the matched option as found. Do not allow duplicate specifiers.
  1663. OptionIter->second = true;
  1664. // If the precision was not specified, also mark the double entry as found.
  1665. if (ValBase.back() != 'f' && ValBase.back() != 'd')
  1666. OptionStrings[ValBase.str() + 'd'] = true;
  1667. // Build the output string.
  1668. StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
  1669. Out = Args.MakeArgString(Out + Prefix + Val);
  1670. if (i != NumOptions - 1)
  1671. Out = Args.MakeArgString(Out + ",");
  1672. }
  1673. OutStrings.push_back(Args.MakeArgString(Out));
  1674. }
  1675. static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1676. const ArgList &Args,
  1677. std::vector<const char *> &Features) {
  1678. // If -march=native, autodetect the feature list.
  1679. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1680. if (StringRef(A->getValue()) == "native") {
  1681. llvm::StringMap<bool> HostFeatures;
  1682. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  1683. for (auto &F : HostFeatures)
  1684. Features.push_back(
  1685. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  1686. }
  1687. }
  1688. if (Triple.getArchName() == "x86_64h") {
  1689. // x86_64h implies quite a few of the more modern subtarget features
  1690. // for Haswell class CPUs, but not all of them. Opt-out of a few.
  1691. Features.push_back("-rdrnd");
  1692. Features.push_back("-aes");
  1693. Features.push_back("-pclmul");
  1694. Features.push_back("-rtm");
  1695. Features.push_back("-hle");
  1696. Features.push_back("-fsgsbase");
  1697. }
  1698. const llvm::Triple::ArchType ArchType = Triple.getArch();
  1699. // Add features to be compatible with gcc for Android.
  1700. if (Triple.isAndroid()) {
  1701. if (ArchType == llvm::Triple::x86_64) {
  1702. Features.push_back("+sse4.2");
  1703. Features.push_back("+popcnt");
  1704. } else
  1705. Features.push_back("+ssse3");
  1706. }
  1707. // Set features according to the -arch flag on MSVC.
  1708. if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1709. StringRef Arch = A->getValue();
  1710. bool ArchUsed = false;
  1711. // First, look for flags that are shared in x86 and x86-64.
  1712. if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
  1713. if (Arch == "AVX" || Arch == "AVX2") {
  1714. ArchUsed = true;
  1715. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1716. }
  1717. }
  1718. // Then, look for x86-specific flags.
  1719. if (ArchType == llvm::Triple::x86) {
  1720. if (Arch == "IA32") {
  1721. ArchUsed = true;
  1722. } else if (Arch == "SSE" || Arch == "SSE2") {
  1723. ArchUsed = true;
  1724. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1725. }
  1726. }
  1727. if (!ArchUsed)
  1728. D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
  1729. }
  1730. // Now add any that the user explicitly requested on the command line,
  1731. // which may override the defaults.
  1732. for (const Arg *A : Args.filtered(options::OPT_m_x86_Features_Group)) {
  1733. StringRef Name = A->getOption().getName();
  1734. A->claim();
  1735. // Skip over "-m".
  1736. assert(Name.startswith("m") && "Invalid feature name.");
  1737. Name = Name.substr(1);
  1738. bool IsNegative = Name.startswith("no-");
  1739. if (IsNegative)
  1740. Name = Name.substr(3);
  1741. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  1742. }
  1743. }
  1744. void Clang::AddX86TargetArgs(const ArgList &Args,
  1745. ArgStringList &CmdArgs) const {
  1746. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1747. Args.hasArg(options::OPT_mkernel) ||
  1748. Args.hasArg(options::OPT_fapple_kext))
  1749. CmdArgs.push_back("-disable-red-zone");
  1750. // Default to avoid implicit floating-point for kernel/kext code, but allow
  1751. // that to be overridden with -mno-soft-float.
  1752. bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
  1753. Args.hasArg(options::OPT_fapple_kext));
  1754. if (Arg *A = Args.getLastArg(
  1755. options::OPT_msoft_float, options::OPT_mno_soft_float,
  1756. options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
  1757. const Option &O = A->getOption();
  1758. NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
  1759. O.matches(options::OPT_msoft_float));
  1760. }
  1761. if (NoImplicitFloat)
  1762. CmdArgs.push_back("-no-implicit-float");
  1763. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  1764. StringRef Value = A->getValue();
  1765. if (Value == "intel" || Value == "att") {
  1766. CmdArgs.push_back("-mllvm");
  1767. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  1768. } else {
  1769. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  1770. << A->getOption().getName() << Value;
  1771. }
  1772. }
  1773. }
  1774. void Clang::AddHexagonTargetArgs(const ArgList &Args,
  1775. ArgStringList &CmdArgs) const {
  1776. CmdArgs.push_back("-mqdsp6-compat");
  1777. CmdArgs.push_back("-Wreturn-type");
  1778. if (const char *v =
  1779. toolchains::HexagonToolChain::GetSmallDataThreshold(Args)) {
  1780. std::string SmallDataThreshold = "-hexagon-small-data-threshold=";
  1781. SmallDataThreshold += v;
  1782. CmdArgs.push_back("-mllvm");
  1783. CmdArgs.push_back(Args.MakeArgString(SmallDataThreshold));
  1784. }
  1785. if (!Args.hasArg(options::OPT_fno_short_enums))
  1786. CmdArgs.push_back("-fshort-enums");
  1787. if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
  1788. CmdArgs.push_back("-mllvm");
  1789. CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
  1790. }
  1791. CmdArgs.push_back("-mllvm");
  1792. CmdArgs.push_back("-machine-sink-split=0");
  1793. }
  1794. // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
  1795. static bool DecodeAArch64Features(const Driver &D, StringRef text,
  1796. std::vector<const char *> &Features) {
  1797. SmallVector<StringRef, 8> Split;
  1798. text.split(Split, StringRef("+"), -1, false);
  1799. for (StringRef Feature : Split) {
  1800. const char *result = llvm::StringSwitch<const char *>(Feature)
  1801. .Case("fp", "+fp-armv8")
  1802. .Case("simd", "+neon")
  1803. .Case("crc", "+crc")
  1804. .Case("crypto", "+crypto")
  1805. .Case("nofp", "-fp-armv8")
  1806. .Case("nosimd", "-neon")
  1807. .Case("nocrc", "-crc")
  1808. .Case("nocrypto", "-crypto")
  1809. .Default(nullptr);
  1810. if (result)
  1811. Features.push_back(result);
  1812. else if (Feature == "neon" || Feature == "noneon")
  1813. D.Diag(diag::err_drv_no_neon_modifier);
  1814. else
  1815. return false;
  1816. }
  1817. return true;
  1818. }
  1819. // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
  1820. // decode CPU and feature.
  1821. static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
  1822. std::vector<const char *> &Features) {
  1823. std::pair<StringRef, StringRef> Split = Mcpu.split("+");
  1824. CPU = Split.first;
  1825. if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
  1826. CPU == "cortex-a72") {
  1827. Features.push_back("+neon");
  1828. Features.push_back("+crc");
  1829. Features.push_back("+crypto");
  1830. } else if (CPU == "generic") {
  1831. Features.push_back("+neon");
  1832. } else {
  1833. return false;
  1834. }
  1835. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  1836. return false;
  1837. return true;
  1838. }
  1839. static bool
  1840. getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
  1841. const ArgList &Args,
  1842. std::vector<const char *> &Features) {
  1843. std::string MarchLowerCase = March.lower();
  1844. std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
  1845. if (Split.first == "armv8-a" || Split.first == "armv8a") {
  1846. // ok, no additional features.
  1847. } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
  1848. Features.push_back("+v8.1a");
  1849. } else {
  1850. return false;
  1851. }
  1852. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  1853. return false;
  1854. return true;
  1855. }
  1856. static bool
  1857. getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  1858. const ArgList &Args,
  1859. std::vector<const char *> &Features) {
  1860. StringRef CPU;
  1861. std::string McpuLowerCase = Mcpu.lower();
  1862. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
  1863. return false;
  1864. return true;
  1865. }
  1866. static bool
  1867. getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
  1868. const ArgList &Args,
  1869. std::vector<const char *> &Features) {
  1870. std::string MtuneLowerCase = Mtune.lower();
  1871. // Handle CPU name is 'native'.
  1872. if (MtuneLowerCase == "native")
  1873. MtuneLowerCase = llvm::sys::getHostCPUName();
  1874. if (MtuneLowerCase == "cyclone") {
  1875. Features.push_back("+zcm");
  1876. Features.push_back("+zcz");
  1877. }
  1878. return true;
  1879. }
  1880. static bool
  1881. getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  1882. const ArgList &Args,
  1883. std::vector<const char *> &Features) {
  1884. StringRef CPU;
  1885. std::vector<const char *> DecodedFeature;
  1886. std::string McpuLowerCase = Mcpu.lower();
  1887. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
  1888. return false;
  1889. return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
  1890. }
  1891. static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
  1892. std::vector<const char *> &Features) {
  1893. Arg *A;
  1894. bool success = true;
  1895. // Enable NEON by default.
  1896. Features.push_back("+neon");
  1897. if ((A = Args.getLastArg(options::OPT_march_EQ)))
  1898. success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
  1899. else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
  1900. success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  1901. else if (Args.hasArg(options::OPT_arch))
  1902. success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
  1903. Features);
  1904. if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
  1905. success =
  1906. getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
  1907. else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
  1908. success =
  1909. getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  1910. else if (Args.hasArg(options::OPT_arch))
  1911. success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
  1912. Args, Features);
  1913. if (!success)
  1914. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  1915. if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
  1916. Features.push_back("-fp-armv8");
  1917. Features.push_back("-crypto");
  1918. Features.push_back("-neon");
  1919. }
  1920. // En/disable crc
  1921. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  1922. if (A->getOption().matches(options::OPT_mcrc))
  1923. Features.push_back("+crc");
  1924. else
  1925. Features.push_back("-crc");
  1926. }
  1927. if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  1928. options::OPT_munaligned_access))
  1929. if (A->getOption().matches(options::OPT_mno_unaligned_access))
  1930. Features.push_back("+strict-align");
  1931. if (Args.hasArg(options::OPT_ffixed_x18))
  1932. Features.push_back("+reserve-x18");
  1933. }
  1934. static void getWebAssemblyTargetFeatures(const ArgList &Args,
  1935. std::vector<const char *> &Features) {
  1936. for (const Arg *A : Args.filtered(options::OPT_m_wasm_Features_Group)) {
  1937. StringRef Name = A->getOption().getName();
  1938. A->claim();
  1939. // Skip over "-m".
  1940. assert(Name.startswith("m") && "Invalid feature name.");
  1941. Name = Name.substr(1);
  1942. bool IsNegative = Name.startswith("no-");
  1943. if (IsNegative)
  1944. Name = Name.substr(3);
  1945. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  1946. }
  1947. }
  1948. static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
  1949. const ArgList &Args, ArgStringList &CmdArgs,
  1950. bool ForAS) {
  1951. const Driver &D = TC.getDriver();
  1952. std::vector<const char *> Features;
  1953. switch (Triple.getArch()) {
  1954. default:
  1955. break;
  1956. case llvm::Triple::mips:
  1957. case llvm::Triple::mipsel:
  1958. case llvm::Triple::mips64:
  1959. case llvm::Triple::mips64el:
  1960. getMIPSTargetFeatures(D, Triple, Args, Features);
  1961. break;
  1962. case llvm::Triple::arm:
  1963. case llvm::Triple::armeb:
  1964. case llvm::Triple::thumb:
  1965. case llvm::Triple::thumbeb:
  1966. getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
  1967. break;
  1968. case llvm::Triple::ppc:
  1969. case llvm::Triple::ppc64:
  1970. case llvm::Triple::ppc64le:
  1971. getPPCTargetFeatures(Args, Features);
  1972. break;
  1973. case llvm::Triple::systemz:
  1974. getSystemZTargetFeatures(Args, Features);
  1975. break;
  1976. case llvm::Triple::aarch64:
  1977. case llvm::Triple::aarch64_be:
  1978. getAArch64TargetFeatures(D, Args, Features);
  1979. break;
  1980. case llvm::Triple::x86:
  1981. case llvm::Triple::x86_64:
  1982. getX86TargetFeatures(D, Triple, Args, Features);
  1983. break;
  1984. case llvm::Triple::wasm32:
  1985. case llvm::Triple::wasm64:
  1986. getWebAssemblyTargetFeatures(Args, Features);
  1987. break;
  1988. }
  1989. // Find the last of each feature.
  1990. llvm::StringMap<unsigned> LastOpt;
  1991. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  1992. const char *Name = Features[I];
  1993. assert(Name[0] == '-' || Name[0] == '+');
  1994. LastOpt[Name + 1] = I;
  1995. }
  1996. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  1997. // If this feature was overridden, ignore it.
  1998. const char *Name = Features[I];
  1999. llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
  2000. assert(LastI != LastOpt.end());
  2001. unsigned Last = LastI->second;
  2002. if (Last != I)
  2003. continue;
  2004. CmdArgs.push_back("-target-feature");
  2005. CmdArgs.push_back(Name);
  2006. }
  2007. }
  2008. static bool
  2009. shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
  2010. const llvm::Triple &Triple) {
  2011. // We use the zero-cost exception tables for Objective-C if the non-fragile
  2012. // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
  2013. // later.
  2014. if (runtime.isNonFragile())
  2015. return true;
  2016. if (!Triple.isMacOSX())
  2017. return false;
  2018. return (!Triple.isMacOSXVersionLT(10, 5) &&
  2019. (Triple.getArch() == llvm::Triple::x86_64 ||
  2020. Triple.getArch() == llvm::Triple::arm));
  2021. }
  2022. /// Adds exception related arguments to the driver command arguments. There's a
  2023. /// master flag, -fexceptions and also language specific flags to enable/disable
  2024. /// C++ and Objective-C exceptions. This makes it possible to for example
  2025. /// disable C++ exceptions but enable Objective-C exceptions.
  2026. static void addExceptionArgs(const ArgList &Args, types::ID InputType,
  2027. const ToolChain &TC, bool KernelOrKext,
  2028. const ObjCRuntime &objcRuntime,
  2029. ArgStringList &CmdArgs) {
  2030. const Driver &D = TC.getDriver();
  2031. const llvm::Triple &Triple = TC.getTriple();
  2032. if (KernelOrKext) {
  2033. // -mkernel and -fapple-kext imply no exceptions, so claim exception related
  2034. // arguments now to avoid warnings about unused arguments.
  2035. Args.ClaimAllArgs(options::OPT_fexceptions);
  2036. Args.ClaimAllArgs(options::OPT_fno_exceptions);
  2037. Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
  2038. Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
  2039. Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
  2040. Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
  2041. return;
  2042. }
  2043. // See if the user explicitly enabled exceptions.
  2044. bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  2045. false);
  2046. // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
  2047. // is not necessarily sensible, but follows GCC.
  2048. if (types::isObjC(InputType) &&
  2049. Args.hasFlag(options::OPT_fobjc_exceptions,
  2050. options::OPT_fno_objc_exceptions, true)) {
  2051. CmdArgs.push_back("-fobjc-exceptions");
  2052. EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
  2053. }
  2054. if (types::isCXX(InputType)) {
  2055. // Disable C++ EH by default on XCore, PS4, and MSVC.
  2056. // FIXME: Remove MSVC from this list once things work.
  2057. bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
  2058. !Triple.isPS4CPU() &&
  2059. !Triple.isWindowsMSVCEnvironment();
  2060. Arg *ExceptionArg = Args.getLastArg(
  2061. options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
  2062. options::OPT_fexceptions, options::OPT_fno_exceptions);
  2063. if (ExceptionArg)
  2064. CXXExceptionsEnabled =
  2065. ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
  2066. ExceptionArg->getOption().matches(options::OPT_fexceptions);
  2067. if (CXXExceptionsEnabled) {
  2068. if (Triple.isPS4CPU()) {
  2069. ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
  2070. assert(ExceptionArg &&
  2071. "On the PS4 exceptions should only be enabled if passing "
  2072. "an argument");
  2073. if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
  2074. const Arg *RTTIArg = TC.getRTTIArg();
  2075. assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
  2076. D.Diag(diag::err_drv_argument_not_allowed_with)
  2077. << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
  2078. } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
  2079. D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
  2080. } else
  2081. assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
  2082. CmdArgs.push_back("-fcxx-exceptions");
  2083. EH = true;
  2084. }
  2085. }
  2086. if (EH)
  2087. CmdArgs.push_back("-fexceptions");
  2088. }
  2089. static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
  2090. bool Default = true;
  2091. if (TC.getTriple().isOSDarwin()) {
  2092. // The native darwin assembler doesn't support the linker_option directives,
  2093. // so we disable them if we think the .s file will be passed to it.
  2094. Default = TC.useIntegratedAs();
  2095. }
  2096. return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
  2097. Default);
  2098. }
  2099. static bool ShouldDisableDwarfDirectory(const ArgList &Args,
  2100. const ToolChain &TC) {
  2101. bool UseDwarfDirectory =
  2102. Args.hasFlag(options::OPT_fdwarf_directory_asm,
  2103. options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
  2104. return !UseDwarfDirectory;
  2105. }
  2106. /// \brief Check whether the given input tree contains any compilation actions.
  2107. static bool ContainsCompileAction(const Action *A) {
  2108. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
  2109. return true;
  2110. for (const auto &Act : *A)
  2111. if (ContainsCompileAction(Act))
  2112. return true;
  2113. return false;
  2114. }
  2115. /// \brief Check if -relax-all should be passed to the internal assembler.
  2116. /// This is done by default when compiling non-assembler source with -O0.
  2117. static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
  2118. bool RelaxDefault = true;
  2119. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2120. RelaxDefault = A->getOption().matches(options::OPT_O0);
  2121. if (RelaxDefault) {
  2122. RelaxDefault = false;
  2123. for (const auto &Act : C.getActions()) {
  2124. if (ContainsCompileAction(Act)) {
  2125. RelaxDefault = true;
  2126. break;
  2127. }
  2128. }
  2129. }
  2130. return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
  2131. RelaxDefault);
  2132. }
  2133. // Extract the integer N from a string spelled "-dwarf-N", returning 0
  2134. // on mismatch. The StringRef input (rather than an Arg) allows
  2135. // for use by the "-Xassembler" option parser.
  2136. static unsigned DwarfVersionNum(StringRef ArgValue) {
  2137. return llvm::StringSwitch<unsigned>(ArgValue)
  2138. .Case("-gdwarf-2", 2)
  2139. .Case("-gdwarf-3", 3)
  2140. .Case("-gdwarf-4", 4)
  2141. .Default(0);
  2142. }
  2143. static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
  2144. CodeGenOptions::DebugInfoKind DebugInfoKind,
  2145. unsigned DwarfVersion) {
  2146. switch (DebugInfoKind) {
  2147. case CodeGenOptions::DebugLineTablesOnly:
  2148. CmdArgs.push_back("-debug-info-kind=line-tables-only");
  2149. break;
  2150. case CodeGenOptions::LimitedDebugInfo:
  2151. CmdArgs.push_back("-debug-info-kind=limited");
  2152. break;
  2153. case CodeGenOptions::FullDebugInfo:
  2154. CmdArgs.push_back("-debug-info-kind=standalone");
  2155. break;
  2156. default:
  2157. break;
  2158. }
  2159. if (DwarfVersion > 0)
  2160. CmdArgs.push_back(
  2161. Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
  2162. }
  2163. static void CollectArgsForIntegratedAssembler(Compilation &C,
  2164. const ArgList &Args,
  2165. ArgStringList &CmdArgs,
  2166. const Driver &D) {
  2167. if (UseRelaxAll(C, Args))
  2168. CmdArgs.push_back("-mrelax-all");
  2169. // When passing -I arguments to the assembler we sometimes need to
  2170. // unconditionally take the next argument. For example, when parsing
  2171. // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
  2172. // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
  2173. // arg after parsing the '-I' arg.
  2174. bool TakeNextArg = false;
  2175. // When using an integrated assembler, translate -Wa, and -Xassembler
  2176. // options.
  2177. bool CompressDebugSections = false;
  2178. for (const Arg *A :
  2179. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  2180. A->claim();
  2181. for (StringRef Value : A->getValues()) {
  2182. if (TakeNextArg) {
  2183. CmdArgs.push_back(Value.data());
  2184. TakeNextArg = false;
  2185. continue;
  2186. }
  2187. switch (C.getDefaultToolChain().getArch()) {
  2188. default:
  2189. break;
  2190. case llvm::Triple::mips:
  2191. case llvm::Triple::mipsel:
  2192. case llvm::Triple::mips64:
  2193. case llvm::Triple::mips64el:
  2194. if (Value == "--trap") {
  2195. CmdArgs.push_back("-target-feature");
  2196. CmdArgs.push_back("+use-tcc-in-div");
  2197. continue;
  2198. }
  2199. if (Value == "--break") {
  2200. CmdArgs.push_back("-target-feature");
  2201. CmdArgs.push_back("-use-tcc-in-div");
  2202. continue;
  2203. }
  2204. if (Value.startswith("-msoft-float")) {
  2205. CmdArgs.push_back("-target-feature");
  2206. CmdArgs.push_back("+soft-float");
  2207. continue;
  2208. }
  2209. if (Value.startswith("-mhard-float")) {
  2210. CmdArgs.push_back("-target-feature");
  2211. CmdArgs.push_back("-soft-float");
  2212. continue;
  2213. }
  2214. break;
  2215. }
  2216. if (Value == "-force_cpusubtype_ALL") {
  2217. // Do nothing, this is the default and we don't support anything else.
  2218. } else if (Value == "-L") {
  2219. CmdArgs.push_back("-msave-temp-labels");
  2220. } else if (Value == "--fatal-warnings") {
  2221. CmdArgs.push_back("-massembler-fatal-warnings");
  2222. } else if (Value == "--noexecstack") {
  2223. CmdArgs.push_back("-mnoexecstack");
  2224. } else if (Value == "-compress-debug-sections" ||
  2225. Value == "--compress-debug-sections") {
  2226. CompressDebugSections = true;
  2227. } else if (Value == "-nocompress-debug-sections" ||
  2228. Value == "--nocompress-debug-sections") {
  2229. CompressDebugSections = false;
  2230. } else if (Value.startswith("-I")) {
  2231. CmdArgs.push_back(Value.data());
  2232. // We need to consume the next argument if the current arg is a plain
  2233. // -I. The next arg will be the include directory.
  2234. if (Value == "-I")
  2235. TakeNextArg = true;
  2236. } else if (Value.startswith("-gdwarf-")) {
  2237. // "-gdwarf-N" options are not cc1as options.
  2238. unsigned DwarfVersion = DwarfVersionNum(Value);
  2239. if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
  2240. CmdArgs.push_back(Value.data());
  2241. } else {
  2242. RenderDebugEnablingArgs(
  2243. Args, CmdArgs, CodeGenOptions::LimitedDebugInfo, DwarfVersion);
  2244. }
  2245. } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
  2246. Value.startswith("-mhwdiv") || Value.startswith("-march")) {
  2247. // Do nothing, we'll validate it later.
  2248. } else {
  2249. D.Diag(diag::err_drv_unsupported_option_argument)
  2250. << A->getOption().getName() << Value;
  2251. }
  2252. }
  2253. }
  2254. if (CompressDebugSections) {
  2255. if (llvm::zlib::isAvailable())
  2256. CmdArgs.push_back("-compress-debug-sections");
  2257. else
  2258. D.Diag(diag::warn_debug_compression_unavailable);
  2259. }
  2260. }
  2261. // This adds the static libclang_rt.builtins-arch.a directly to the command line
  2262. // FIXME: Make sure we can also emit shared objects if they're requested
  2263. // and available, check for possible errors, etc.
  2264. static void addClangRT(const ToolChain &TC, const ArgList &Args,
  2265. ArgStringList &CmdArgs) {
  2266. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
  2267. }
  2268. namespace {
  2269. enum OpenMPRuntimeKind {
  2270. /// An unknown OpenMP runtime. We can't generate effective OpenMP code
  2271. /// without knowing what runtime to target.
  2272. OMPRT_Unknown,
  2273. /// The LLVM OpenMP runtime. When completed and integrated, this will become
  2274. /// the default for Clang.
  2275. OMPRT_OMP,
  2276. /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
  2277. /// this runtime but can swallow the pragmas, and find and link against the
  2278. /// runtime library itself.
  2279. OMPRT_GOMP,
  2280. /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
  2281. /// OpenMP runtime. We support this mode for users with existing dependencies
  2282. /// on this runtime library name.
  2283. OMPRT_IOMP5
  2284. };
  2285. }
  2286. /// Compute the desired OpenMP runtime from the flag provided.
  2287. static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
  2288. const ArgList &Args) {
  2289. StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
  2290. const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
  2291. if (A)
  2292. RuntimeName = A->getValue();
  2293. auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
  2294. .Case("libomp", OMPRT_OMP)
  2295. .Case("libgomp", OMPRT_GOMP)
  2296. .Case("libiomp5", OMPRT_IOMP5)
  2297. .Default(OMPRT_Unknown);
  2298. if (RT == OMPRT_Unknown) {
  2299. if (A)
  2300. TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
  2301. << A->getOption().getName() << A->getValue();
  2302. else
  2303. // FIXME: We could use a nicer diagnostic here.
  2304. TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
  2305. }
  2306. return RT;
  2307. }
  2308. static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
  2309. const ArgList &Args) {
  2310. if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  2311. options::OPT_fno_openmp, false))
  2312. return;
  2313. switch (getOpenMPRuntime(TC, Args)) {
  2314. case OMPRT_OMP:
  2315. CmdArgs.push_back("-lomp");
  2316. break;
  2317. case OMPRT_GOMP:
  2318. CmdArgs.push_back("-lgomp");
  2319. break;
  2320. case OMPRT_IOMP5:
  2321. CmdArgs.push_back("-liomp5");
  2322. break;
  2323. case OMPRT_Unknown:
  2324. // Already diagnosed.
  2325. break;
  2326. }
  2327. }
  2328. static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
  2329. ArgStringList &CmdArgs, StringRef Sanitizer,
  2330. bool IsShared) {
  2331. // Static runtimes must be forced into executable, so we wrap them in
  2332. // whole-archive.
  2333. if (!IsShared) CmdArgs.push_back("-whole-archive");
  2334. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
  2335. if (!IsShared) CmdArgs.push_back("-no-whole-archive");
  2336. }
  2337. // Tries to use a file with the list of dynamic symbols that need to be exported
  2338. // from the runtime library. Returns true if the file was found.
  2339. static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
  2340. ArgStringList &CmdArgs,
  2341. StringRef Sanitizer) {
  2342. SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
  2343. if (llvm::sys::fs::exists(SanRT + ".syms")) {
  2344. CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
  2345. return true;
  2346. }
  2347. return false;
  2348. }
  2349. static void linkSanitizerRuntimeDeps(const ToolChain &TC,
  2350. ArgStringList &CmdArgs) {
  2351. // Force linking against the system libraries sanitizers depends on
  2352. // (see PR15823 why this is necessary).
  2353. CmdArgs.push_back("--no-as-needed");
  2354. CmdArgs.push_back("-lpthread");
  2355. CmdArgs.push_back("-lrt");
  2356. CmdArgs.push_back("-lm");
  2357. // There's no libdl on FreeBSD.
  2358. if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
  2359. CmdArgs.push_back("-ldl");
  2360. }
  2361. static void
  2362. collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2363. SmallVectorImpl<StringRef> &SharedRuntimes,
  2364. SmallVectorImpl<StringRef> &StaticRuntimes,
  2365. SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
  2366. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  2367. // Collect shared runtimes.
  2368. if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
  2369. SharedRuntimes.push_back("asan");
  2370. }
  2371. // Collect static runtimes.
  2372. if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
  2373. // Don't link static runtimes into DSOs or if compiling for Android.
  2374. return;
  2375. }
  2376. if (SanArgs.needsAsanRt()) {
  2377. if (SanArgs.needsSharedAsanRt()) {
  2378. HelperStaticRuntimes.push_back("asan-preinit");
  2379. } else {
  2380. StaticRuntimes.push_back("asan");
  2381. if (SanArgs.linkCXXRuntimes())
  2382. StaticRuntimes.push_back("asan_cxx");
  2383. }
  2384. }
  2385. if (SanArgs.needsDfsanRt())
  2386. StaticRuntimes.push_back("dfsan");
  2387. if (SanArgs.needsLsanRt())
  2388. StaticRuntimes.push_back("lsan");
  2389. if (SanArgs.needsMsanRt()) {
  2390. StaticRuntimes.push_back("msan");
  2391. if (SanArgs.linkCXXRuntimes())
  2392. StaticRuntimes.push_back("msan_cxx");
  2393. }
  2394. if (SanArgs.needsTsanRt()) {
  2395. StaticRuntimes.push_back("tsan");
  2396. if (SanArgs.linkCXXRuntimes())
  2397. StaticRuntimes.push_back("tsan_cxx");
  2398. }
  2399. if (SanArgs.needsUbsanRt()) {
  2400. StaticRuntimes.push_back("ubsan_standalone");
  2401. if (SanArgs.linkCXXRuntimes())
  2402. StaticRuntimes.push_back("ubsan_standalone_cxx");
  2403. }
  2404. if (SanArgs.needsSafeStackRt())
  2405. StaticRuntimes.push_back("safestack");
  2406. }
  2407. // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
  2408. // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
  2409. static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2410. ArgStringList &CmdArgs) {
  2411. SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
  2412. HelperStaticRuntimes;
  2413. collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
  2414. HelperStaticRuntimes);
  2415. for (auto RT : SharedRuntimes)
  2416. addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
  2417. for (auto RT : HelperStaticRuntimes)
  2418. addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
  2419. bool AddExportDynamic = false;
  2420. for (auto RT : StaticRuntimes) {
  2421. addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
  2422. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  2423. }
  2424. // If there is a static runtime with no dynamic list, force all the symbols
  2425. // to be dynamic to be sure we export sanitizer interface functions.
  2426. if (AddExportDynamic)
  2427. CmdArgs.push_back("-export-dynamic");
  2428. return !StaticRuntimes.empty();
  2429. }
  2430. static bool areOptimizationsEnabled(const ArgList &Args) {
  2431. // Find the last -O arg and see if it is non-zero.
  2432. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2433. return !A->getOption().matches(options::OPT_O0);
  2434. // Defaults to -O0.
  2435. return false;
  2436. }
  2437. static bool shouldUseFramePointerForTarget(const ArgList &Args,
  2438. const llvm::Triple &Triple) {
  2439. switch (Triple.getArch()) {
  2440. case llvm::Triple::xcore:
  2441. case llvm::Triple::wasm32:
  2442. case llvm::Triple::wasm64:
  2443. // XCore never wants frame pointers, regardless of OS.
  2444. // WebAssembly never wants frame pointers.
  2445. return false;
  2446. default:
  2447. break;
  2448. }
  2449. if (Triple.isOSLinux()) {
  2450. switch (Triple.getArch()) {
  2451. // Don't use a frame pointer on linux if optimizing for certain targets.
  2452. case llvm::Triple::mips64:
  2453. case llvm::Triple::mips64el:
  2454. case llvm::Triple::mips:
  2455. case llvm::Triple::mipsel:
  2456. case llvm::Triple::systemz:
  2457. case llvm::Triple::x86:
  2458. case llvm::Triple::x86_64:
  2459. return !areOptimizationsEnabled(Args);
  2460. default:
  2461. return true;
  2462. }
  2463. }
  2464. if (Triple.isOSWindows()) {
  2465. switch (Triple.getArch()) {
  2466. case llvm::Triple::x86:
  2467. return !areOptimizationsEnabled(Args);
  2468. case llvm::Triple::arm:
  2469. case llvm::Triple::thumb:
  2470. // Windows on ARM builds with FPO disabled to aid fast stack walking
  2471. return true;
  2472. default:
  2473. // All other supported Windows ISAs use xdata unwind information, so frame
  2474. // pointers are not generally useful.
  2475. return false;
  2476. }
  2477. }
  2478. return true;
  2479. }
  2480. static bool shouldUseFramePointer(const ArgList &Args,
  2481. const llvm::Triple &Triple) {
  2482. if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
  2483. options::OPT_fomit_frame_pointer))
  2484. return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
  2485. if (Args.hasArg(options::OPT_pg))
  2486. return true;
  2487. return shouldUseFramePointerForTarget(Args, Triple);
  2488. }
  2489. static bool shouldUseLeafFramePointer(const ArgList &Args,
  2490. const llvm::Triple &Triple) {
  2491. if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
  2492. options::OPT_momit_leaf_frame_pointer))
  2493. return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
  2494. if (Args.hasArg(options::OPT_pg))
  2495. return true;
  2496. if (Triple.isPS4CPU())
  2497. return false;
  2498. return shouldUseFramePointerForTarget(Args, Triple);
  2499. }
  2500. /// Add a CC1 option to specify the debug compilation directory.
  2501. static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
  2502. SmallString<128> cwd;
  2503. if (!llvm::sys::fs::current_path(cwd)) {
  2504. CmdArgs.push_back("-fdebug-compilation-dir");
  2505. CmdArgs.push_back(Args.MakeArgString(cwd));
  2506. }
  2507. }
  2508. static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
  2509. Arg *FinalOutput = Args.getLastArg(options::OPT_o);
  2510. if (FinalOutput && Args.hasArg(options::OPT_c)) {
  2511. SmallString<128> T(FinalOutput->getValue());
  2512. llvm::sys::path::replace_extension(T, "dwo");
  2513. return Args.MakeArgString(T);
  2514. } else {
  2515. // Use the compilation dir.
  2516. SmallString<128> T(
  2517. Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
  2518. SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
  2519. llvm::sys::path::replace_extension(F, "dwo");
  2520. T += F;
  2521. return Args.MakeArgString(F);
  2522. }
  2523. }
  2524. static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
  2525. const JobAction &JA, const ArgList &Args,
  2526. const InputInfo &Output, const char *OutFile) {
  2527. ArgStringList ExtractArgs;
  2528. ExtractArgs.push_back("--extract-dwo");
  2529. ArgStringList StripArgs;
  2530. StripArgs.push_back("--strip-dwo");
  2531. // Grabbing the output of the earlier compile step.
  2532. StripArgs.push_back(Output.getFilename());
  2533. ExtractArgs.push_back(Output.getFilename());
  2534. ExtractArgs.push_back(OutFile);
  2535. const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
  2536. InputInfo II(Output.getFilename(), types::TY_Object, Output.getFilename());
  2537. // First extract the dwo sections.
  2538. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
  2539. // Then remove them from the original .o file.
  2540. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
  2541. }
  2542. /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
  2543. /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
  2544. static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
  2545. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  2546. if (A->getOption().matches(options::OPT_O4) ||
  2547. A->getOption().matches(options::OPT_Ofast))
  2548. return true;
  2549. if (A->getOption().matches(options::OPT_O0))
  2550. return false;
  2551. assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
  2552. // Vectorize -Os.
  2553. StringRef S(A->getValue());
  2554. if (S == "s")
  2555. return true;
  2556. // Don't vectorize -Oz, unless it's the slp vectorizer.
  2557. if (S == "z")
  2558. return isSlpVec;
  2559. unsigned OptLevel = 0;
  2560. if (S.getAsInteger(10, OptLevel))
  2561. return false;
  2562. return OptLevel > 1;
  2563. }
  2564. return false;
  2565. }
  2566. /// Add -x lang to \p CmdArgs for \p Input.
  2567. static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
  2568. ArgStringList &CmdArgs) {
  2569. // When using -verify-pch, we don't want to provide the type
  2570. // 'precompiled-header' if it was inferred from the file extension
  2571. if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
  2572. return;
  2573. CmdArgs.push_back("-x");
  2574. if (Args.hasArg(options::OPT_rewrite_objc))
  2575. CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
  2576. else
  2577. CmdArgs.push_back(types::getTypeName(Input.getType()));
  2578. }
  2579. static VersionTuple getMSCompatibilityVersion(unsigned Version) {
  2580. if (Version < 100)
  2581. return VersionTuple(Version);
  2582. if (Version < 10000)
  2583. return VersionTuple(Version / 100, Version % 100);
  2584. unsigned Build = 0, Factor = 1;
  2585. for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
  2586. Build = Build + (Version % 10) * Factor;
  2587. return VersionTuple(Version / 100, Version % 100, Build);
  2588. }
  2589. // Claim options we don't want to warn if they are unused. We do this for
  2590. // options that build systems might add but are unused when assembling or only
  2591. // running the preprocessor for example.
  2592. static void claimNoWarnArgs(const ArgList &Args) {
  2593. // Don't warn about unused -f(no-)?lto. This can happen when we're
  2594. // preprocessing, precompiling or assembling.
  2595. Args.ClaimAllArgs(options::OPT_flto_EQ);
  2596. Args.ClaimAllArgs(options::OPT_flto);
  2597. Args.ClaimAllArgs(options::OPT_fno_lto);
  2598. }
  2599. static void appendUserToPath(SmallVectorImpl<char> &Result) {
  2600. #ifdef LLVM_ON_UNIX
  2601. const char *Username = getenv("LOGNAME");
  2602. #else
  2603. const char *Username = getenv("USERNAME");
  2604. #endif
  2605. if (Username) {
  2606. // Validate that LoginName can be used in a path, and get its length.
  2607. size_t Len = 0;
  2608. for (const char *P = Username; *P; ++P, ++Len) {
  2609. if (!isAlphanumeric(*P) && *P != '_') {
  2610. Username = nullptr;
  2611. break;
  2612. }
  2613. }
  2614. if (Username && Len > 0) {
  2615. Result.append(Username, Username + Len);
  2616. return;
  2617. }
  2618. }
  2619. // Fallback to user id.
  2620. #ifdef LLVM_ON_UNIX
  2621. std::string UID = llvm::utostr(getuid());
  2622. #else
  2623. // FIXME: Windows seems to have an 'SID' that might work.
  2624. std::string UID = "9999";
  2625. #endif
  2626. Result.append(UID.begin(), UID.end());
  2627. }
  2628. VersionTuple visualstudio::getMSVCVersion(const Driver *D,
  2629. const llvm::Triple &Triple,
  2630. const llvm::opt::ArgList &Args,
  2631. bool IsWindowsMSVC) {
  2632. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  2633. IsWindowsMSVC) ||
  2634. Args.hasArg(options::OPT_fmsc_version) ||
  2635. Args.hasArg(options::OPT_fms_compatibility_version)) {
  2636. const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
  2637. const Arg *MSCompatibilityVersion =
  2638. Args.getLastArg(options::OPT_fms_compatibility_version);
  2639. if (MSCVersion && MSCompatibilityVersion) {
  2640. if (D)
  2641. D->Diag(diag::err_drv_argument_not_allowed_with)
  2642. << MSCVersion->getAsString(Args)
  2643. << MSCompatibilityVersion->getAsString(Args);
  2644. return VersionTuple();
  2645. }
  2646. if (MSCompatibilityVersion) {
  2647. VersionTuple MSVT;
  2648. if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
  2649. D->Diag(diag::err_drv_invalid_value)
  2650. << MSCompatibilityVersion->getAsString(Args)
  2651. << MSCompatibilityVersion->getValue();
  2652. return MSVT;
  2653. }
  2654. if (MSCVersion) {
  2655. unsigned Version = 0;
  2656. if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
  2657. D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
  2658. << MSCVersion->getValue();
  2659. return getMSCompatibilityVersion(Version);
  2660. }
  2661. unsigned Major, Minor, Micro;
  2662. Triple.getEnvironmentVersion(Major, Minor, Micro);
  2663. if (Major || Minor || Micro)
  2664. return VersionTuple(Major, Minor, Micro);
  2665. return VersionTuple(18);
  2666. }
  2667. return VersionTuple();
  2668. }
  2669. static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
  2670. const InputInfo &Output, const ArgList &Args,
  2671. ArgStringList &CmdArgs) {
  2672. auto *ProfileGenerateArg = Args.getLastArg(
  2673. options::OPT_fprofile_instr_generate,
  2674. options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
  2675. options::OPT_fprofile_generate_EQ,
  2676. options::OPT_fno_profile_instr_generate);
  2677. if (ProfileGenerateArg &&
  2678. ProfileGenerateArg->getOption().matches(
  2679. options::OPT_fno_profile_instr_generate))
  2680. ProfileGenerateArg = nullptr;
  2681. auto *ProfileUseArg = Args.getLastArg(
  2682. options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
  2683. options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
  2684. options::OPT_fno_profile_instr_use);
  2685. if (ProfileUseArg &&
  2686. ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
  2687. ProfileUseArg = nullptr;
  2688. if (ProfileGenerateArg && ProfileUseArg)
  2689. D.Diag(diag::err_drv_argument_not_allowed_with)
  2690. << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
  2691. if (ProfileGenerateArg) {
  2692. if (ProfileGenerateArg->getOption().matches(
  2693. options::OPT_fprofile_instr_generate_EQ))
  2694. ProfileGenerateArg->render(Args, CmdArgs);
  2695. else if (ProfileGenerateArg->getOption().matches(
  2696. options::OPT_fprofile_generate_EQ)) {
  2697. SmallString<128> Path(ProfileGenerateArg->getValue());
  2698. llvm::sys::path::append(Path, "default.profraw");
  2699. CmdArgs.push_back(
  2700. Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
  2701. } else
  2702. Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
  2703. }
  2704. if (ProfileUseArg) {
  2705. if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
  2706. ProfileUseArg->render(Args, CmdArgs);
  2707. else if ((ProfileUseArg->getOption().matches(
  2708. options::OPT_fprofile_use_EQ) ||
  2709. ProfileUseArg->getOption().matches(
  2710. options::OPT_fprofile_instr_use))) {
  2711. SmallString<128> Path(
  2712. ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
  2713. if (Path.empty() || llvm::sys::fs::is_directory(Path))
  2714. llvm::sys::path::append(Path, "default.profdata");
  2715. CmdArgs.push_back(
  2716. Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
  2717. }
  2718. }
  2719. if (Args.hasArg(options::OPT_ftest_coverage) ||
  2720. Args.hasArg(options::OPT_coverage))
  2721. CmdArgs.push_back("-femit-coverage-notes");
  2722. if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  2723. false) ||
  2724. Args.hasArg(options::OPT_coverage))
  2725. CmdArgs.push_back("-femit-coverage-data");
  2726. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  2727. options::OPT_fno_coverage_mapping, false) &&
  2728. !ProfileGenerateArg)
  2729. D.Diag(diag::err_drv_argument_only_allowed_with)
  2730. << "-fcoverage-mapping"
  2731. << "-fprofile-instr-generate";
  2732. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  2733. options::OPT_fno_coverage_mapping, false))
  2734. CmdArgs.push_back("-fcoverage-mapping");
  2735. if (C.getArgs().hasArg(options::OPT_c) ||
  2736. C.getArgs().hasArg(options::OPT_S)) {
  2737. if (Output.isFilename()) {
  2738. CmdArgs.push_back("-coverage-file");
  2739. SmallString<128> CoverageFilename;
  2740. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
  2741. CoverageFilename = FinalOutput->getValue();
  2742. } else {
  2743. CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
  2744. }
  2745. if (llvm::sys::path::is_relative(CoverageFilename)) {
  2746. SmallString<128> Pwd;
  2747. if (!llvm::sys::fs::current_path(Pwd)) {
  2748. llvm::sys::path::append(Pwd, CoverageFilename);
  2749. CoverageFilename.swap(Pwd);
  2750. }
  2751. }
  2752. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  2753. }
  2754. }
  2755. }
  2756. /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
  2757. /// smooshes them together with platform defaults, to decide whether
  2758. /// this compile should be using PIC mode or not. Returns a tuple of
  2759. /// (RelocationModel, PICLevel, IsPIE).
  2760. static std::tuple<llvm::Reloc::Model, unsigned, bool>
  2761. ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
  2762. const ArgList &Args) {
  2763. // FIXME: why does this code...and so much everywhere else, use both
  2764. // ToolChain.getTriple() and Triple?
  2765. bool PIE = ToolChain.isPIEDefault();
  2766. bool PIC = PIE || ToolChain.isPICDefault();
  2767. bool IsPICLevelTwo = PIC;
  2768. bool KernelOrKext =
  2769. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  2770. // Android-specific defaults for PIC/PIE
  2771. if (ToolChain.getTriple().isAndroid()) {
  2772. switch (ToolChain.getArch()) {
  2773. case llvm::Triple::arm:
  2774. case llvm::Triple::armeb:
  2775. case llvm::Triple::thumb:
  2776. case llvm::Triple::thumbeb:
  2777. case llvm::Triple::aarch64:
  2778. case llvm::Triple::mips:
  2779. case llvm::Triple::mipsel:
  2780. case llvm::Triple::mips64:
  2781. case llvm::Triple::mips64el:
  2782. PIC = true; // "-fpic"
  2783. break;
  2784. case llvm::Triple::x86:
  2785. case llvm::Triple::x86_64:
  2786. PIC = true; // "-fPIC"
  2787. IsPICLevelTwo = true;
  2788. break;
  2789. default:
  2790. break;
  2791. }
  2792. }
  2793. // OpenBSD-specific defaults for PIE
  2794. if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
  2795. switch (ToolChain.getArch()) {
  2796. case llvm::Triple::mips64:
  2797. case llvm::Triple::mips64el:
  2798. case llvm::Triple::sparcel:
  2799. case llvm::Triple::x86:
  2800. case llvm::Triple::x86_64:
  2801. IsPICLevelTwo = false; // "-fpie"
  2802. break;
  2803. case llvm::Triple::ppc:
  2804. case llvm::Triple::sparc:
  2805. case llvm::Triple::sparcv9:
  2806. IsPICLevelTwo = true; // "-fPIE"
  2807. break;
  2808. default:
  2809. break;
  2810. }
  2811. }
  2812. // The last argument relating to either PIC or PIE wins, and no
  2813. // other argument is used. If the last argument is any flavor of the
  2814. // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
  2815. // option implicitly enables PIC at the same level.
  2816. Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
  2817. options::OPT_fpic, options::OPT_fno_pic,
  2818. options::OPT_fPIE, options::OPT_fno_PIE,
  2819. options::OPT_fpie, options::OPT_fno_pie);
  2820. // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
  2821. // is forced, then neither PIC nor PIE flags will have no effect.
  2822. if (!ToolChain.isPICDefaultForced()) {
  2823. if (LastPICArg) {
  2824. Option O = LastPICArg->getOption();
  2825. if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
  2826. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
  2827. PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
  2828. PIC =
  2829. PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
  2830. IsPICLevelTwo =
  2831. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
  2832. } else {
  2833. PIE = PIC = false;
  2834. if (Triple.isPS4CPU()) {
  2835. Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
  2836. StringRef Model = ModelArg ? ModelArg->getValue() : "";
  2837. if (Model != "kernel") {
  2838. PIC = true;
  2839. ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
  2840. << LastPICArg->getSpelling();
  2841. }
  2842. }
  2843. }
  2844. }
  2845. }
  2846. // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
  2847. // PIC level would've been set to level 1, force it back to level 2 PIC
  2848. // instead.
  2849. if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
  2850. IsPICLevelTwo |= ToolChain.isPICDefault();
  2851. // This kernel flags are a trump-card: they will disable PIC/PIE
  2852. // generation, independent of the argument order.
  2853. if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  2854. !Triple.isWatchOS()))
  2855. PIC = PIE = false;
  2856. if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
  2857. // This is a very special mode. It trumps the other modes, almost no one
  2858. // uses it, and it isn't even valid on any OS but Darwin.
  2859. if (!ToolChain.getTriple().isOSDarwin())
  2860. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  2861. << A->getSpelling() << ToolChain.getTriple().str();
  2862. // FIXME: Warn when this flag trumps some other PIC or PIE flag.
  2863. // Only a forced PIC mode can cause the actual compile to have PIC defines
  2864. // etc., no flags are sufficient. This behavior was selected to closely
  2865. // match that of llvm-gcc and Apple GCC before that.
  2866. PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
  2867. return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
  2868. }
  2869. if (PIC)
  2870. return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
  2871. return std::make_tuple(llvm::Reloc::Static, 0, false);
  2872. }
  2873. static const char *RelocationModelName(llvm::Reloc::Model Model) {
  2874. switch (Model) {
  2875. case llvm::Reloc::Default:
  2876. return nullptr;
  2877. case llvm::Reloc::Static:
  2878. return "static";
  2879. case llvm::Reloc::PIC_:
  2880. return "pic";
  2881. case llvm::Reloc::DynamicNoPIC:
  2882. return "dynamic-no-pic";
  2883. }
  2884. llvm_unreachable("Unknown Reloc::Model kind");
  2885. }
  2886. static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
  2887. ArgStringList &CmdArgs) {
  2888. llvm::Reloc::Model RelocationModel;
  2889. unsigned PICLevel;
  2890. bool IsPIE;
  2891. std::tie(RelocationModel, PICLevel, IsPIE) =
  2892. ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
  2893. if (RelocationModel != llvm::Reloc::Static)
  2894. CmdArgs.push_back("-KPIC");
  2895. }
  2896. void Clang::ConstructJob(Compilation &C, const JobAction &JA,
  2897. const InputInfo &Output, const InputInfoList &Inputs,
  2898. const ArgList &Args, const char *LinkingOutput) const {
  2899. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  2900. const llvm::Triple Triple(TripleStr);
  2901. bool KernelOrKext =
  2902. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  2903. const Driver &D = getToolChain().getDriver();
  2904. ArgStringList CmdArgs;
  2905. bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
  2906. bool IsWindowsCygnus =
  2907. getToolChain().getTriple().isWindowsCygwinEnvironment();
  2908. bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
  2909. bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
  2910. // Check number of inputs for sanity. We need at least one input.
  2911. assert(Inputs.size() >= 1 && "Must have at least one input.");
  2912. const InputInfo &Input = Inputs[0];
  2913. // CUDA compilation may have multiple inputs (source file + results of
  2914. // device-side compilations). All other jobs are expected to have exactly one
  2915. // input.
  2916. bool IsCuda = types::isCuda(Input.getType());
  2917. assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
  2918. // Invoke ourselves in -cc1 mode.
  2919. //
  2920. // FIXME: Implement custom jobs for internal actions.
  2921. CmdArgs.push_back("-cc1");
  2922. // Add the "effective" target triple.
  2923. CmdArgs.push_back("-triple");
  2924. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  2925. const ToolChain *AuxToolChain = nullptr;
  2926. if (IsCuda) {
  2927. // FIXME: We need a (better) way to pass information about
  2928. // particular compilation pass we're constructing here. For now we
  2929. // can check which toolchain we're using and pick the other one to
  2930. // extract the triple.
  2931. if (&getToolChain() == C.getCudaDeviceToolChain())
  2932. AuxToolChain = C.getCudaHostToolChain();
  2933. else if (&getToolChain() == C.getCudaHostToolChain())
  2934. AuxToolChain = C.getCudaDeviceToolChain();
  2935. else
  2936. llvm_unreachable("Can't figure out CUDA compilation mode.");
  2937. assert(AuxToolChain != nullptr && "No aux toolchain.");
  2938. CmdArgs.push_back("-aux-triple");
  2939. CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
  2940. CmdArgs.push_back("-fcuda-target-overloads");
  2941. CmdArgs.push_back("-fcuda-disable-target-call-checks");
  2942. }
  2943. if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
  2944. Triple.getArch() == llvm::Triple::thumb)) {
  2945. unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
  2946. unsigned Version;
  2947. Triple.getArchName().substr(Offset).getAsInteger(10, Version);
  2948. if (Version < 7)
  2949. D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
  2950. << TripleStr;
  2951. }
  2952. // Push all default warning arguments that are specific to
  2953. // the given target. These come before user provided warning options
  2954. // are provided.
  2955. getToolChain().addClangWarningOptions(CmdArgs);
  2956. // Select the appropriate action.
  2957. RewriteKind rewriteKind = RK_None;
  2958. if (isa<AnalyzeJobAction>(JA)) {
  2959. assert(JA.getType() == types::TY_Plist && "Invalid output type.");
  2960. CmdArgs.push_back("-analyze");
  2961. } else if (isa<MigrateJobAction>(JA)) {
  2962. CmdArgs.push_back("-migrate");
  2963. } else if (isa<PreprocessJobAction>(JA)) {
  2964. if (Output.getType() == types::TY_Dependencies)
  2965. CmdArgs.push_back("-Eonly");
  2966. else {
  2967. CmdArgs.push_back("-E");
  2968. if (Args.hasArg(options::OPT_rewrite_objc) &&
  2969. !Args.hasArg(options::OPT_g_Group))
  2970. CmdArgs.push_back("-P");
  2971. }
  2972. } else if (isa<AssembleJobAction>(JA)) {
  2973. CmdArgs.push_back("-emit-obj");
  2974. CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
  2975. // Also ignore explicit -force_cpusubtype_ALL option.
  2976. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  2977. } else if (isa<PrecompileJobAction>(JA)) {
  2978. // Use PCH if the user requested it.
  2979. bool UsePCH = D.CCCUsePCH;
  2980. if (JA.getType() == types::TY_Nothing)
  2981. CmdArgs.push_back("-fsyntax-only");
  2982. else if (UsePCH)
  2983. CmdArgs.push_back("-emit-pch");
  2984. else
  2985. CmdArgs.push_back("-emit-pth");
  2986. } else if (isa<VerifyPCHJobAction>(JA)) {
  2987. CmdArgs.push_back("-verify-pch");
  2988. } else {
  2989. assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
  2990. "Invalid action for clang tool.");
  2991. if (JA.getType() == types::TY_Nothing) {
  2992. CmdArgs.push_back("-fsyntax-only");
  2993. } else if (JA.getType() == types::TY_LLVM_IR ||
  2994. JA.getType() == types::TY_LTO_IR) {
  2995. CmdArgs.push_back("-emit-llvm");
  2996. } else if (JA.getType() == types::TY_LLVM_BC ||
  2997. JA.getType() == types::TY_LTO_BC) {
  2998. CmdArgs.push_back("-emit-llvm-bc");
  2999. } else if (JA.getType() == types::TY_PP_Asm) {
  3000. CmdArgs.push_back("-S");
  3001. } else if (JA.getType() == types::TY_AST) {
  3002. CmdArgs.push_back("-emit-pch");
  3003. } else if (JA.getType() == types::TY_ModuleFile) {
  3004. CmdArgs.push_back("-module-file-info");
  3005. } else if (JA.getType() == types::TY_RewrittenObjC) {
  3006. CmdArgs.push_back("-rewrite-objc");
  3007. rewriteKind = RK_NonFragile;
  3008. } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
  3009. CmdArgs.push_back("-rewrite-objc");
  3010. rewriteKind = RK_Fragile;
  3011. } else {
  3012. assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
  3013. }
  3014. // Preserve use-list order by default when emitting bitcode, so that
  3015. // loading the bitcode up in 'opt' or 'llc' and running passes gives the
  3016. // same result as running passes here. For LTO, we don't need to preserve
  3017. // the use-list order, since serialization to bitcode is part of the flow.
  3018. if (JA.getType() == types::TY_LLVM_BC)
  3019. CmdArgs.push_back("-emit-llvm-uselists");
  3020. if (D.isUsingLTO())
  3021. Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
  3022. }
  3023. // We normally speed up the clang process a bit by skipping destructors at
  3024. // exit, but when we're generating diagnostics we can rely on some of the
  3025. // cleanup.
  3026. if (!C.isForDiagnostics())
  3027. CmdArgs.push_back("-disable-free");
  3028. // Disable the verification pass in -asserts builds.
  3029. #ifdef NDEBUG
  3030. CmdArgs.push_back("-disable-llvm-verifier");
  3031. #endif
  3032. // Set the main file name, so that debug info works even with
  3033. // -save-temps.
  3034. CmdArgs.push_back("-main-file-name");
  3035. CmdArgs.push_back(getBaseInputName(Args, Input));
  3036. // Some flags which affect the language (via preprocessor
  3037. // defines).
  3038. if (Args.hasArg(options::OPT_static))
  3039. CmdArgs.push_back("-static-define");
  3040. if (isa<AnalyzeJobAction>(JA)) {
  3041. // Enable region store model by default.
  3042. CmdArgs.push_back("-analyzer-store=region");
  3043. // Treat blocks as analysis entry points.
  3044. CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
  3045. CmdArgs.push_back("-analyzer-eagerly-assume");
  3046. // Add default argument set.
  3047. if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
  3048. CmdArgs.push_back("-analyzer-checker=core");
  3049. if (!IsWindowsMSVC)
  3050. CmdArgs.push_back("-analyzer-checker=unix");
  3051. if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
  3052. CmdArgs.push_back("-analyzer-checker=osx");
  3053. CmdArgs.push_back("-analyzer-checker=deadcode");
  3054. if (types::isCXX(Input.getType()))
  3055. CmdArgs.push_back("-analyzer-checker=cplusplus");
  3056. // Enable the following experimental checkers for testing.
  3057. CmdArgs.push_back(
  3058. "-analyzer-checker=security.insecureAPI.UncheckedReturn");
  3059. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
  3060. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
  3061. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
  3062. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
  3063. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
  3064. // Default nullability checks.
  3065. CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
  3066. CmdArgs.push_back(
  3067. "-analyzer-checker=nullability.NullReturnedFromNonnull");
  3068. }
  3069. // Set the output format. The default is plist, for (lame) historical
  3070. // reasons.
  3071. CmdArgs.push_back("-analyzer-output");
  3072. if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
  3073. CmdArgs.push_back(A->getValue());
  3074. else
  3075. CmdArgs.push_back("plist");
  3076. // Disable the presentation of standard compiler warnings when
  3077. // using --analyze. We only want to show static analyzer diagnostics
  3078. // or frontend errors.
  3079. CmdArgs.push_back("-w");
  3080. // Add -Xanalyzer arguments when running as analyzer.
  3081. Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
  3082. }
  3083. CheckCodeGenerationOptions(D, Args);
  3084. llvm::Reloc::Model RelocationModel;
  3085. unsigned PICLevel;
  3086. bool IsPIE;
  3087. std::tie(RelocationModel, PICLevel, IsPIE) =
  3088. ParsePICArgs(getToolChain(), Triple, Args);
  3089. const char *RMName = RelocationModelName(RelocationModel);
  3090. if (RMName) {
  3091. CmdArgs.push_back("-mrelocation-model");
  3092. CmdArgs.push_back(RMName);
  3093. }
  3094. if (PICLevel > 0) {
  3095. CmdArgs.push_back("-pic-level");
  3096. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3097. if (IsPIE) {
  3098. CmdArgs.push_back("-pie-level");
  3099. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3100. }
  3101. }
  3102. if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
  3103. CmdArgs.push_back("-meabi");
  3104. CmdArgs.push_back(A->getValue());
  3105. }
  3106. CmdArgs.push_back("-mthread-model");
  3107. if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
  3108. CmdArgs.push_back(A->getValue());
  3109. else
  3110. CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
  3111. Args.AddLastArg(CmdArgs, options::OPT_fveclib);
  3112. if (!Args.hasFlag(options::OPT_fmerge_all_constants,
  3113. options::OPT_fno_merge_all_constants))
  3114. CmdArgs.push_back("-fno-merge-all-constants");
  3115. // LLVM Code Generator Options.
  3116. if (Args.hasArg(options::OPT_frewrite_map_file) ||
  3117. Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
  3118. for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
  3119. options::OPT_frewrite_map_file_EQ)) {
  3120. CmdArgs.push_back("-frewrite-map-file");
  3121. CmdArgs.push_back(A->getValue());
  3122. A->claim();
  3123. }
  3124. }
  3125. if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
  3126. StringRef v = A->getValue();
  3127. CmdArgs.push_back("-mllvm");
  3128. CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
  3129. A->claim();
  3130. }
  3131. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  3132. CmdArgs.push_back("-mregparm");
  3133. CmdArgs.push_back(A->getValue());
  3134. }
  3135. if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
  3136. options::OPT_freg_struct_return)) {
  3137. if (getToolChain().getArch() != llvm::Triple::x86) {
  3138. D.Diag(diag::err_drv_unsupported_opt_for_target)
  3139. << A->getSpelling() << getToolChain().getTriple().str();
  3140. } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
  3141. CmdArgs.push_back("-fpcc-struct-return");
  3142. } else {
  3143. assert(A->getOption().matches(options::OPT_freg_struct_return));
  3144. CmdArgs.push_back("-freg-struct-return");
  3145. }
  3146. }
  3147. if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
  3148. CmdArgs.push_back("-mrtd");
  3149. if (shouldUseFramePointer(Args, getToolChain().getTriple()))
  3150. CmdArgs.push_back("-mdisable-fp-elim");
  3151. if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
  3152. options::OPT_fno_zero_initialized_in_bss))
  3153. CmdArgs.push_back("-mno-zero-initialized-in-bss");
  3154. bool OFastEnabled = isOptimizationLevelFast(Args);
  3155. // If -Ofast is the optimization level, then -fstrict-aliasing should be
  3156. // enabled. This alias option is being used to simplify the hasFlag logic.
  3157. OptSpecifier StrictAliasingAliasOption =
  3158. OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
  3159. // We turn strict aliasing off by default if we're in CL mode, since MSVC
  3160. // doesn't do any TBAA.
  3161. bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
  3162. if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
  3163. options::OPT_fno_strict_aliasing, TBAAOnByDefault))
  3164. CmdArgs.push_back("-relaxed-aliasing");
  3165. if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
  3166. options::OPT_fno_struct_path_tbaa))
  3167. CmdArgs.push_back("-no-struct-path-tbaa");
  3168. if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
  3169. false))
  3170. CmdArgs.push_back("-fstrict-enums");
  3171. if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
  3172. options::OPT_fno_strict_vtable_pointers,
  3173. false))
  3174. CmdArgs.push_back("-fstrict-vtable-pointers");
  3175. if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
  3176. options::OPT_fno_optimize_sibling_calls))
  3177. CmdArgs.push_back("-mdisable-tail-calls");
  3178. // Handle segmented stacks.
  3179. if (Args.hasArg(options::OPT_fsplit_stack))
  3180. CmdArgs.push_back("-split-stacks");
  3181. // If -Ofast is the optimization level, then -ffast-math should be enabled.
  3182. // This alias option is being used to simplify the getLastArg logic.
  3183. OptSpecifier FastMathAliasOption =
  3184. OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
  3185. // Handle various floating point optimization flags, mapping them to the
  3186. // appropriate LLVM code generation flags. The pattern for all of these is to
  3187. // default off the codegen optimizations, and if any flag enables them and no
  3188. // flag disables them after the flag enabling them, enable the codegen
  3189. // optimization. This is complicated by several "umbrella" flags.
  3190. if (Arg *A = Args.getLastArg(
  3191. options::OPT_ffast_math, FastMathAliasOption,
  3192. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3193. options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
  3194. options::OPT_fno_honor_infinities))
  3195. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3196. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3197. A->getOption().getID() != options::OPT_fhonor_infinities)
  3198. CmdArgs.push_back("-menable-no-infs");
  3199. if (Arg *A = Args.getLastArg(
  3200. options::OPT_ffast_math, FastMathAliasOption,
  3201. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3202. options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
  3203. options::OPT_fno_honor_nans))
  3204. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3205. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3206. A->getOption().getID() != options::OPT_fhonor_nans)
  3207. CmdArgs.push_back("-menable-no-nans");
  3208. // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
  3209. bool MathErrno = getToolChain().IsMathErrnoDefault();
  3210. if (Arg *A =
  3211. Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3212. options::OPT_fno_fast_math, options::OPT_fmath_errno,
  3213. options::OPT_fno_math_errno)) {
  3214. // Turning on -ffast_math (with either flag) removes the need for MathErrno.
  3215. // However, turning *off* -ffast_math merely restores the toolchain default
  3216. // (which may be false).
  3217. if (A->getOption().getID() == options::OPT_fno_math_errno ||
  3218. A->getOption().getID() == options::OPT_ffast_math ||
  3219. A->getOption().getID() == options::OPT_Ofast)
  3220. MathErrno = false;
  3221. else if (A->getOption().getID() == options::OPT_fmath_errno)
  3222. MathErrno = true;
  3223. }
  3224. if (MathErrno)
  3225. CmdArgs.push_back("-fmath-errno");
  3226. // There are several flags which require disabling very specific
  3227. // optimizations. Any of these being disabled forces us to turn off the
  3228. // entire set of LLVM optimizations, so collect them through all the flag
  3229. // madness.
  3230. bool AssociativeMath = false;
  3231. if (Arg *A = Args.getLastArg(
  3232. options::OPT_ffast_math, FastMathAliasOption,
  3233. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3234. options::OPT_fno_unsafe_math_optimizations,
  3235. options::OPT_fassociative_math, options::OPT_fno_associative_math))
  3236. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3237. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3238. A->getOption().getID() != options::OPT_fno_associative_math)
  3239. AssociativeMath = true;
  3240. bool ReciprocalMath = false;
  3241. if (Arg *A = Args.getLastArg(
  3242. options::OPT_ffast_math, FastMathAliasOption,
  3243. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3244. options::OPT_fno_unsafe_math_optimizations,
  3245. options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
  3246. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3247. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3248. A->getOption().getID() != options::OPT_fno_reciprocal_math)
  3249. ReciprocalMath = true;
  3250. bool SignedZeros = true;
  3251. if (Arg *A = Args.getLastArg(
  3252. options::OPT_ffast_math, FastMathAliasOption,
  3253. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3254. options::OPT_fno_unsafe_math_optimizations,
  3255. options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
  3256. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3257. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3258. A->getOption().getID() != options::OPT_fsigned_zeros)
  3259. SignedZeros = false;
  3260. bool TrappingMath = true;
  3261. if (Arg *A = Args.getLastArg(
  3262. options::OPT_ffast_math, FastMathAliasOption,
  3263. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3264. options::OPT_fno_unsafe_math_optimizations,
  3265. options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
  3266. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3267. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3268. A->getOption().getID() != options::OPT_ftrapping_math)
  3269. TrappingMath = false;
  3270. if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
  3271. !TrappingMath)
  3272. CmdArgs.push_back("-menable-unsafe-fp-math");
  3273. if (!SignedZeros)
  3274. CmdArgs.push_back("-fno-signed-zeros");
  3275. if (ReciprocalMath)
  3276. CmdArgs.push_back("-freciprocal-math");
  3277. // Validate and pass through -fp-contract option.
  3278. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3279. options::OPT_fno_fast_math,
  3280. options::OPT_ffp_contract)) {
  3281. if (A->getOption().getID() == options::OPT_ffp_contract) {
  3282. StringRef Val = A->getValue();
  3283. if (Val == "fast" || Val == "on" || Val == "off") {
  3284. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
  3285. } else {
  3286. D.Diag(diag::err_drv_unsupported_option_argument)
  3287. << A->getOption().getName() << Val;
  3288. }
  3289. } else if (A->getOption().matches(options::OPT_ffast_math) ||
  3290. (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
  3291. // If fast-math is set then set the fp-contract mode to fast.
  3292. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
  3293. }
  3294. }
  3295. ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
  3296. // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
  3297. // and if we find them, tell the frontend to provide the appropriate
  3298. // preprocessor macros. This is distinct from enabling any optimizations as
  3299. // these options induce language changes which must survive serialization
  3300. // and deserialization, etc.
  3301. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3302. options::OPT_fno_fast_math))
  3303. if (!A->getOption().matches(options::OPT_fno_fast_math))
  3304. CmdArgs.push_back("-ffast-math");
  3305. if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
  3306. options::OPT_fno_fast_math))
  3307. if (A->getOption().matches(options::OPT_ffinite_math_only))
  3308. CmdArgs.push_back("-ffinite-math-only");
  3309. // Decide whether to use verbose asm. Verbose assembly is the default on
  3310. // toolchains which have the integrated assembler on by default.
  3311. bool IsIntegratedAssemblerDefault =
  3312. getToolChain().IsIntegratedAssemblerDefault();
  3313. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  3314. IsIntegratedAssemblerDefault) ||
  3315. Args.hasArg(options::OPT_dA))
  3316. CmdArgs.push_back("-masm-verbose");
  3317. if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
  3318. IsIntegratedAssemblerDefault))
  3319. CmdArgs.push_back("-no-integrated-as");
  3320. if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
  3321. CmdArgs.push_back("-mdebug-pass");
  3322. CmdArgs.push_back("Structure");
  3323. }
  3324. if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
  3325. CmdArgs.push_back("-mdebug-pass");
  3326. CmdArgs.push_back("Arguments");
  3327. }
  3328. // Enable -mconstructor-aliases except on darwin, where we have to
  3329. // work around a linker bug; see <rdar://problem/7651567>.
  3330. if (!getToolChain().getTriple().isOSDarwin())
  3331. CmdArgs.push_back("-mconstructor-aliases");
  3332. // Darwin's kernel doesn't support guard variables; just die if we
  3333. // try to use them.
  3334. if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
  3335. CmdArgs.push_back("-fforbid-guard-variables");
  3336. if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
  3337. false)) {
  3338. CmdArgs.push_back("-mms-bitfields");
  3339. }
  3340. // This is a coarse approximation of what llvm-gcc actually does, both
  3341. // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
  3342. // complicated ways.
  3343. bool AsynchronousUnwindTables =
  3344. Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
  3345. options::OPT_fno_asynchronous_unwind_tables,
  3346. (getToolChain().IsUnwindTablesDefault() ||
  3347. getToolChain().getSanitizerArgs().needsUnwindTables()) &&
  3348. !KernelOrKext);
  3349. if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
  3350. AsynchronousUnwindTables))
  3351. CmdArgs.push_back("-munwind-tables");
  3352. getToolChain().addClangTargetOptions(Args, CmdArgs);
  3353. if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
  3354. CmdArgs.push_back("-mlimit-float-precision");
  3355. CmdArgs.push_back(A->getValue());
  3356. }
  3357. // FIXME: Handle -mtune=.
  3358. (void)Args.hasArg(options::OPT_mtune_EQ);
  3359. if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
  3360. CmdArgs.push_back("-mcode-model");
  3361. CmdArgs.push_back(A->getValue());
  3362. }
  3363. // Add the target cpu
  3364. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
  3365. if (!CPU.empty()) {
  3366. CmdArgs.push_back("-target-cpu");
  3367. CmdArgs.push_back(Args.MakeArgString(CPU));
  3368. }
  3369. if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
  3370. CmdArgs.push_back("-mfpmath");
  3371. CmdArgs.push_back(A->getValue());
  3372. }
  3373. // Add the target features
  3374. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
  3375. // Add target specific flags.
  3376. switch (getToolChain().getArch()) {
  3377. default:
  3378. break;
  3379. case llvm::Triple::arm:
  3380. case llvm::Triple::armeb:
  3381. case llvm::Triple::thumb:
  3382. case llvm::Triple::thumbeb:
  3383. // Use the effective triple, which takes into account the deployment target.
  3384. AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
  3385. break;
  3386. case llvm::Triple::aarch64:
  3387. case llvm::Triple::aarch64_be:
  3388. AddAArch64TargetArgs(Args, CmdArgs);
  3389. break;
  3390. case llvm::Triple::mips:
  3391. case llvm::Triple::mipsel:
  3392. case llvm::Triple::mips64:
  3393. case llvm::Triple::mips64el:
  3394. AddMIPSTargetArgs(Args, CmdArgs);
  3395. break;
  3396. case llvm::Triple::ppc:
  3397. case llvm::Triple::ppc64:
  3398. case llvm::Triple::ppc64le:
  3399. AddPPCTargetArgs(Args, CmdArgs);
  3400. break;
  3401. case llvm::Triple::sparc:
  3402. case llvm::Triple::sparcel:
  3403. case llvm::Triple::sparcv9:
  3404. AddSparcTargetArgs(Args, CmdArgs);
  3405. break;
  3406. case llvm::Triple::x86:
  3407. case llvm::Triple::x86_64:
  3408. AddX86TargetArgs(Args, CmdArgs);
  3409. break;
  3410. case llvm::Triple::hexagon:
  3411. AddHexagonTargetArgs(Args, CmdArgs);
  3412. break;
  3413. }
  3414. // The 'g' groups options involve a somewhat intricate sequence of decisions
  3415. // about what to pass from the driver to the frontend, but by the time they
  3416. // reach cc1 they've been factored into two well-defined orthogonal choices:
  3417. // * what level of debug info to generate
  3418. // * what dwarf version to write
  3419. // This avoids having to monkey around further in cc1 other than to disable
  3420. // codeview if not running in a Windows environment. Perhaps even that
  3421. // decision should be made in the driver as well though.
  3422. enum CodeGenOptions::DebugInfoKind DebugInfoKind =
  3423. CodeGenOptions::NoDebugInfo;
  3424. // These two are potentially updated by AddClangCLArgs.
  3425. unsigned DwarfVersion = 0;
  3426. bool EmitCodeView = false;
  3427. // Add clang-cl arguments.
  3428. if (getToolChain().getDriver().IsCLMode())
  3429. AddClangCLArgs(Args, CmdArgs, &DebugInfoKind, &EmitCodeView);
  3430. // Pass the linker version in use.
  3431. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  3432. CmdArgs.push_back("-target-linker-version");
  3433. CmdArgs.push_back(A->getValue());
  3434. }
  3435. if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
  3436. CmdArgs.push_back("-momit-leaf-frame-pointer");
  3437. // Explicitly error on some things we know we don't support and can't just
  3438. // ignore.
  3439. types::ID InputType = Input.getType();
  3440. if (!Args.hasArg(options::OPT_fallow_unsupported)) {
  3441. Arg *Unsupported;
  3442. if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
  3443. getToolChain().getArch() == llvm::Triple::x86) {
  3444. if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
  3445. (Unsupported = Args.getLastArg(options::OPT_mkernel)))
  3446. D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
  3447. << Unsupported->getOption().getName();
  3448. }
  3449. }
  3450. Args.AddAllArgs(CmdArgs, options::OPT_v);
  3451. Args.AddLastArg(CmdArgs, options::OPT_H);
  3452. if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
  3453. CmdArgs.push_back("-header-include-file");
  3454. CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
  3455. : "-");
  3456. }
  3457. Args.AddLastArg(CmdArgs, options::OPT_P);
  3458. Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
  3459. if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
  3460. CmdArgs.push_back("-diagnostic-log-file");
  3461. CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
  3462. : "-");
  3463. }
  3464. Args.ClaimAllArgs(options::OPT_g_Group);
  3465. Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
  3466. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  3467. // If you say "-gline-tables-only -gsplit-dwarf", split-dwarf wins,
  3468. // which mandates turning on "-g". But -split-dwarf is not a g_group option,
  3469. // hence it takes a nontrivial test to decide about line-tables-only.
  3470. if (A->getOption().matches(options::OPT_gline_tables_only) &&
  3471. (!SplitDwarfArg || A->getIndex() > SplitDwarfArg->getIndex())) {
  3472. DebugInfoKind = CodeGenOptions::DebugLineTablesOnly;
  3473. SplitDwarfArg = nullptr;
  3474. } else if (!A->getOption().matches(options::OPT_g0)) {
  3475. // Some 'g' group option other than one expressly disabling debug info
  3476. // must have been the final (winning) one. They're all equivalent.
  3477. DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
  3478. }
  3479. }
  3480. // If a -gdwarf argument appeared, use it, unless DebugInfoKind is None
  3481. // (because that would mean that "-g0" was the rightmost 'g' group option).
  3482. // FIXME: specifying "-gdwarf-<N>" "-g1" in that order works,
  3483. // but "-g1" "-gdwarf-<N>" does not. A deceptively simple (but wrong) "fix"
  3484. // exists of removing the gdwarf options from the g_group.
  3485. if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
  3486. options::OPT_gdwarf_4))
  3487. DwarfVersion = DwarfVersionNum(A->getSpelling());
  3488. // Forward -gcodeview.
  3489. // 'EmitCodeView might have been set by CL-compatibility argument parsing.
  3490. if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
  3491. // DwarfVersion remains at 0 if no explicit choice was made.
  3492. CmdArgs.push_back("-gcodeview");
  3493. } else if (DwarfVersion == 0 &&
  3494. DebugInfoKind != CodeGenOptions::NoDebugInfo) {
  3495. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  3496. }
  3497. // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
  3498. Args.ClaimAllArgs(options::OPT_g_flags_Group);
  3499. // PS4 defaults to no column info
  3500. if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
  3501. /*Default=*/ !IsPS4CPU))
  3502. CmdArgs.push_back("-dwarf-column-info");
  3503. // FIXME: Move backend command line options to the module.
  3504. if (Args.hasArg(options::OPT_gmodules)) {
  3505. DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
  3506. CmdArgs.push_back("-dwarf-ext-refs");
  3507. CmdArgs.push_back("-fmodule-format=obj");
  3508. }
  3509. // -gsplit-dwarf should turn on -g and enable the backend dwarf
  3510. // splitting and extraction.
  3511. // FIXME: Currently only works on Linux.
  3512. if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
  3513. DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
  3514. CmdArgs.push_back("-backend-option");
  3515. CmdArgs.push_back("-split-dwarf=Enable");
  3516. }
  3517. // After we've dealt with all combinations of things that could
  3518. // make DebugInfoKind be other than None or DebugLineTablesOnly,
  3519. // figure out if we need to "upgrade" it to standalone debug info.
  3520. // We parse these two '-f' options whether or not they will be used,
  3521. // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
  3522. bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
  3523. options::OPT_fno_standalone_debug,
  3524. getToolChain().GetDefaultStandaloneDebug());
  3525. if (DebugInfoKind == CodeGenOptions::LimitedDebugInfo && NeedFullDebug)
  3526. DebugInfoKind = CodeGenOptions::FullDebugInfo;
  3527. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion);
  3528. // -ggnu-pubnames turns on gnu style pubnames in the backend.
  3529. if (Args.hasArg(options::OPT_ggnu_pubnames)) {
  3530. CmdArgs.push_back("-backend-option");
  3531. CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
  3532. }
  3533. // -gdwarf-aranges turns on the emission of the aranges section in the
  3534. // backend.
  3535. // Always enabled on the PS4.
  3536. if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
  3537. CmdArgs.push_back("-backend-option");
  3538. CmdArgs.push_back("-generate-arange-section");
  3539. }
  3540. if (Args.hasFlag(options::OPT_fdebug_types_section,
  3541. options::OPT_fno_debug_types_section, false)) {
  3542. CmdArgs.push_back("-backend-option");
  3543. CmdArgs.push_back("-generate-type-units");
  3544. }
  3545. // CloudABI uses -ffunction-sections and -fdata-sections by default.
  3546. bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI;
  3547. if (Args.hasFlag(options::OPT_ffunction_sections,
  3548. options::OPT_fno_function_sections, UseSeparateSections)) {
  3549. CmdArgs.push_back("-ffunction-sections");
  3550. }
  3551. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  3552. UseSeparateSections)) {
  3553. CmdArgs.push_back("-fdata-sections");
  3554. }
  3555. if (!Args.hasFlag(options::OPT_funique_section_names,
  3556. options::OPT_fno_unique_section_names, true))
  3557. CmdArgs.push_back("-fno-unique-section-names");
  3558. Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
  3559. addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
  3560. // Pass options for controlling the default header search paths.
  3561. if (Args.hasArg(options::OPT_nostdinc)) {
  3562. CmdArgs.push_back("-nostdsysteminc");
  3563. CmdArgs.push_back("-nobuiltininc");
  3564. } else {
  3565. if (Args.hasArg(options::OPT_nostdlibinc))
  3566. CmdArgs.push_back("-nostdsysteminc");
  3567. Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
  3568. Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
  3569. }
  3570. // Pass the path to compiler resource files.
  3571. CmdArgs.push_back("-resource-dir");
  3572. CmdArgs.push_back(D.ResourceDir.c_str());
  3573. Args.AddLastArg(CmdArgs, options::OPT_working_directory);
  3574. bool ARCMTEnabled = false;
  3575. if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
  3576. if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
  3577. options::OPT_ccc_arcmt_modify,
  3578. options::OPT_ccc_arcmt_migrate)) {
  3579. ARCMTEnabled = true;
  3580. switch (A->getOption().getID()) {
  3581. default:
  3582. llvm_unreachable("missed a case");
  3583. case options::OPT_ccc_arcmt_check:
  3584. CmdArgs.push_back("-arcmt-check");
  3585. break;
  3586. case options::OPT_ccc_arcmt_modify:
  3587. CmdArgs.push_back("-arcmt-modify");
  3588. break;
  3589. case options::OPT_ccc_arcmt_migrate:
  3590. CmdArgs.push_back("-arcmt-migrate");
  3591. CmdArgs.push_back("-mt-migrate-directory");
  3592. CmdArgs.push_back(A->getValue());
  3593. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
  3594. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
  3595. break;
  3596. }
  3597. }
  3598. } else {
  3599. Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
  3600. Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
  3601. Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
  3602. }
  3603. if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
  3604. if (ARCMTEnabled) {
  3605. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  3606. << "-ccc-arcmt-migrate";
  3607. }
  3608. CmdArgs.push_back("-mt-migrate-directory");
  3609. CmdArgs.push_back(A->getValue());
  3610. if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
  3611. options::OPT_objcmt_migrate_subscripting,
  3612. options::OPT_objcmt_migrate_property)) {
  3613. // None specified, means enable them all.
  3614. CmdArgs.push_back("-objcmt-migrate-literals");
  3615. CmdArgs.push_back("-objcmt-migrate-subscripting");
  3616. CmdArgs.push_back("-objcmt-migrate-property");
  3617. } else {
  3618. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  3619. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  3620. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  3621. }
  3622. } else {
  3623. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  3624. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  3625. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  3626. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
  3627. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
  3628. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
  3629. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
  3630. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
  3631. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
  3632. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
  3633. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
  3634. Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
  3635. Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
  3636. Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
  3637. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
  3638. Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
  3639. }
  3640. // Add preprocessing options like -I, -D, etc. if we are using the
  3641. // preprocessor.
  3642. //
  3643. // FIXME: Support -fpreprocessed
  3644. if (types::getPreprocessedType(InputType) != types::TY_INVALID)
  3645. AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
  3646. AuxToolChain);
  3647. // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
  3648. // that "The compiler can only warn and ignore the option if not recognized".
  3649. // When building with ccache, it will pass -D options to clang even on
  3650. // preprocessed inputs and configure concludes that -fPIC is not supported.
  3651. Args.ClaimAllArgs(options::OPT_D);
  3652. // Manually translate -O4 to -O3; let clang reject others.
  3653. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  3654. if (A->getOption().matches(options::OPT_O4)) {
  3655. CmdArgs.push_back("-O3");
  3656. D.Diag(diag::warn_O4_is_O3);
  3657. } else {
  3658. A->render(Args, CmdArgs);
  3659. }
  3660. }
  3661. // Warn about ignored options to clang.
  3662. for (const Arg *A :
  3663. Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
  3664. D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
  3665. A->claim();
  3666. }
  3667. claimNoWarnArgs(Args);
  3668. Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
  3669. Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
  3670. if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
  3671. CmdArgs.push_back("-pedantic");
  3672. Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
  3673. Args.AddLastArg(CmdArgs, options::OPT_w);
  3674. // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
  3675. // (-ansi is equivalent to -std=c89 or -std=c++98).
  3676. //
  3677. // If a std is supplied, only add -trigraphs if it follows the
  3678. // option.
  3679. bool ImplyVCPPCXXVer = false;
  3680. if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
  3681. if (Std->getOption().matches(options::OPT_ansi))
  3682. if (types::isCXX(InputType))
  3683. CmdArgs.push_back("-std=c++98");
  3684. else
  3685. CmdArgs.push_back("-std=c89");
  3686. else
  3687. Std->render(Args, CmdArgs);
  3688. // If -f(no-)trigraphs appears after the language standard flag, honor it.
  3689. if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
  3690. options::OPT_ftrigraphs,
  3691. options::OPT_fno_trigraphs))
  3692. if (A != Std)
  3693. A->render(Args, CmdArgs);
  3694. } else {
  3695. // Honor -std-default.
  3696. //
  3697. // FIXME: Clang doesn't correctly handle -std= when the input language
  3698. // doesn't match. For the time being just ignore this for C++ inputs;
  3699. // eventually we want to do all the standard defaulting here instead of
  3700. // splitting it between the driver and clang -cc1.
  3701. if (!types::isCXX(InputType))
  3702. Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
  3703. /*Joined=*/true);
  3704. else if (IsWindowsMSVC)
  3705. ImplyVCPPCXXVer = true;
  3706. Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
  3707. options::OPT_fno_trigraphs);
  3708. }
  3709. // GCC's behavior for -Wwrite-strings is a bit strange:
  3710. // * In C, this "warning flag" changes the types of string literals from
  3711. // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
  3712. // for the discarded qualifier.
  3713. // * In C++, this is just a normal warning flag.
  3714. //
  3715. // Implementing this warning correctly in C is hard, so we follow GCC's
  3716. // behavior for now. FIXME: Directly diagnose uses of a string literal as
  3717. // a non-const char* in C, rather than using this crude hack.
  3718. if (!types::isCXX(InputType)) {
  3719. // FIXME: This should behave just like a warning flag, and thus should also
  3720. // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
  3721. Arg *WriteStrings =
  3722. Args.getLastArg(options::OPT_Wwrite_strings,
  3723. options::OPT_Wno_write_strings, options::OPT_w);
  3724. if (WriteStrings &&
  3725. WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
  3726. CmdArgs.push_back("-fconst-strings");
  3727. }
  3728. // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
  3729. // during C++ compilation, which it is by default. GCC keeps this define even
  3730. // in the presence of '-w', match this behavior bug-for-bug.
  3731. if (types::isCXX(InputType) &&
  3732. Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
  3733. true)) {
  3734. CmdArgs.push_back("-fdeprecated-macro");
  3735. }
  3736. // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
  3737. if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
  3738. if (Asm->getOption().matches(options::OPT_fasm))
  3739. CmdArgs.push_back("-fgnu-keywords");
  3740. else
  3741. CmdArgs.push_back("-fno-gnu-keywords");
  3742. }
  3743. if (ShouldDisableDwarfDirectory(Args, getToolChain()))
  3744. CmdArgs.push_back("-fno-dwarf-directory-asm");
  3745. if (ShouldDisableAutolink(Args, getToolChain()))
  3746. CmdArgs.push_back("-fno-autolink");
  3747. // Add in -fdebug-compilation-dir if necessary.
  3748. addDebugCompDirArg(Args, CmdArgs);
  3749. for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
  3750. StringRef Map = A->getValue();
  3751. if (Map.find('=') == StringRef::npos)
  3752. D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
  3753. else
  3754. CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
  3755. A->claim();
  3756. }
  3757. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
  3758. options::OPT_ftemplate_depth_EQ)) {
  3759. CmdArgs.push_back("-ftemplate-depth");
  3760. CmdArgs.push_back(A->getValue());
  3761. }
  3762. if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
  3763. CmdArgs.push_back("-foperator-arrow-depth");
  3764. CmdArgs.push_back(A->getValue());
  3765. }
  3766. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
  3767. CmdArgs.push_back("-fconstexpr-depth");
  3768. CmdArgs.push_back(A->getValue());
  3769. }
  3770. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
  3771. CmdArgs.push_back("-fconstexpr-steps");
  3772. CmdArgs.push_back(A->getValue());
  3773. }
  3774. if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
  3775. CmdArgs.push_back("-fbracket-depth");
  3776. CmdArgs.push_back(A->getValue());
  3777. }
  3778. if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
  3779. options::OPT_Wlarge_by_value_copy_def)) {
  3780. if (A->getNumValues()) {
  3781. StringRef bytes = A->getValue();
  3782. CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
  3783. } else
  3784. CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
  3785. }
  3786. if (Args.hasArg(options::OPT_relocatable_pch))
  3787. CmdArgs.push_back("-relocatable-pch");
  3788. if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
  3789. CmdArgs.push_back("-fconstant-string-class");
  3790. CmdArgs.push_back(A->getValue());
  3791. }
  3792. if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
  3793. CmdArgs.push_back("-ftabstop");
  3794. CmdArgs.push_back(A->getValue());
  3795. }
  3796. CmdArgs.push_back("-ferror-limit");
  3797. if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
  3798. CmdArgs.push_back(A->getValue());
  3799. else
  3800. CmdArgs.push_back("19");
  3801. if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
  3802. CmdArgs.push_back("-fmacro-backtrace-limit");
  3803. CmdArgs.push_back(A->getValue());
  3804. }
  3805. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
  3806. CmdArgs.push_back("-ftemplate-backtrace-limit");
  3807. CmdArgs.push_back(A->getValue());
  3808. }
  3809. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
  3810. CmdArgs.push_back("-fconstexpr-backtrace-limit");
  3811. CmdArgs.push_back(A->getValue());
  3812. }
  3813. if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
  3814. CmdArgs.push_back("-fspell-checking-limit");
  3815. CmdArgs.push_back(A->getValue());
  3816. }
  3817. // Pass -fmessage-length=.
  3818. CmdArgs.push_back("-fmessage-length");
  3819. if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
  3820. CmdArgs.push_back(A->getValue());
  3821. } else {
  3822. // If -fmessage-length=N was not specified, determine whether this is a
  3823. // terminal and, if so, implicitly define -fmessage-length appropriately.
  3824. unsigned N = llvm::sys::Process::StandardErrColumns();
  3825. CmdArgs.push_back(Args.MakeArgString(Twine(N)));
  3826. }
  3827. // -fvisibility= and -fvisibility-ms-compat are of a piece.
  3828. if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
  3829. options::OPT_fvisibility_ms_compat)) {
  3830. if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
  3831. CmdArgs.push_back("-fvisibility");
  3832. CmdArgs.push_back(A->getValue());
  3833. } else {
  3834. assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
  3835. CmdArgs.push_back("-fvisibility");
  3836. CmdArgs.push_back("hidden");
  3837. CmdArgs.push_back("-ftype-visibility");
  3838. CmdArgs.push_back("default");
  3839. }
  3840. }
  3841. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
  3842. Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
  3843. // -fhosted is default.
  3844. if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
  3845. KernelOrKext)
  3846. CmdArgs.push_back("-ffreestanding");
  3847. // Forward -f (flag) options which we can pass directly.
  3848. Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
  3849. Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
  3850. Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
  3851. // Emulated TLS is enabled by default on Android, and can be enabled manually
  3852. // with -femulated-tls.
  3853. bool EmulatedTLSDefault = Triple.isAndroid();
  3854. if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
  3855. EmulatedTLSDefault))
  3856. CmdArgs.push_back("-femulated-tls");
  3857. // AltiVec-like language extensions aren't relevant for assembling.
  3858. if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
  3859. Args.AddLastArg(CmdArgs, options::OPT_faltivec);
  3860. Args.AddLastArg(CmdArgs, options::OPT_fzvector);
  3861. }
  3862. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
  3863. Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
  3864. // Forward flags for OpenMP
  3865. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  3866. options::OPT_fno_openmp, false))
  3867. switch (getOpenMPRuntime(getToolChain(), Args)) {
  3868. case OMPRT_OMP:
  3869. case OMPRT_IOMP5:
  3870. // Clang can generate useful OpenMP code for these two runtime libraries.
  3871. CmdArgs.push_back("-fopenmp");
  3872. // If no option regarding the use of TLS in OpenMP codegeneration is
  3873. // given, decide a default based on the target. Otherwise rely on the
  3874. // options and pass the right information to the frontend.
  3875. if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
  3876. options::OPT_fnoopenmp_use_tls, /*Default=*/true))
  3877. CmdArgs.push_back("-fnoopenmp-use-tls");
  3878. break;
  3879. default:
  3880. // By default, if Clang doesn't know how to generate useful OpenMP code
  3881. // for a specific runtime library, we just don't pass the '-fopenmp' flag
  3882. // down to the actual compilation.
  3883. // FIXME: It would be better to have a mode which *only* omits IR
  3884. // generation based on the OpenMP support so that we get consistent
  3885. // semantic analysis, etc.
  3886. break;
  3887. }
  3888. const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
  3889. Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
  3890. // Report an error for -faltivec on anything other than PowerPC.
  3891. if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
  3892. const llvm::Triple::ArchType Arch = getToolChain().getArch();
  3893. if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  3894. Arch == llvm::Triple::ppc64le))
  3895. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  3896. << "ppc/ppc64/ppc64le";
  3897. }
  3898. // -fzvector is incompatible with -faltivec.
  3899. if (Arg *A = Args.getLastArg(options::OPT_fzvector))
  3900. if (Args.hasArg(options::OPT_faltivec))
  3901. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  3902. << "-faltivec";
  3903. if (getToolChain().SupportsProfiling())
  3904. Args.AddLastArg(CmdArgs, options::OPT_pg);
  3905. // -flax-vector-conversions is default.
  3906. if (!Args.hasFlag(options::OPT_flax_vector_conversions,
  3907. options::OPT_fno_lax_vector_conversions))
  3908. CmdArgs.push_back("-fno-lax-vector-conversions");
  3909. if (Args.getLastArg(options::OPT_fapple_kext) ||
  3910. (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
  3911. CmdArgs.push_back("-fapple-kext");
  3912. Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
  3913. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
  3914. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
  3915. Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
  3916. Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
  3917. if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
  3918. CmdArgs.push_back("-ftrapv-handler");
  3919. CmdArgs.push_back(A->getValue());
  3920. }
  3921. Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
  3922. // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
  3923. // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
  3924. if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
  3925. if (A->getOption().matches(options::OPT_fwrapv))
  3926. CmdArgs.push_back("-fwrapv");
  3927. } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
  3928. options::OPT_fno_strict_overflow)) {
  3929. if (A->getOption().matches(options::OPT_fno_strict_overflow))
  3930. CmdArgs.push_back("-fwrapv");
  3931. }
  3932. if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
  3933. options::OPT_fno_reroll_loops))
  3934. if (A->getOption().matches(options::OPT_freroll_loops))
  3935. CmdArgs.push_back("-freroll-loops");
  3936. Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
  3937. Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
  3938. options::OPT_fno_unroll_loops);
  3939. Args.AddLastArg(CmdArgs, options::OPT_pthread);
  3940. // -stack-protector=0 is default.
  3941. unsigned StackProtectorLevel = 0;
  3942. if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
  3943. Args.ClaimAllArgs(options::OPT_fno_stack_protector);
  3944. Args.ClaimAllArgs(options::OPT_fstack_protector_all);
  3945. Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
  3946. Args.ClaimAllArgs(options::OPT_fstack_protector);
  3947. } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
  3948. options::OPT_fstack_protector_all,
  3949. options::OPT_fstack_protector_strong,
  3950. options::OPT_fstack_protector)) {
  3951. if (A->getOption().matches(options::OPT_fstack_protector)) {
  3952. StackProtectorLevel = std::max<unsigned>(
  3953. LangOptions::SSPOn,
  3954. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
  3955. } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
  3956. StackProtectorLevel = LangOptions::SSPStrong;
  3957. else if (A->getOption().matches(options::OPT_fstack_protector_all))
  3958. StackProtectorLevel = LangOptions::SSPReq;
  3959. } else {
  3960. StackProtectorLevel =
  3961. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
  3962. }
  3963. if (StackProtectorLevel) {
  3964. CmdArgs.push_back("-stack-protector");
  3965. CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
  3966. }
  3967. // --param ssp-buffer-size=
  3968. for (const Arg *A : Args.filtered(options::OPT__param)) {
  3969. StringRef Str(A->getValue());
  3970. if (Str.startswith("ssp-buffer-size=")) {
  3971. if (StackProtectorLevel) {
  3972. CmdArgs.push_back("-stack-protector-buffer-size");
  3973. // FIXME: Verify the argument is a valid integer.
  3974. CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
  3975. }
  3976. A->claim();
  3977. }
  3978. }
  3979. // Translate -mstackrealign
  3980. if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
  3981. false))
  3982. CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
  3983. if (Args.hasArg(options::OPT_mstack_alignment)) {
  3984. StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
  3985. CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
  3986. }
  3987. if (Args.hasArg(options::OPT_mstack_probe_size)) {
  3988. StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
  3989. if (!Size.empty())
  3990. CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
  3991. else
  3992. CmdArgs.push_back("-mstack-probe-size=0");
  3993. }
  3994. switch (getToolChain().getArch()) {
  3995. case llvm::Triple::aarch64:
  3996. case llvm::Triple::aarch64_be:
  3997. case llvm::Triple::arm:
  3998. case llvm::Triple::armeb:
  3999. case llvm::Triple::thumb:
  4000. case llvm::Triple::thumbeb:
  4001. CmdArgs.push_back("-fallow-half-arguments-and-returns");
  4002. break;
  4003. default:
  4004. break;
  4005. }
  4006. if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
  4007. options::OPT_mno_restrict_it)) {
  4008. if (A->getOption().matches(options::OPT_mrestrict_it)) {
  4009. CmdArgs.push_back("-backend-option");
  4010. CmdArgs.push_back("-arm-restrict-it");
  4011. } else {
  4012. CmdArgs.push_back("-backend-option");
  4013. CmdArgs.push_back("-arm-no-restrict-it");
  4014. }
  4015. } else if (Triple.isOSWindows() &&
  4016. (Triple.getArch() == llvm::Triple::arm ||
  4017. Triple.getArch() == llvm::Triple::thumb)) {
  4018. // Windows on ARM expects restricted IT blocks
  4019. CmdArgs.push_back("-backend-option");
  4020. CmdArgs.push_back("-arm-restrict-it");
  4021. }
  4022. // Forward -f options with positive and negative forms; we translate
  4023. // these by hand.
  4024. if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
  4025. StringRef fname = A->getValue();
  4026. if (!llvm::sys::fs::exists(fname))
  4027. D.Diag(diag::err_drv_no_such_file) << fname;
  4028. else
  4029. A->render(Args, CmdArgs);
  4030. }
  4031. // -fbuiltin is default unless -mkernel is used
  4032. if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
  4033. !Args.hasArg(options::OPT_mkernel)))
  4034. CmdArgs.push_back("-fno-builtin");
  4035. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4036. options::OPT_fno_assume_sane_operator_new))
  4037. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4038. // -fblocks=0 is default.
  4039. if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
  4040. getToolChain().IsBlocksDefault()) ||
  4041. (Args.hasArg(options::OPT_fgnu_runtime) &&
  4042. Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
  4043. !Args.hasArg(options::OPT_fno_blocks))) {
  4044. CmdArgs.push_back("-fblocks");
  4045. if (!Args.hasArg(options::OPT_fgnu_runtime) &&
  4046. !getToolChain().hasBlocksRuntime())
  4047. CmdArgs.push_back("-fblocks-runtime-optional");
  4048. }
  4049. // -fmodules enables the use of precompiled modules (off by default).
  4050. // Users can pass -fno-cxx-modules to turn off modules support for
  4051. // C++/Objective-C++ programs.
  4052. bool HaveModules = false;
  4053. if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
  4054. bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
  4055. options::OPT_fno_cxx_modules, true);
  4056. if (AllowedInCXX || !types::isCXX(InputType)) {
  4057. CmdArgs.push_back("-fmodules");
  4058. HaveModules = true;
  4059. }
  4060. }
  4061. // -fmodule-maps enables implicit reading of module map files. By default,
  4062. // this is enabled if we are using precompiled modules.
  4063. if (Args.hasFlag(options::OPT_fimplicit_module_maps,
  4064. options::OPT_fno_implicit_module_maps, HaveModules)) {
  4065. CmdArgs.push_back("-fimplicit-module-maps");
  4066. }
  4067. // -fmodules-decluse checks that modules used are declared so (off by
  4068. // default).
  4069. if (Args.hasFlag(options::OPT_fmodules_decluse,
  4070. options::OPT_fno_modules_decluse, false)) {
  4071. CmdArgs.push_back("-fmodules-decluse");
  4072. }
  4073. // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
  4074. // all #included headers are part of modules.
  4075. if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
  4076. options::OPT_fno_modules_strict_decluse, false)) {
  4077. CmdArgs.push_back("-fmodules-strict-decluse");
  4078. }
  4079. // -fno-implicit-modules turns off implicitly compiling modules on demand.
  4080. if (!Args.hasFlag(options::OPT_fimplicit_modules,
  4081. options::OPT_fno_implicit_modules)) {
  4082. CmdArgs.push_back("-fno-implicit-modules");
  4083. }
  4084. // -fmodule-name specifies the module that is currently being built (or
  4085. // used for header checking by -fmodule-maps).
  4086. Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
  4087. // -fmodule-map-file can be used to specify files containing module
  4088. // definitions.
  4089. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
  4090. // -fmodule-file can be used to specify files containing precompiled modules.
  4091. if (HaveModules)
  4092. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
  4093. else
  4094. Args.ClaimAllArgs(options::OPT_fmodule_file);
  4095. // -fmodule-cache-path specifies where our implicitly-built module files
  4096. // should be written.
  4097. SmallString<128> Path;
  4098. if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
  4099. Path = A->getValue();
  4100. if (HaveModules) {
  4101. if (C.isForDiagnostics()) {
  4102. // When generating crash reports, we want to emit the modules along with
  4103. // the reproduction sources, so we ignore any provided module path.
  4104. Path = Output.getFilename();
  4105. llvm::sys::path::replace_extension(Path, ".cache");
  4106. llvm::sys::path::append(Path, "modules");
  4107. } else if (Path.empty()) {
  4108. // No module path was provided: use the default.
  4109. llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
  4110. llvm::sys::path::append(Path, "org.llvm.clang.");
  4111. appendUserToPath(Path);
  4112. llvm::sys::path::append(Path, "ModuleCache");
  4113. }
  4114. const char Arg[] = "-fmodules-cache-path=";
  4115. Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
  4116. CmdArgs.push_back(Args.MakeArgString(Path));
  4117. }
  4118. // When building modules and generating crashdumps, we need to dump a module
  4119. // dependency VFS alongside the output.
  4120. if (HaveModules && C.isForDiagnostics()) {
  4121. SmallString<128> VFSDir(Output.getFilename());
  4122. llvm::sys::path::replace_extension(VFSDir, ".cache");
  4123. // Add the cache directory as a temp so the crash diagnostics pick it up.
  4124. C.addTempFile(Args.MakeArgString(VFSDir));
  4125. llvm::sys::path::append(VFSDir, "vfs");
  4126. CmdArgs.push_back("-module-dependency-dir");
  4127. CmdArgs.push_back(Args.MakeArgString(VFSDir));
  4128. }
  4129. if (HaveModules)
  4130. Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
  4131. // Pass through all -fmodules-ignore-macro arguments.
  4132. Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
  4133. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
  4134. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
  4135. Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
  4136. if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
  4137. if (Args.hasArg(options::OPT_fbuild_session_timestamp))
  4138. D.Diag(diag::err_drv_argument_not_allowed_with)
  4139. << A->getAsString(Args) << "-fbuild-session-timestamp";
  4140. llvm::sys::fs::file_status Status;
  4141. if (llvm::sys::fs::status(A->getValue(), Status))
  4142. D.Diag(diag::err_drv_no_such_file) << A->getValue();
  4143. CmdArgs.push_back(Args.MakeArgString(
  4144. "-fbuild-session-timestamp=" +
  4145. Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
  4146. }
  4147. if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
  4148. if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
  4149. options::OPT_fbuild_session_file))
  4150. D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
  4151. Args.AddLastArg(CmdArgs,
  4152. options::OPT_fmodules_validate_once_per_build_session);
  4153. }
  4154. Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
  4155. // -faccess-control is default.
  4156. if (Args.hasFlag(options::OPT_fno_access_control,
  4157. options::OPT_faccess_control, false))
  4158. CmdArgs.push_back("-fno-access-control");
  4159. // -felide-constructors is the default.
  4160. if (Args.hasFlag(options::OPT_fno_elide_constructors,
  4161. options::OPT_felide_constructors, false))
  4162. CmdArgs.push_back("-fno-elide-constructors");
  4163. ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
  4164. if (KernelOrKext || (types::isCXX(InputType) &&
  4165. (RTTIMode == ToolChain::RM_DisabledExplicitly ||
  4166. RTTIMode == ToolChain::RM_DisabledImplicitly)))
  4167. CmdArgs.push_back("-fno-rtti");
  4168. // -fshort-enums=0 is default for all architectures except Hexagon.
  4169. if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
  4170. getToolChain().getArch() == llvm::Triple::hexagon))
  4171. CmdArgs.push_back("-fshort-enums");
  4172. // -fsigned-char is default.
  4173. if (Arg *A = Args.getLastArg(
  4174. options::OPT_fsigned_char, options::OPT_fno_signed_char,
  4175. options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
  4176. if (A->getOption().matches(options::OPT_funsigned_char) ||
  4177. A->getOption().matches(options::OPT_fno_signed_char)) {
  4178. CmdArgs.push_back("-fno-signed-char");
  4179. }
  4180. } else if (!isSignedCharDefault(getToolChain().getTriple())) {
  4181. CmdArgs.push_back("-fno-signed-char");
  4182. }
  4183. // -fuse-cxa-atexit is default.
  4184. if (!Args.hasFlag(
  4185. options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
  4186. !IsWindowsCygnus && !IsWindowsGNU &&
  4187. getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
  4188. getToolChain().getArch() != llvm::Triple::hexagon &&
  4189. getToolChain().getArch() != llvm::Triple::xcore &&
  4190. ((getToolChain().getTriple().getVendor() !=
  4191. llvm::Triple::MipsTechnologies) ||
  4192. getToolChain().getTriple().hasEnvironment())) ||
  4193. KernelOrKext)
  4194. CmdArgs.push_back("-fno-use-cxa-atexit");
  4195. // -fms-extensions=0 is default.
  4196. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  4197. IsWindowsMSVC))
  4198. CmdArgs.push_back("-fms-extensions");
  4199. // -fno-use-line-directives is default.
  4200. if (Args.hasFlag(options::OPT_fuse_line_directives,
  4201. options::OPT_fno_use_line_directives, false))
  4202. CmdArgs.push_back("-fuse-line-directives");
  4203. // -fms-compatibility=0 is default.
  4204. if (Args.hasFlag(options::OPT_fms_compatibility,
  4205. options::OPT_fno_ms_compatibility,
  4206. (IsWindowsMSVC &&
  4207. Args.hasFlag(options::OPT_fms_extensions,
  4208. options::OPT_fno_ms_extensions, true))))
  4209. CmdArgs.push_back("-fms-compatibility");
  4210. // -fms-compatibility-version=18.00 is default.
  4211. VersionTuple MSVT = visualstudio::getMSVCVersion(
  4212. &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
  4213. if (!MSVT.empty())
  4214. CmdArgs.push_back(
  4215. Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
  4216. bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
  4217. if (ImplyVCPPCXXVer) {
  4218. if (IsMSVC2015Compatible)
  4219. CmdArgs.push_back("-std=c++14");
  4220. else
  4221. CmdArgs.push_back("-std=c++11");
  4222. }
  4223. // -fno-borland-extensions is default.
  4224. if (Args.hasFlag(options::OPT_fborland_extensions,
  4225. options::OPT_fno_borland_extensions, false))
  4226. CmdArgs.push_back("-fborland-extensions");
  4227. // -fno-declspec is default, except for PS4.
  4228. if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
  4229. getToolChain().getTriple().isPS4()))
  4230. CmdArgs.push_back("-fdeclspec");
  4231. else if (Args.hasArg(options::OPT_fno_declspec))
  4232. CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
  4233. // -fthreadsafe-static is default, except for MSVC compatibility versions less
  4234. // than 19.
  4235. if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
  4236. options::OPT_fno_threadsafe_statics,
  4237. !IsWindowsMSVC || IsMSVC2015Compatible))
  4238. CmdArgs.push_back("-fno-threadsafe-statics");
  4239. // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
  4240. // needs it.
  4241. if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
  4242. options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
  4243. CmdArgs.push_back("-fdelayed-template-parsing");
  4244. // -fgnu-keywords default varies depending on language; only pass if
  4245. // specified.
  4246. if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
  4247. options::OPT_fno_gnu_keywords))
  4248. A->render(Args, CmdArgs);
  4249. if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
  4250. false))
  4251. CmdArgs.push_back("-fgnu89-inline");
  4252. if (Args.hasArg(options::OPT_fno_inline))
  4253. CmdArgs.push_back("-fno-inline");
  4254. if (Args.hasArg(options::OPT_fno_inline_functions))
  4255. CmdArgs.push_back("-fno-inline-functions");
  4256. ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
  4257. // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
  4258. // legacy is the default. Except for deployment taget of 10.5,
  4259. // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
  4260. // gets ignored silently.
  4261. if (objcRuntime.isNonFragile()) {
  4262. if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
  4263. options::OPT_fno_objc_legacy_dispatch,
  4264. objcRuntime.isLegacyDispatchDefaultForArch(
  4265. getToolChain().getArch()))) {
  4266. if (getToolChain().UseObjCMixedDispatch())
  4267. CmdArgs.push_back("-fobjc-dispatch-method=mixed");
  4268. else
  4269. CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
  4270. }
  4271. }
  4272. // When ObjectiveC legacy runtime is in effect on MacOSX,
  4273. // turn on the option to do Array/Dictionary subscripting
  4274. // by default.
  4275. if (getToolChain().getArch() == llvm::Triple::x86 &&
  4276. getToolChain().getTriple().isMacOSX() &&
  4277. !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
  4278. objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
  4279. objcRuntime.isNeXTFamily())
  4280. CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
  4281. // -fencode-extended-block-signature=1 is default.
  4282. if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
  4283. CmdArgs.push_back("-fencode-extended-block-signature");
  4284. }
  4285. // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
  4286. // NOTE: This logic is duplicated in ToolChains.cpp.
  4287. bool ARC = isObjCAutoRefCount(Args);
  4288. if (ARC) {
  4289. getToolChain().CheckObjCARC();
  4290. CmdArgs.push_back("-fobjc-arc");
  4291. // FIXME: It seems like this entire block, and several around it should be
  4292. // wrapped in isObjC, but for now we just use it here as this is where it
  4293. // was being used previously.
  4294. if (types::isCXX(InputType) && types::isObjC(InputType)) {
  4295. if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  4296. CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
  4297. else
  4298. CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
  4299. }
  4300. // Allow the user to enable full exceptions code emission.
  4301. // We define off for Objective-CC, on for Objective-C++.
  4302. if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
  4303. options::OPT_fno_objc_arc_exceptions,
  4304. /*default*/ types::isCXX(InputType)))
  4305. CmdArgs.push_back("-fobjc-arc-exceptions");
  4306. }
  4307. // -fobjc-infer-related-result-type is the default, except in the Objective-C
  4308. // rewriter.
  4309. if (rewriteKind != RK_None)
  4310. CmdArgs.push_back("-fno-objc-infer-related-result-type");
  4311. // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
  4312. // takes precedence.
  4313. const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
  4314. if (!GCArg)
  4315. GCArg = Args.getLastArg(options::OPT_fobjc_gc);
  4316. if (GCArg) {
  4317. if (ARC) {
  4318. D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
  4319. } else if (getToolChain().SupportsObjCGC()) {
  4320. GCArg->render(Args, CmdArgs);
  4321. } else {
  4322. // FIXME: We should move this to a hard error.
  4323. D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
  4324. }
  4325. }
  4326. // Pass down -fobjc-weak or -fno-objc-weak if present.
  4327. if (types::isObjC(InputType)) {
  4328. auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
  4329. options::OPT_fno_objc_weak);
  4330. if (!WeakArg) {
  4331. // nothing to do
  4332. } else if (GCArg) {
  4333. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  4334. D.Diag(diag::err_objc_weak_with_gc);
  4335. } else if (!objcRuntime.allowsWeak()) {
  4336. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  4337. D.Diag(diag::err_objc_weak_unsupported);
  4338. } else {
  4339. WeakArg->render(Args, CmdArgs);
  4340. }
  4341. }
  4342. if (Args.hasFlag(options::OPT_fapplication_extension,
  4343. options::OPT_fno_application_extension, false))
  4344. CmdArgs.push_back("-fapplication-extension");
  4345. // Handle GCC-style exception args.
  4346. if (!C.getDriver().IsCLMode())
  4347. addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
  4348. CmdArgs);
  4349. if (getToolChain().UseSjLjExceptions(Args))
  4350. CmdArgs.push_back("-fsjlj-exceptions");
  4351. // C++ "sane" operator new.
  4352. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4353. options::OPT_fno_assume_sane_operator_new))
  4354. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4355. // -fsized-deallocation is off by default, as it is an ABI-breaking change for
  4356. // most platforms.
  4357. if (Args.hasFlag(options::OPT_fsized_deallocation,
  4358. options::OPT_fno_sized_deallocation, false))
  4359. CmdArgs.push_back("-fsized-deallocation");
  4360. // -fconstant-cfstrings is default, and may be subject to argument translation
  4361. // on Darwin.
  4362. if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
  4363. options::OPT_fno_constant_cfstrings) ||
  4364. !Args.hasFlag(options::OPT_mconstant_cfstrings,
  4365. options::OPT_mno_constant_cfstrings))
  4366. CmdArgs.push_back("-fno-constant-cfstrings");
  4367. // -fshort-wchar default varies depending on platform; only
  4368. // pass if specified.
  4369. if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
  4370. options::OPT_fno_short_wchar))
  4371. A->render(Args, CmdArgs);
  4372. // -fno-pascal-strings is default, only pass non-default.
  4373. if (Args.hasFlag(options::OPT_fpascal_strings,
  4374. options::OPT_fno_pascal_strings, false))
  4375. CmdArgs.push_back("-fpascal-strings");
  4376. // Honor -fpack-struct= and -fpack-struct, if given. Note that
  4377. // -fno-pack-struct doesn't apply to -fpack-struct=.
  4378. if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
  4379. std::string PackStructStr = "-fpack-struct=";
  4380. PackStructStr += A->getValue();
  4381. CmdArgs.push_back(Args.MakeArgString(PackStructStr));
  4382. } else if (Args.hasFlag(options::OPT_fpack_struct,
  4383. options::OPT_fno_pack_struct, false)) {
  4384. CmdArgs.push_back("-fpack-struct=1");
  4385. }
  4386. // Handle -fmax-type-align=N and -fno-type-align
  4387. bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
  4388. if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
  4389. if (!SkipMaxTypeAlign) {
  4390. std::string MaxTypeAlignStr = "-fmax-type-align=";
  4391. MaxTypeAlignStr += A->getValue();
  4392. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4393. }
  4394. } else if (getToolChain().getTriple().isOSDarwin()) {
  4395. if (!SkipMaxTypeAlign) {
  4396. std::string MaxTypeAlignStr = "-fmax-type-align=16";
  4397. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4398. }
  4399. }
  4400. // -fcommon is the default unless compiling kernel code or the target says so
  4401. bool NoCommonDefault =
  4402. KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
  4403. if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
  4404. !NoCommonDefault))
  4405. CmdArgs.push_back("-fno-common");
  4406. // -fsigned-bitfields is default, and clang doesn't yet support
  4407. // -funsigned-bitfields.
  4408. if (!Args.hasFlag(options::OPT_fsigned_bitfields,
  4409. options::OPT_funsigned_bitfields))
  4410. D.Diag(diag::warn_drv_clang_unsupported)
  4411. << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
  4412. // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
  4413. if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
  4414. D.Diag(diag::err_drv_clang_unsupported)
  4415. << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
  4416. // -finput_charset=UTF-8 is default. Reject others
  4417. if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
  4418. StringRef value = inputCharset->getValue();
  4419. if (value != "UTF-8")
  4420. D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
  4421. << value;
  4422. }
  4423. // -fexec_charset=UTF-8 is default. Reject others
  4424. if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
  4425. StringRef value = execCharset->getValue();
  4426. if (value != "UTF-8")
  4427. D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
  4428. << value;
  4429. }
  4430. // -fcaret-diagnostics is default.
  4431. if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
  4432. options::OPT_fno_caret_diagnostics, true))
  4433. CmdArgs.push_back("-fno-caret-diagnostics");
  4434. // -fdiagnostics-fixit-info is default, only pass non-default.
  4435. if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
  4436. options::OPT_fno_diagnostics_fixit_info))
  4437. CmdArgs.push_back("-fno-diagnostics-fixit-info");
  4438. // Enable -fdiagnostics-show-option by default.
  4439. if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
  4440. options::OPT_fno_diagnostics_show_option))
  4441. CmdArgs.push_back("-fdiagnostics-show-option");
  4442. if (const Arg *A =
  4443. Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
  4444. CmdArgs.push_back("-fdiagnostics-show-category");
  4445. CmdArgs.push_back(A->getValue());
  4446. }
  4447. if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
  4448. CmdArgs.push_back("-fdiagnostics-format");
  4449. CmdArgs.push_back(A->getValue());
  4450. }
  4451. if (Arg *A = Args.getLastArg(
  4452. options::OPT_fdiagnostics_show_note_include_stack,
  4453. options::OPT_fno_diagnostics_show_note_include_stack)) {
  4454. if (A->getOption().matches(
  4455. options::OPT_fdiagnostics_show_note_include_stack))
  4456. CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
  4457. else
  4458. CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
  4459. }
  4460. // Color diagnostics are the default, unless the terminal doesn't support
  4461. // them.
  4462. // Support both clang's -f[no-]color-diagnostics and gcc's
  4463. // -f[no-]diagnostics-colors[=never|always|auto].
  4464. enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
  4465. for (const auto &Arg : Args) {
  4466. const Option &O = Arg->getOption();
  4467. if (!O.matches(options::OPT_fcolor_diagnostics) &&
  4468. !O.matches(options::OPT_fdiagnostics_color) &&
  4469. !O.matches(options::OPT_fno_color_diagnostics) &&
  4470. !O.matches(options::OPT_fno_diagnostics_color) &&
  4471. !O.matches(options::OPT_fdiagnostics_color_EQ))
  4472. continue;
  4473. Arg->claim();
  4474. if (O.matches(options::OPT_fcolor_diagnostics) ||
  4475. O.matches(options::OPT_fdiagnostics_color)) {
  4476. ShowColors = Colors_On;
  4477. } else if (O.matches(options::OPT_fno_color_diagnostics) ||
  4478. O.matches(options::OPT_fno_diagnostics_color)) {
  4479. ShowColors = Colors_Off;
  4480. } else {
  4481. assert(O.matches(options::OPT_fdiagnostics_color_EQ));
  4482. StringRef value(Arg->getValue());
  4483. if (value == "always")
  4484. ShowColors = Colors_On;
  4485. else if (value == "never")
  4486. ShowColors = Colors_Off;
  4487. else if (value == "auto")
  4488. ShowColors = Colors_Auto;
  4489. else
  4490. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  4491. << ("-fdiagnostics-color=" + value).str();
  4492. }
  4493. }
  4494. if (ShowColors == Colors_On ||
  4495. (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
  4496. CmdArgs.push_back("-fcolor-diagnostics");
  4497. if (Args.hasArg(options::OPT_fansi_escape_codes))
  4498. CmdArgs.push_back("-fansi-escape-codes");
  4499. if (!Args.hasFlag(options::OPT_fshow_source_location,
  4500. options::OPT_fno_show_source_location))
  4501. CmdArgs.push_back("-fno-show-source-location");
  4502. if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
  4503. true))
  4504. CmdArgs.push_back("-fno-show-column");
  4505. if (!Args.hasFlag(options::OPT_fspell_checking,
  4506. options::OPT_fno_spell_checking))
  4507. CmdArgs.push_back("-fno-spell-checking");
  4508. // -fno-asm-blocks is default.
  4509. if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
  4510. false))
  4511. CmdArgs.push_back("-fasm-blocks");
  4512. // -fgnu-inline-asm is default.
  4513. if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
  4514. options::OPT_fno_gnu_inline_asm, true))
  4515. CmdArgs.push_back("-fno-gnu-inline-asm");
  4516. // Enable vectorization per default according to the optimization level
  4517. // selected. For optimization levels that want vectorization we use the alias
  4518. // option to simplify the hasFlag logic.
  4519. bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
  4520. OptSpecifier VectorizeAliasOption =
  4521. EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
  4522. if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
  4523. options::OPT_fno_vectorize, EnableVec))
  4524. CmdArgs.push_back("-vectorize-loops");
  4525. // -fslp-vectorize is enabled based on the optimization level selected.
  4526. bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
  4527. OptSpecifier SLPVectAliasOption =
  4528. EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
  4529. if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
  4530. options::OPT_fno_slp_vectorize, EnableSLPVec))
  4531. CmdArgs.push_back("-vectorize-slp");
  4532. // -fno-slp-vectorize-aggressive is default.
  4533. if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
  4534. options::OPT_fno_slp_vectorize_aggressive, false))
  4535. CmdArgs.push_back("-vectorize-slp-aggressive");
  4536. if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
  4537. A->render(Args, CmdArgs);
  4538. // -fdollars-in-identifiers default varies depending on platform and
  4539. // language; only pass if specified.
  4540. if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
  4541. options::OPT_fno_dollars_in_identifiers)) {
  4542. if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
  4543. CmdArgs.push_back("-fdollars-in-identifiers");
  4544. else
  4545. CmdArgs.push_back("-fno-dollars-in-identifiers");
  4546. }
  4547. // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
  4548. // practical purposes.
  4549. if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
  4550. options::OPT_fno_unit_at_a_time)) {
  4551. if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
  4552. D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
  4553. }
  4554. if (Args.hasFlag(options::OPT_fapple_pragma_pack,
  4555. options::OPT_fno_apple_pragma_pack, false))
  4556. CmdArgs.push_back("-fapple-pragma-pack");
  4557. // le32-specific flags:
  4558. // -fno-math-builtin: clang should not convert math builtins to intrinsics
  4559. // by default.
  4560. if (getToolChain().getArch() == llvm::Triple::le32) {
  4561. CmdArgs.push_back("-fno-math-builtin");
  4562. }
  4563. // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
  4564. //
  4565. // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
  4566. #if 0
  4567. if (getToolChain().getTriple().isOSDarwin() &&
  4568. (getToolChain().getArch() == llvm::Triple::arm ||
  4569. getToolChain().getArch() == llvm::Triple::thumb)) {
  4570. if (!Args.hasArg(options::OPT_fbuiltin_strcat))
  4571. CmdArgs.push_back("-fno-builtin-strcat");
  4572. if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
  4573. CmdArgs.push_back("-fno-builtin-strcpy");
  4574. }
  4575. #endif
  4576. // Enable rewrite includes if the user's asked for it or if we're generating
  4577. // diagnostics.
  4578. // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
  4579. // nice to enable this when doing a crashdump for modules as well.
  4580. if (Args.hasFlag(options::OPT_frewrite_includes,
  4581. options::OPT_fno_rewrite_includes, false) ||
  4582. (C.isForDiagnostics() && !HaveModules))
  4583. CmdArgs.push_back("-frewrite-includes");
  4584. // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
  4585. if (Arg *A = Args.getLastArg(options::OPT_traditional,
  4586. options::OPT_traditional_cpp)) {
  4587. if (isa<PreprocessJobAction>(JA))
  4588. CmdArgs.push_back("-traditional-cpp");
  4589. else
  4590. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  4591. }
  4592. Args.AddLastArg(CmdArgs, options::OPT_dM);
  4593. Args.AddLastArg(CmdArgs, options::OPT_dD);
  4594. // Handle serialized diagnostics.
  4595. if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
  4596. CmdArgs.push_back("-serialize-diagnostic-file");
  4597. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  4598. }
  4599. if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
  4600. CmdArgs.push_back("-fretain-comments-from-system-headers");
  4601. // Forward -fcomment-block-commands to -cc1.
  4602. Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
  4603. // Forward -fparse-all-comments to -cc1.
  4604. Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
  4605. // Turn -fplugin=name.so into -load name.so
  4606. for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
  4607. CmdArgs.push_back("-load");
  4608. CmdArgs.push_back(A->getValue());
  4609. A->claim();
  4610. }
  4611. // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
  4612. // parser.
  4613. Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
  4614. for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
  4615. A->claim();
  4616. // We translate this by hand to the -cc1 argument, since nightly test uses
  4617. // it and developers have been trained to spell it with -mllvm.
  4618. if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
  4619. CmdArgs.push_back("-disable-llvm-optzns");
  4620. } else
  4621. A->render(Args, CmdArgs);
  4622. }
  4623. // With -save-temps, we want to save the unoptimized bitcode output from the
  4624. // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
  4625. // by the frontend.
  4626. if (C.getDriver().isSaveTempsEnabled() && isa<CompileJobAction>(JA))
  4627. CmdArgs.push_back("-disable-llvm-passes");
  4628. if (Output.getType() == types::TY_Dependencies) {
  4629. // Handled with other dependency code.
  4630. } else if (Output.isFilename()) {
  4631. CmdArgs.push_back("-o");
  4632. CmdArgs.push_back(Output.getFilename());
  4633. } else {
  4634. assert(Output.isNothing() && "Invalid output.");
  4635. }
  4636. addDashXForInput(Args, Input, CmdArgs);
  4637. if (Input.isFilename())
  4638. CmdArgs.push_back(Input.getFilename());
  4639. else
  4640. Input.getInputArg().renderAsInput(Args, CmdArgs);
  4641. Args.AddAllArgs(CmdArgs, options::OPT_undef);
  4642. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  4643. // Optionally embed the -cc1 level arguments into the debug info, for build
  4644. // analysis.
  4645. if (getToolChain().UseDwarfDebugFlags()) {
  4646. ArgStringList OriginalArgs;
  4647. for (const auto &Arg : Args)
  4648. Arg->render(Args, OriginalArgs);
  4649. SmallString<256> Flags;
  4650. Flags += Exec;
  4651. for (const char *OriginalArg : OriginalArgs) {
  4652. SmallString<128> EscapedArg;
  4653. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  4654. Flags += " ";
  4655. Flags += EscapedArg;
  4656. }
  4657. CmdArgs.push_back("-dwarf-debug-flags");
  4658. CmdArgs.push_back(Args.MakeArgString(Flags));
  4659. }
  4660. // Add the split debug info name to the command lines here so we
  4661. // can propagate it to the backend.
  4662. bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
  4663. (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
  4664. isa<BackendJobAction>(JA));
  4665. const char *SplitDwarfOut;
  4666. if (SplitDwarf) {
  4667. CmdArgs.push_back("-split-dwarf-file");
  4668. SplitDwarfOut = SplitDebugName(Args, Input);
  4669. CmdArgs.push_back(SplitDwarfOut);
  4670. }
  4671. // Host-side cuda compilation receives device-side outputs as Inputs[1...].
  4672. // Include them with -fcuda-include-gpubinary.
  4673. if (IsCuda && Inputs.size() > 1)
  4674. for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
  4675. CmdArgs.push_back("-fcuda-include-gpubinary");
  4676. CmdArgs.push_back(I->getFilename());
  4677. }
  4678. // Finally add the compile command to the compilation.
  4679. if (Args.hasArg(options::OPT__SLASH_fallback) &&
  4680. Output.getType() == types::TY_Object &&
  4681. (InputType == types::TY_C || InputType == types::TY_CXX)) {
  4682. auto CLCommand =
  4683. getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
  4684. C.addCommand(llvm::make_unique<FallbackCommand>(
  4685. JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
  4686. } else {
  4687. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  4688. }
  4689. // Handle the debug info splitting at object creation time if we're
  4690. // creating an object.
  4691. // TODO: Currently only works on linux with newer objcopy.
  4692. if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
  4693. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
  4694. if (Arg *A = Args.getLastArg(options::OPT_pg))
  4695. if (Args.hasArg(options::OPT_fomit_frame_pointer))
  4696. D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
  4697. << A->getAsString(Args);
  4698. // Claim some arguments which clang supports automatically.
  4699. // -fpch-preprocess is used with gcc to add a special marker in the output to
  4700. // include the PCH file. Clang's PTH solution is completely transparent, so we
  4701. // do not need to deal with it at all.
  4702. Args.ClaimAllArgs(options::OPT_fpch_preprocess);
  4703. // Claim some arguments which clang doesn't support, but we don't
  4704. // care to warn the user about.
  4705. Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
  4706. Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
  4707. // Disable warnings for clang -E -emit-llvm foo.c
  4708. Args.ClaimAllArgs(options::OPT_emit_llvm);
  4709. }
  4710. /// Add options related to the Objective-C runtime/ABI.
  4711. ///
  4712. /// Returns true if the runtime is non-fragile.
  4713. ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
  4714. ArgStringList &cmdArgs,
  4715. RewriteKind rewriteKind) const {
  4716. // Look for the controlling runtime option.
  4717. Arg *runtimeArg =
  4718. args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
  4719. options::OPT_fobjc_runtime_EQ);
  4720. // Just forward -fobjc-runtime= to the frontend. This supercedes
  4721. // options about fragility.
  4722. if (runtimeArg &&
  4723. runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
  4724. ObjCRuntime runtime;
  4725. StringRef value = runtimeArg->getValue();
  4726. if (runtime.tryParse(value)) {
  4727. getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
  4728. << value;
  4729. }
  4730. runtimeArg->render(args, cmdArgs);
  4731. return runtime;
  4732. }
  4733. // Otherwise, we'll need the ABI "version". Version numbers are
  4734. // slightly confusing for historical reasons:
  4735. // 1 - Traditional "fragile" ABI
  4736. // 2 - Non-fragile ABI, version 1
  4737. // 3 - Non-fragile ABI, version 2
  4738. unsigned objcABIVersion = 1;
  4739. // If -fobjc-abi-version= is present, use that to set the version.
  4740. if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
  4741. StringRef value = abiArg->getValue();
  4742. if (value == "1")
  4743. objcABIVersion = 1;
  4744. else if (value == "2")
  4745. objcABIVersion = 2;
  4746. else if (value == "3")
  4747. objcABIVersion = 3;
  4748. else
  4749. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
  4750. } else {
  4751. // Otherwise, determine if we are using the non-fragile ABI.
  4752. bool nonFragileABIIsDefault =
  4753. (rewriteKind == RK_NonFragile ||
  4754. (rewriteKind == RK_None &&
  4755. getToolChain().IsObjCNonFragileABIDefault()));
  4756. if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
  4757. options::OPT_fno_objc_nonfragile_abi,
  4758. nonFragileABIIsDefault)) {
  4759. // Determine the non-fragile ABI version to use.
  4760. #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
  4761. unsigned nonFragileABIVersion = 1;
  4762. #else
  4763. unsigned nonFragileABIVersion = 2;
  4764. #endif
  4765. if (Arg *abiArg =
  4766. args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
  4767. StringRef value = abiArg->getValue();
  4768. if (value == "1")
  4769. nonFragileABIVersion = 1;
  4770. else if (value == "2")
  4771. nonFragileABIVersion = 2;
  4772. else
  4773. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  4774. << value;
  4775. }
  4776. objcABIVersion = 1 + nonFragileABIVersion;
  4777. } else {
  4778. objcABIVersion = 1;
  4779. }
  4780. }
  4781. // We don't actually care about the ABI version other than whether
  4782. // it's non-fragile.
  4783. bool isNonFragile = objcABIVersion != 1;
  4784. // If we have no runtime argument, ask the toolchain for its default runtime.
  4785. // However, the rewriter only really supports the Mac runtime, so assume that.
  4786. ObjCRuntime runtime;
  4787. if (!runtimeArg) {
  4788. switch (rewriteKind) {
  4789. case RK_None:
  4790. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  4791. break;
  4792. case RK_Fragile:
  4793. runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
  4794. break;
  4795. case RK_NonFragile:
  4796. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  4797. break;
  4798. }
  4799. // -fnext-runtime
  4800. } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
  4801. // On Darwin, make this use the default behavior for the toolchain.
  4802. if (getToolChain().getTriple().isOSDarwin()) {
  4803. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  4804. // Otherwise, build for a generic macosx port.
  4805. } else {
  4806. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  4807. }
  4808. // -fgnu-runtime
  4809. } else {
  4810. assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
  4811. // Legacy behaviour is to target the gnustep runtime if we are i
  4812. // non-fragile mode or the GCC runtime in fragile mode.
  4813. if (isNonFragile)
  4814. runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
  4815. else
  4816. runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
  4817. }
  4818. cmdArgs.push_back(
  4819. args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
  4820. return runtime;
  4821. }
  4822. static bool maybeConsumeDash(const std::string &EH, size_t &I) {
  4823. bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
  4824. I += HaveDash;
  4825. return !HaveDash;
  4826. }
  4827. namespace {
  4828. struct EHFlags {
  4829. EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
  4830. bool Synch;
  4831. bool Asynch;
  4832. bool NoExceptC;
  4833. };
  4834. } // end anonymous namespace
  4835. /// /EH controls whether to run destructor cleanups when exceptions are
  4836. /// thrown. There are three modifiers:
  4837. /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
  4838. /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
  4839. /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
  4840. /// - c: Assume that extern "C" functions are implicitly noexcept. This
  4841. /// modifier is an optimization, so we ignore it for now.
  4842. /// The default is /EHs-c-, meaning cleanups are disabled.
  4843. static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
  4844. EHFlags EH;
  4845. std::vector<std::string> EHArgs =
  4846. Args.getAllArgValues(options::OPT__SLASH_EH);
  4847. for (auto EHVal : EHArgs) {
  4848. for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
  4849. switch (EHVal[I]) {
  4850. case 'a':
  4851. EH.Asynch = maybeConsumeDash(EHVal, I);
  4852. continue;
  4853. case 'c':
  4854. EH.NoExceptC = maybeConsumeDash(EHVal, I);
  4855. continue;
  4856. case 's':
  4857. EH.Synch = maybeConsumeDash(EHVal, I);
  4858. continue;
  4859. default:
  4860. break;
  4861. }
  4862. D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
  4863. break;
  4864. }
  4865. }
  4866. return EH;
  4867. }
  4868. void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs,
  4869. enum CodeGenOptions::DebugInfoKind *DebugInfoKind,
  4870. bool *EmitCodeView) const {
  4871. unsigned RTOptionID = options::OPT__SLASH_MT;
  4872. if (Args.hasArg(options::OPT__SLASH_LDd))
  4873. // The /LDd option implies /MTd. The dependent lib part can be overridden,
  4874. // but defining _DEBUG is sticky.
  4875. RTOptionID = options::OPT__SLASH_MTd;
  4876. if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
  4877. RTOptionID = A->getOption().getID();
  4878. StringRef FlagForCRT;
  4879. switch (RTOptionID) {
  4880. case options::OPT__SLASH_MD:
  4881. if (Args.hasArg(options::OPT__SLASH_LDd))
  4882. CmdArgs.push_back("-D_DEBUG");
  4883. CmdArgs.push_back("-D_MT");
  4884. CmdArgs.push_back("-D_DLL");
  4885. FlagForCRT = "--dependent-lib=msvcrt";
  4886. break;
  4887. case options::OPT__SLASH_MDd:
  4888. CmdArgs.push_back("-D_DEBUG");
  4889. CmdArgs.push_back("-D_MT");
  4890. CmdArgs.push_back("-D_DLL");
  4891. FlagForCRT = "--dependent-lib=msvcrtd";
  4892. break;
  4893. case options::OPT__SLASH_MT:
  4894. if (Args.hasArg(options::OPT__SLASH_LDd))
  4895. CmdArgs.push_back("-D_DEBUG");
  4896. CmdArgs.push_back("-D_MT");
  4897. FlagForCRT = "--dependent-lib=libcmt";
  4898. break;
  4899. case options::OPT__SLASH_MTd:
  4900. CmdArgs.push_back("-D_DEBUG");
  4901. CmdArgs.push_back("-D_MT");
  4902. FlagForCRT = "--dependent-lib=libcmtd";
  4903. break;
  4904. default:
  4905. llvm_unreachable("Unexpected option ID.");
  4906. }
  4907. if (Args.hasArg(options::OPT__SLASH_Zl)) {
  4908. CmdArgs.push_back("-D_VC_NODEFAULTLIB");
  4909. } else {
  4910. CmdArgs.push_back(FlagForCRT.data());
  4911. // This provides POSIX compatibility (maps 'open' to '_open'), which most
  4912. // users want. The /Za flag to cl.exe turns this off, but it's not
  4913. // implemented in clang.
  4914. CmdArgs.push_back("--dependent-lib=oldnames");
  4915. }
  4916. // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
  4917. // would produce interleaved output, so ignore /showIncludes in such cases.
  4918. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
  4919. if (Arg *A = Args.getLastArg(options::OPT_show_includes))
  4920. A->render(Args, CmdArgs);
  4921. // This controls whether or not we emit RTTI data for polymorphic types.
  4922. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  4923. /*default=*/false))
  4924. CmdArgs.push_back("-fno-rtti-data");
  4925. // Emit CodeView if -Z7 is present.
  4926. *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
  4927. bool EmitDwarf = Args.hasArg(options::OPT_gdwarf);
  4928. // If we are emitting CV but not DWARF, don't build information that LLVM
  4929. // can't yet process.
  4930. if (*EmitCodeView && !EmitDwarf)
  4931. *DebugInfoKind = CodeGenOptions::DebugLineTablesOnly;
  4932. if (*EmitCodeView)
  4933. CmdArgs.push_back("-gcodeview");
  4934. const Driver &D = getToolChain().getDriver();
  4935. EHFlags EH = parseClangCLEHFlags(D, Args);
  4936. // FIXME: Do something with NoExceptC.
  4937. if (EH.Synch || EH.Asynch) {
  4938. CmdArgs.push_back("-fcxx-exceptions");
  4939. CmdArgs.push_back("-fexceptions");
  4940. }
  4941. // /EP should expand to -E -P.
  4942. if (Args.hasArg(options::OPT__SLASH_EP)) {
  4943. CmdArgs.push_back("-E");
  4944. CmdArgs.push_back("-P");
  4945. }
  4946. unsigned VolatileOptionID;
  4947. if (getToolChain().getArch() == llvm::Triple::x86_64 ||
  4948. getToolChain().getArch() == llvm::Triple::x86)
  4949. VolatileOptionID = options::OPT__SLASH_volatile_ms;
  4950. else
  4951. VolatileOptionID = options::OPT__SLASH_volatile_iso;
  4952. if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
  4953. VolatileOptionID = A->getOption().getID();
  4954. if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
  4955. CmdArgs.push_back("-fms-volatile");
  4956. Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
  4957. Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
  4958. if (MostGeneralArg && BestCaseArg)
  4959. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  4960. << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
  4961. if (MostGeneralArg) {
  4962. Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
  4963. Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
  4964. Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
  4965. Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
  4966. Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
  4967. if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
  4968. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  4969. << FirstConflict->getAsString(Args)
  4970. << SecondConflict->getAsString(Args);
  4971. if (SingleArg)
  4972. CmdArgs.push_back("-fms-memptr-rep=single");
  4973. else if (MultipleArg)
  4974. CmdArgs.push_back("-fms-memptr-rep=multiple");
  4975. else
  4976. CmdArgs.push_back("-fms-memptr-rep=virtual");
  4977. }
  4978. if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
  4979. A->render(Args, CmdArgs);
  4980. if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
  4981. CmdArgs.push_back("-fdiagnostics-format");
  4982. if (Args.hasArg(options::OPT__SLASH_fallback))
  4983. CmdArgs.push_back("msvc-fallback");
  4984. else
  4985. CmdArgs.push_back("msvc");
  4986. }
  4987. }
  4988. visualstudio::Compiler *Clang::getCLFallback() const {
  4989. if (!CLFallback)
  4990. CLFallback.reset(new visualstudio::Compiler(getToolChain()));
  4991. return CLFallback.get();
  4992. }
  4993. void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
  4994. ArgStringList &CmdArgs) const {
  4995. StringRef CPUName;
  4996. StringRef ABIName;
  4997. const llvm::Triple &Triple = getToolChain().getTriple();
  4998. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  4999. CmdArgs.push_back("-target-abi");
  5000. CmdArgs.push_back(ABIName.data());
  5001. }
  5002. void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
  5003. const InputInfo &Output, const InputInfoList &Inputs,
  5004. const ArgList &Args,
  5005. const char *LinkingOutput) const {
  5006. ArgStringList CmdArgs;
  5007. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  5008. const InputInfo &Input = Inputs[0];
  5009. std::string TripleStr =
  5010. getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
  5011. const llvm::Triple Triple(TripleStr);
  5012. // Don't warn about "clang -w -c foo.s"
  5013. Args.ClaimAllArgs(options::OPT_w);
  5014. // and "clang -emit-llvm -c foo.s"
  5015. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5016. claimNoWarnArgs(Args);
  5017. // Invoke ourselves in -cc1as mode.
  5018. //
  5019. // FIXME: Implement custom jobs for internal actions.
  5020. CmdArgs.push_back("-cc1as");
  5021. // Add the "effective" target triple.
  5022. CmdArgs.push_back("-triple");
  5023. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  5024. // Set the output mode, we currently only expect to be used as a real
  5025. // assembler.
  5026. CmdArgs.push_back("-filetype");
  5027. CmdArgs.push_back("obj");
  5028. // Set the main file name, so that debug info works even with
  5029. // -save-temps or preprocessed assembly.
  5030. CmdArgs.push_back("-main-file-name");
  5031. CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
  5032. // Add the target cpu
  5033. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
  5034. if (!CPU.empty()) {
  5035. CmdArgs.push_back("-target-cpu");
  5036. CmdArgs.push_back(Args.MakeArgString(CPU));
  5037. }
  5038. // Add the target features
  5039. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
  5040. // Ignore explicit -force_cpusubtype_ALL option.
  5041. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  5042. // Pass along any -I options so we get proper .include search paths.
  5043. Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
  5044. // Determine the original source input.
  5045. const Action *SourceAction = &JA;
  5046. while (SourceAction->getKind() != Action::InputClass) {
  5047. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  5048. SourceAction = SourceAction->getInputs()[0];
  5049. }
  5050. // Forward -g and handle debug info related flags, assuming we are dealing
  5051. // with an actual assembly file.
  5052. if (SourceAction->getType() == types::TY_Asm ||
  5053. SourceAction->getType() == types::TY_PP_Asm) {
  5054. bool WantDebug = false;
  5055. unsigned DwarfVersion = 0;
  5056. Args.ClaimAllArgs(options::OPT_g_Group);
  5057. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  5058. WantDebug = !A->getOption().matches(options::OPT_g0);
  5059. if (WantDebug)
  5060. DwarfVersion = DwarfVersionNum(A->getSpelling());
  5061. }
  5062. if (DwarfVersion == 0)
  5063. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  5064. RenderDebugEnablingArgs(Args, CmdArgs,
  5065. (WantDebug ? CodeGenOptions::LimitedDebugInfo
  5066. : CodeGenOptions::NoDebugInfo),
  5067. DwarfVersion);
  5068. // Add the -fdebug-compilation-dir flag if needed.
  5069. addDebugCompDirArg(Args, CmdArgs);
  5070. // Set the AT_producer to the clang version when using the integrated
  5071. // assembler on assembly source files.
  5072. CmdArgs.push_back("-dwarf-debug-producer");
  5073. CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
  5074. // And pass along -I options
  5075. Args.AddAllArgs(CmdArgs, options::OPT_I);
  5076. }
  5077. // Handle -fPIC et al -- the relocation-model affects the assembler
  5078. // for some targets.
  5079. llvm::Reloc::Model RelocationModel;
  5080. unsigned PICLevel;
  5081. bool IsPIE;
  5082. std::tie(RelocationModel, PICLevel, IsPIE) =
  5083. ParsePICArgs(getToolChain(), Triple, Args);
  5084. const char *RMName = RelocationModelName(RelocationModel);
  5085. if (RMName) {
  5086. CmdArgs.push_back("-mrelocation-model");
  5087. CmdArgs.push_back(RMName);
  5088. }
  5089. // Optionally embed the -cc1as level arguments into the debug info, for build
  5090. // analysis.
  5091. if (getToolChain().UseDwarfDebugFlags()) {
  5092. ArgStringList OriginalArgs;
  5093. for (const auto &Arg : Args)
  5094. Arg->render(Args, OriginalArgs);
  5095. SmallString<256> Flags;
  5096. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5097. Flags += Exec;
  5098. for (const char *OriginalArg : OriginalArgs) {
  5099. SmallString<128> EscapedArg;
  5100. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  5101. Flags += " ";
  5102. Flags += EscapedArg;
  5103. }
  5104. CmdArgs.push_back("-dwarf-debug-flags");
  5105. CmdArgs.push_back(Args.MakeArgString(Flags));
  5106. }
  5107. // FIXME: Add -static support, once we have it.
  5108. // Add target specific flags.
  5109. switch (getToolChain().getArch()) {
  5110. default:
  5111. break;
  5112. case llvm::Triple::mips:
  5113. case llvm::Triple::mipsel:
  5114. case llvm::Triple::mips64:
  5115. case llvm::Triple::mips64el:
  5116. AddMIPSTargetArgs(Args, CmdArgs);
  5117. break;
  5118. }
  5119. // Consume all the warning flags. Usually this would be handled more
  5120. // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
  5121. // doesn't handle that so rather than warning about unused flags that are
  5122. // actually used, we'll lie by omission instead.
  5123. // FIXME: Stop lying and consume only the appropriate driver flags
  5124. for (const Arg *A : Args.filtered(options::OPT_W_Group))
  5125. A->claim();
  5126. CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
  5127. getToolChain().getDriver());
  5128. Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
  5129. assert(Output.isFilename() && "Unexpected lipo output.");
  5130. CmdArgs.push_back("-o");
  5131. CmdArgs.push_back(Output.getFilename());
  5132. assert(Input.isFilename() && "Invalid input.");
  5133. CmdArgs.push_back(Input.getFilename());
  5134. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5135. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5136. // Handle the debug info splitting at object creation time if we're
  5137. // creating an object.
  5138. // TODO: Currently only works on linux with newer objcopy.
  5139. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  5140. getToolChain().getTriple().isOSLinux())
  5141. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  5142. SplitDebugName(Args, Input));
  5143. }
  5144. void GnuTool::anchor() {}
  5145. void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
  5146. const InputInfo &Output,
  5147. const InputInfoList &Inputs, const ArgList &Args,
  5148. const char *LinkingOutput) const {
  5149. const Driver &D = getToolChain().getDriver();
  5150. ArgStringList CmdArgs;
  5151. for (const auto &A : Args) {
  5152. if (forwardToGCC(A->getOption())) {
  5153. // Don't forward any -g arguments to assembly steps.
  5154. if (isa<AssembleJobAction>(JA) &&
  5155. A->getOption().matches(options::OPT_g_Group))
  5156. continue;
  5157. // Don't forward any -W arguments to assembly and link steps.
  5158. if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
  5159. A->getOption().matches(options::OPT_W_Group))
  5160. continue;
  5161. // It is unfortunate that we have to claim here, as this means
  5162. // we will basically never report anything interesting for
  5163. // platforms using a generic gcc, even if we are just using gcc
  5164. // to get to the assembler.
  5165. A->claim();
  5166. A->render(Args, CmdArgs);
  5167. }
  5168. }
  5169. RenderExtraToolArgs(JA, CmdArgs);
  5170. // If using a driver driver, force the arch.
  5171. if (getToolChain().getTriple().isOSDarwin()) {
  5172. CmdArgs.push_back("-arch");
  5173. CmdArgs.push_back(
  5174. Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
  5175. }
  5176. // Try to force gcc to match the tool chain we want, if we recognize
  5177. // the arch.
  5178. //
  5179. // FIXME: The triple class should directly provide the information we want
  5180. // here.
  5181. switch (getToolChain().getArch()) {
  5182. default:
  5183. break;
  5184. case llvm::Triple::x86:
  5185. case llvm::Triple::ppc:
  5186. CmdArgs.push_back("-m32");
  5187. break;
  5188. case llvm::Triple::x86_64:
  5189. case llvm::Triple::ppc64:
  5190. case llvm::Triple::ppc64le:
  5191. CmdArgs.push_back("-m64");
  5192. break;
  5193. case llvm::Triple::sparcel:
  5194. CmdArgs.push_back("-EL");
  5195. break;
  5196. }
  5197. if (Output.isFilename()) {
  5198. CmdArgs.push_back("-o");
  5199. CmdArgs.push_back(Output.getFilename());
  5200. } else {
  5201. assert(Output.isNothing() && "Unexpected output");
  5202. CmdArgs.push_back("-fsyntax-only");
  5203. }
  5204. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5205. // Only pass -x if gcc will understand it; otherwise hope gcc
  5206. // understands the suffix correctly. The main use case this would go
  5207. // wrong in is for linker inputs if they happened to have an odd
  5208. // suffix; really the only way to get this to happen is a command
  5209. // like '-x foobar a.c' which will treat a.c like a linker input.
  5210. //
  5211. // FIXME: For the linker case specifically, can we safely convert
  5212. // inputs into '-Wl,' options?
  5213. for (const auto &II : Inputs) {
  5214. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5215. if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
  5216. II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
  5217. D.Diag(diag::err_drv_no_linker_llvm_support)
  5218. << getToolChain().getTripleString();
  5219. else if (II.getType() == types::TY_AST)
  5220. D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
  5221. else if (II.getType() == types::TY_ModuleFile)
  5222. D.Diag(diag::err_drv_no_module_support)
  5223. << getToolChain().getTripleString();
  5224. if (types::canTypeBeUserSpecified(II.getType())) {
  5225. CmdArgs.push_back("-x");
  5226. CmdArgs.push_back(types::getTypeName(II.getType()));
  5227. }
  5228. if (II.isFilename())
  5229. CmdArgs.push_back(II.getFilename());
  5230. else {
  5231. const Arg &A = II.getInputArg();
  5232. // Reverse translate some rewritten options.
  5233. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
  5234. CmdArgs.push_back("-lstdc++");
  5235. continue;
  5236. }
  5237. // Don't render as input, we need gcc to do the translations.
  5238. A.render(Args, CmdArgs);
  5239. }
  5240. }
  5241. const std::string customGCCName = D.getCCCGenericGCCName();
  5242. const char *GCCName;
  5243. if (!customGCCName.empty())
  5244. GCCName = customGCCName.c_str();
  5245. else if (D.CCCIsCXX()) {
  5246. GCCName = "g++";
  5247. } else
  5248. GCCName = "gcc";
  5249. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
  5250. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5251. }
  5252. void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
  5253. ArgStringList &CmdArgs) const {
  5254. CmdArgs.push_back("-E");
  5255. }
  5256. void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
  5257. ArgStringList &CmdArgs) const {
  5258. const Driver &D = getToolChain().getDriver();
  5259. switch (JA.getType()) {
  5260. // If -flto, etc. are present then make sure not to force assembly output.
  5261. case types::TY_LLVM_IR:
  5262. case types::TY_LTO_IR:
  5263. case types::TY_LLVM_BC:
  5264. case types::TY_LTO_BC:
  5265. CmdArgs.push_back("-c");
  5266. break;
  5267. case types::TY_PP_Asm:
  5268. CmdArgs.push_back("-S");
  5269. break;
  5270. case types::TY_Nothing:
  5271. CmdArgs.push_back("-fsyntax-only");
  5272. break;
  5273. default:
  5274. D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
  5275. }
  5276. }
  5277. void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
  5278. ArgStringList &CmdArgs) const {
  5279. // The types are (hopefully) good enough.
  5280. }
  5281. // Hexagon tools start.
  5282. void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
  5283. ArgStringList &CmdArgs) const {}
  5284. void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  5285. const InputInfo &Output,
  5286. const InputInfoList &Inputs,
  5287. const ArgList &Args,
  5288. const char *LinkingOutput) const {
  5289. claimNoWarnArgs(Args);
  5290. const Driver &D = getToolChain().getDriver();
  5291. ArgStringList CmdArgs;
  5292. std::string MarchString = "-march=";
  5293. MarchString += toolchains::HexagonToolChain::GetTargetCPU(Args);
  5294. CmdArgs.push_back(Args.MakeArgString(MarchString));
  5295. RenderExtraToolArgs(JA, CmdArgs);
  5296. if (Output.isFilename()) {
  5297. CmdArgs.push_back("-o");
  5298. CmdArgs.push_back(Output.getFilename());
  5299. } else {
  5300. assert(Output.isNothing() && "Unexpected output");
  5301. CmdArgs.push_back("-fsyntax-only");
  5302. }
  5303. if (const char *v = toolchains::HexagonToolChain::GetSmallDataThreshold(Args))
  5304. CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
  5305. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5306. // Only pass -x if gcc will understand it; otherwise hope gcc
  5307. // understands the suffix correctly. The main use case this would go
  5308. // wrong in is for linker inputs if they happened to have an odd
  5309. // suffix; really the only way to get this to happen is a command
  5310. // like '-x foobar a.c' which will treat a.c like a linker input.
  5311. //
  5312. // FIXME: For the linker case specifically, can we safely convert
  5313. // inputs into '-Wl,' options?
  5314. for (const auto &II : Inputs) {
  5315. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5316. if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
  5317. II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
  5318. D.Diag(clang::diag::err_drv_no_linker_llvm_support)
  5319. << getToolChain().getTripleString();
  5320. else if (II.getType() == types::TY_AST)
  5321. D.Diag(clang::diag::err_drv_no_ast_support)
  5322. << getToolChain().getTripleString();
  5323. else if (II.getType() == types::TY_ModuleFile)
  5324. D.Diag(diag::err_drv_no_module_support)
  5325. << getToolChain().getTripleString();
  5326. if (II.isFilename())
  5327. CmdArgs.push_back(II.getFilename());
  5328. else
  5329. // Don't render as input, we need gcc to do the translations.
  5330. // FIXME: Pranav: What is this ?
  5331. II.getInputArg().render(Args, CmdArgs);
  5332. }
  5333. const char *GCCName = "hexagon-as";
  5334. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
  5335. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5336. }
  5337. void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
  5338. ArgStringList &CmdArgs) const {
  5339. // The types are (hopefully) good enough.
  5340. }
  5341. static void
  5342. constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
  5343. const toolchains::HexagonToolChain &ToolChain,
  5344. const InputInfo &Output, const InputInfoList &Inputs,
  5345. const ArgList &Args, ArgStringList &CmdArgs,
  5346. const char *LinkingOutput) {
  5347. const Driver &D = ToolChain.getDriver();
  5348. //----------------------------------------------------------------------------
  5349. //
  5350. //----------------------------------------------------------------------------
  5351. bool hasStaticArg = Args.hasArg(options::OPT_static);
  5352. bool buildingLib = Args.hasArg(options::OPT_shared);
  5353. bool buildPIE = Args.hasArg(options::OPT_pie);
  5354. bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
  5355. bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
  5356. bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
  5357. bool useG0 = false;
  5358. bool useShared = buildingLib && !hasStaticArg;
  5359. //----------------------------------------------------------------------------
  5360. // Silence warnings for various options
  5361. //----------------------------------------------------------------------------
  5362. Args.ClaimAllArgs(options::OPT_g_Group);
  5363. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5364. Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
  5365. // handled somewhere else.
  5366. Args.ClaimAllArgs(options::OPT_static_libgcc);
  5367. //----------------------------------------------------------------------------
  5368. //
  5369. //----------------------------------------------------------------------------
  5370. for (const auto &Opt : ToolChain.ExtraOpts)
  5371. CmdArgs.push_back(Opt.c_str());
  5372. std::string MarchString = toolchains::HexagonToolChain::GetTargetCPU(Args);
  5373. CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
  5374. if (buildingLib) {
  5375. CmdArgs.push_back("-shared");
  5376. CmdArgs.push_back("-call_shared"); // should be the default, but doing as
  5377. // hexagon-gcc does
  5378. }
  5379. if (hasStaticArg)
  5380. CmdArgs.push_back("-static");
  5381. if (buildPIE && !buildingLib)
  5382. CmdArgs.push_back("-pie");
  5383. if (const char *v =
  5384. toolchains::HexagonToolChain::GetSmallDataThreshold(Args)) {
  5385. CmdArgs.push_back(Args.MakeArgString(std::string("-G") + v));
  5386. useG0 = toolchains::HexagonToolChain::UsesG0(v);
  5387. }
  5388. //----------------------------------------------------------------------------
  5389. //
  5390. //----------------------------------------------------------------------------
  5391. CmdArgs.push_back("-o");
  5392. CmdArgs.push_back(Output.getFilename());
  5393. const std::string MarchSuffix = "/" + MarchString;
  5394. const std::string G0Suffix = "/G0";
  5395. const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
  5396. const std::string RootDir = ToolChain.GetGnuDir(D.InstalledDir, Args) + "/";
  5397. const std::string StartFilesDir =
  5398. RootDir + "hexagon/lib" + (useG0 ? MarchG0Suffix : MarchSuffix);
  5399. //----------------------------------------------------------------------------
  5400. // moslib
  5401. //----------------------------------------------------------------------------
  5402. std::vector<std::string> oslibs;
  5403. bool hasStandalone = false;
  5404. for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
  5405. A->claim();
  5406. oslibs.emplace_back(A->getValue());
  5407. hasStandalone = hasStandalone || (oslibs.back() == "standalone");
  5408. }
  5409. if (oslibs.empty()) {
  5410. oslibs.push_back("standalone");
  5411. hasStandalone = true;
  5412. }
  5413. //----------------------------------------------------------------------------
  5414. // Start Files
  5415. //----------------------------------------------------------------------------
  5416. if (incStdLib && incStartFiles) {
  5417. if (!buildingLib) {
  5418. if (hasStandalone) {
  5419. CmdArgs.push_back(
  5420. Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
  5421. }
  5422. CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
  5423. }
  5424. std::string initObj = useShared ? "/initS.o" : "/init.o";
  5425. CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
  5426. }
  5427. //----------------------------------------------------------------------------
  5428. // Library Search Paths
  5429. //----------------------------------------------------------------------------
  5430. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  5431. //----------------------------------------------------------------------------
  5432. //
  5433. //----------------------------------------------------------------------------
  5434. Args.AddAllArgs(CmdArgs,
  5435. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  5436. options::OPT_t, options::OPT_u_Group});
  5437. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  5438. //----------------------------------------------------------------------------
  5439. // Libraries
  5440. //----------------------------------------------------------------------------
  5441. if (incStdLib && incDefLibs) {
  5442. if (D.CCCIsCXX()) {
  5443. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  5444. CmdArgs.push_back("-lm");
  5445. }
  5446. CmdArgs.push_back("--start-group");
  5447. if (!buildingLib) {
  5448. for (const std::string &Lib : oslibs)
  5449. CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
  5450. CmdArgs.push_back("-lc");
  5451. }
  5452. CmdArgs.push_back("-lgcc");
  5453. CmdArgs.push_back("--end-group");
  5454. }
  5455. //----------------------------------------------------------------------------
  5456. // End files
  5457. //----------------------------------------------------------------------------
  5458. if (incStdLib && incStartFiles) {
  5459. std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
  5460. CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
  5461. }
  5462. }
  5463. void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5464. const InputInfo &Output,
  5465. const InputInfoList &Inputs,
  5466. const ArgList &Args,
  5467. const char *LinkingOutput) const {
  5468. const toolchains::HexagonToolChain &ToolChain =
  5469. static_cast<const toolchains::HexagonToolChain &>(getToolChain());
  5470. ArgStringList CmdArgs;
  5471. constructHexagonLinkArgs(C, JA, ToolChain, Output, Inputs, Args, CmdArgs,
  5472. LinkingOutput);
  5473. std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
  5474. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  5475. CmdArgs, Inputs));
  5476. }
  5477. // Hexagon tools end.
  5478. void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5479. const InputInfo &Output,
  5480. const InputInfoList &Inputs,
  5481. const ArgList &Args,
  5482. const char *LinkingOutput) const {
  5483. std::string Linker = getToolChain().GetProgramPath(getShortName());
  5484. ArgStringList CmdArgs;
  5485. CmdArgs.push_back("-flavor");
  5486. CmdArgs.push_back("old-gnu");
  5487. CmdArgs.push_back("-target");
  5488. CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
  5489. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  5490. CmdArgs.push_back("-o");
  5491. CmdArgs.push_back(Output.getFilename());
  5492. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  5493. CmdArgs, Inputs));
  5494. }
  5495. // AMDGPU tools end.
  5496. const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
  5497. std::string MArch;
  5498. if (!Arch.empty())
  5499. MArch = Arch;
  5500. else
  5501. MArch = Triple.getArchName();
  5502. MArch = StringRef(MArch).split("+").first.lower();
  5503. // Handle -march=native.
  5504. if (MArch == "native") {
  5505. std::string CPU = llvm::sys::getHostCPUName();
  5506. if (CPU != "generic") {
  5507. // Translate the native cpu into the architecture suffix for that CPU.
  5508. StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
  5509. // If there is no valid architecture suffix for this CPU we don't know how
  5510. // to handle it, so return no architecture.
  5511. if (Suffix.empty())
  5512. MArch = "";
  5513. else
  5514. MArch = std::string("arm") + Suffix.str();
  5515. }
  5516. }
  5517. return MArch;
  5518. }
  5519. /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
  5520. StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
  5521. std::string MArch = getARMArch(Arch, Triple);
  5522. // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
  5523. // here means an -march=native that we can't handle, so instead return no CPU.
  5524. if (MArch.empty())
  5525. return StringRef();
  5526. // We need to return an empty string here on invalid MArch values as the
  5527. // various places that call this function can't cope with a null result.
  5528. return Triple.getARMCPUForArch(MArch);
  5529. }
  5530. /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
  5531. std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
  5532. const llvm::Triple &Triple) {
  5533. // FIXME: Warn on inconsistent use of -mcpu and -march.
  5534. // If we have -mcpu=, use that.
  5535. if (!CPU.empty()) {
  5536. std::string MCPU = StringRef(CPU).split("+").first.lower();
  5537. // Handle -mcpu=native.
  5538. if (MCPU == "native")
  5539. return llvm::sys::getHostCPUName();
  5540. else
  5541. return MCPU;
  5542. }
  5543. return getARMCPUForMArch(Arch, Triple);
  5544. }
  5545. /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
  5546. /// CPU (or Arch, if CPU is generic).
  5547. // FIXME: This is redundant with -mcpu, why does LLVM use this.
  5548. StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
  5549. const llvm::Triple &Triple) {
  5550. unsigned ArchKind;
  5551. if (CPU == "generic") {
  5552. std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
  5553. ArchKind = llvm::ARM::parseArch(ARMArch);
  5554. if (ArchKind == llvm::ARM::AK_INVALID)
  5555. // In case of generic Arch, i.e. "arm",
  5556. // extract arch from default cpu of the Triple
  5557. ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
  5558. } else {
  5559. // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
  5560. // armv7k triple if it's actually been specified via "-arch armv7k".
  5561. ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
  5562. ? (unsigned)llvm::ARM::AK_ARMV7K
  5563. : llvm::ARM::parseCPUArch(CPU);
  5564. }
  5565. if (ArchKind == llvm::ARM::AK_INVALID)
  5566. return "";
  5567. return llvm::ARM::getSubArch(ArchKind);
  5568. }
  5569. void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
  5570. const llvm::Triple &Triple) {
  5571. if (Args.hasArg(options::OPT_r))
  5572. return;
  5573. // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
  5574. // to generate BE-8 executables.
  5575. if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
  5576. CmdArgs.push_back("--be8");
  5577. }
  5578. mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
  5579. // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
  5580. // was first introduced in Release 3. However, other compilers have
  5581. // traditionally allowed it for Release 2 so we should do the same.
  5582. return (NanEncoding)llvm::StringSwitch<int>(CPU)
  5583. .Case("mips1", NanLegacy)
  5584. .Case("mips2", NanLegacy)
  5585. .Case("mips3", NanLegacy)
  5586. .Case("mips4", NanLegacy)
  5587. .Case("mips5", NanLegacy)
  5588. .Case("mips32", NanLegacy)
  5589. .Case("mips32r2", NanLegacy | Nan2008)
  5590. .Case("mips32r3", NanLegacy | Nan2008)
  5591. .Case("mips32r5", NanLegacy | Nan2008)
  5592. .Case("mips32r6", Nan2008)
  5593. .Case("mips64", NanLegacy)
  5594. .Case("mips64r2", NanLegacy | Nan2008)
  5595. .Case("mips64r3", NanLegacy | Nan2008)
  5596. .Case("mips64r5", NanLegacy | Nan2008)
  5597. .Case("mips64r6", Nan2008)
  5598. .Default(NanLegacy);
  5599. }
  5600. bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
  5601. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  5602. return A && (A->getValue() == StringRef(Value));
  5603. }
  5604. bool mips::isUCLibc(const ArgList &Args) {
  5605. Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
  5606. return A && A->getOption().matches(options::OPT_muclibc);
  5607. }
  5608. bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
  5609. if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
  5610. return llvm::StringSwitch<bool>(NaNArg->getValue())
  5611. .Case("2008", true)
  5612. .Case("legacy", false)
  5613. .Default(false);
  5614. // NaN2008 is the default for MIPS32r6/MIPS64r6.
  5615. return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
  5616. .Cases("mips32r6", "mips64r6", true)
  5617. .Default(false);
  5618. return false;
  5619. }
  5620. bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
  5621. StringRef ABIName, mips::FloatABI FloatABI) {
  5622. if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
  5623. Triple.getVendor() != llvm::Triple::MipsTechnologies)
  5624. return false;
  5625. if (ABIName != "32")
  5626. return false;
  5627. // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
  5628. // present.
  5629. if (FloatABI == mips::FloatABI::Soft)
  5630. return false;
  5631. return llvm::StringSwitch<bool>(CPUName)
  5632. .Cases("mips2", "mips3", "mips4", "mips5", true)
  5633. .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
  5634. .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
  5635. .Default(false);
  5636. }
  5637. bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
  5638. StringRef CPUName, StringRef ABIName,
  5639. mips::FloatABI FloatABI) {
  5640. bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
  5641. // FPXX shouldn't be used if -msingle-float is present.
  5642. if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
  5643. options::OPT_mdouble_float))
  5644. if (A->getOption().matches(options::OPT_msingle_float))
  5645. UseFPXX = false;
  5646. return UseFPXX;
  5647. }
  5648. llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
  5649. // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
  5650. // archs which Darwin doesn't use.
  5651. // The matching this routine does is fairly pointless, since it is neither the
  5652. // complete architecture list, nor a reasonable subset. The problem is that
  5653. // historically the driver driver accepts this and also ties its -march=
  5654. // handling to the architecture name, so we need to be careful before removing
  5655. // support for it.
  5656. // This code must be kept in sync with Clang's Darwin specific argument
  5657. // translation.
  5658. return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
  5659. .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
  5660. .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
  5661. .Case("ppc64", llvm::Triple::ppc64)
  5662. .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
  5663. .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
  5664. llvm::Triple::x86)
  5665. .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
  5666. // This is derived from the driver driver.
  5667. .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
  5668. .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
  5669. .Cases("armv7s", "xscale", llvm::Triple::arm)
  5670. .Case("arm64", llvm::Triple::aarch64)
  5671. .Case("r600", llvm::Triple::r600)
  5672. .Case("amdgcn", llvm::Triple::amdgcn)
  5673. .Case("nvptx", llvm::Triple::nvptx)
  5674. .Case("nvptx64", llvm::Triple::nvptx64)
  5675. .Case("amdil", llvm::Triple::amdil)
  5676. .Case("spir", llvm::Triple::spir)
  5677. .Default(llvm::Triple::UnknownArch);
  5678. }
  5679. void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
  5680. const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
  5681. T.setArch(Arch);
  5682. if (Str == "x86_64h")
  5683. T.setArchName(Str);
  5684. else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
  5685. T.setOS(llvm::Triple::UnknownOS);
  5686. T.setObjectFormat(llvm::Triple::MachO);
  5687. }
  5688. }
  5689. const char *Clang::getBaseInputName(const ArgList &Args,
  5690. const InputInfo &Input) {
  5691. return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
  5692. }
  5693. const char *Clang::getBaseInputStem(const ArgList &Args,
  5694. const InputInfoList &Inputs) {
  5695. const char *Str = getBaseInputName(Args, Inputs[0]);
  5696. if (const char *End = strrchr(Str, '.'))
  5697. return Args.MakeArgString(std::string(Str, End));
  5698. return Str;
  5699. }
  5700. const char *Clang::getDependencyFileName(const ArgList &Args,
  5701. const InputInfoList &Inputs) {
  5702. // FIXME: Think about this more.
  5703. std::string Res;
  5704. if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
  5705. std::string Str(OutputOpt->getValue());
  5706. Res = Str.substr(0, Str.rfind('.'));
  5707. } else {
  5708. Res = getBaseInputStem(Args, Inputs);
  5709. }
  5710. return Args.MakeArgString(Res + ".d");
  5711. }
  5712. void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5713. const InputInfo &Output,
  5714. const InputInfoList &Inputs,
  5715. const ArgList &Args,
  5716. const char *LinkingOutput) const {
  5717. const ToolChain &ToolChain = getToolChain();
  5718. const Driver &D = ToolChain.getDriver();
  5719. ArgStringList CmdArgs;
  5720. // Silence warning for "clang -g foo.o -o foo"
  5721. Args.ClaimAllArgs(options::OPT_g_Group);
  5722. // and "clang -emit-llvm foo.o -o foo"
  5723. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5724. // and for "clang -w foo.o -o foo". Other warning options are already
  5725. // handled somewhere else.
  5726. Args.ClaimAllArgs(options::OPT_w);
  5727. if (!D.SysRoot.empty())
  5728. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  5729. // CloudABI only supports static linkage.
  5730. CmdArgs.push_back("-Bstatic");
  5731. CmdArgs.push_back("--eh-frame-hdr");
  5732. CmdArgs.push_back("--gc-sections");
  5733. if (Output.isFilename()) {
  5734. CmdArgs.push_back("-o");
  5735. CmdArgs.push_back(Output.getFilename());
  5736. } else {
  5737. assert(Output.isNothing() && "Invalid output.");
  5738. }
  5739. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  5740. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
  5741. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
  5742. }
  5743. Args.AddAllArgs(CmdArgs, options::OPT_L);
  5744. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  5745. Args.AddAllArgs(CmdArgs,
  5746. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  5747. options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
  5748. if (D.isUsingLTO())
  5749. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  5750. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  5751. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  5752. if (D.CCCIsCXX())
  5753. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  5754. CmdArgs.push_back("-lc");
  5755. CmdArgs.push_back("-lcompiler_rt");
  5756. }
  5757. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  5758. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  5759. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  5760. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5761. }
  5762. void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  5763. const InputInfo &Output,
  5764. const InputInfoList &Inputs,
  5765. const ArgList &Args,
  5766. const char *LinkingOutput) const {
  5767. ArgStringList CmdArgs;
  5768. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  5769. const InputInfo &Input = Inputs[0];
  5770. // Determine the original source input.
  5771. const Action *SourceAction = &JA;
  5772. while (SourceAction->getKind() != Action::InputClass) {
  5773. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  5774. SourceAction = SourceAction->getInputs()[0];
  5775. }
  5776. // If -fno_integrated_as is used add -Q to the darwin assember driver to make
  5777. // sure it runs its system assembler not clang's integrated assembler.
  5778. // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
  5779. // FIXME: at run-time detect assembler capabilities or rely on version
  5780. // information forwarded by -target-assembler-version (future)
  5781. if (Args.hasArg(options::OPT_fno_integrated_as)) {
  5782. const llvm::Triple &T(getToolChain().getTriple());
  5783. if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
  5784. CmdArgs.push_back("-Q");
  5785. }
  5786. // Forward -g, assuming we are dealing with an actual assembly file.
  5787. if (SourceAction->getType() == types::TY_Asm ||
  5788. SourceAction->getType() == types::TY_PP_Asm) {
  5789. if (Args.hasArg(options::OPT_gstabs))
  5790. CmdArgs.push_back("--gstabs");
  5791. else if (Args.hasArg(options::OPT_g_Group))
  5792. CmdArgs.push_back("-g");
  5793. }
  5794. // Derived from asm spec.
  5795. AddMachOArch(Args, CmdArgs);
  5796. // Use -force_cpusubtype_ALL on x86 by default.
  5797. if (getToolChain().getArch() == llvm::Triple::x86 ||
  5798. getToolChain().getArch() == llvm::Triple::x86_64 ||
  5799. Args.hasArg(options::OPT_force__cpusubtype__ALL))
  5800. CmdArgs.push_back("-force_cpusubtype_ALL");
  5801. if (getToolChain().getArch() != llvm::Triple::x86_64 &&
  5802. (((Args.hasArg(options::OPT_mkernel) ||
  5803. Args.hasArg(options::OPT_fapple_kext)) &&
  5804. getMachOToolChain().isKernelStatic()) ||
  5805. Args.hasArg(options::OPT_static)))
  5806. CmdArgs.push_back("-static");
  5807. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5808. assert(Output.isFilename() && "Unexpected lipo output.");
  5809. CmdArgs.push_back("-o");
  5810. CmdArgs.push_back(Output.getFilename());
  5811. assert(Input.isFilename() && "Invalid input.");
  5812. CmdArgs.push_back(Input.getFilename());
  5813. // asm_final spec is empty.
  5814. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  5815. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5816. }
  5817. void darwin::MachOTool::anchor() {}
  5818. void darwin::MachOTool::AddMachOArch(const ArgList &Args,
  5819. ArgStringList &CmdArgs) const {
  5820. StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
  5821. // Derived from darwin_arch spec.
  5822. CmdArgs.push_back("-arch");
  5823. CmdArgs.push_back(Args.MakeArgString(ArchName));
  5824. // FIXME: Is this needed anymore?
  5825. if (ArchName == "arm")
  5826. CmdArgs.push_back("-force_cpusubtype_ALL");
  5827. }
  5828. bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
  5829. // We only need to generate a temp path for LTO if we aren't compiling object
  5830. // files. When compiling source files, we run 'dsymutil' after linking. We
  5831. // don't run 'dsymutil' when compiling object files.
  5832. for (const auto &Input : Inputs)
  5833. if (Input.getType() != types::TY_Object)
  5834. return true;
  5835. return false;
  5836. }
  5837. void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
  5838. ArgStringList &CmdArgs,
  5839. const InputInfoList &Inputs) const {
  5840. const Driver &D = getToolChain().getDriver();
  5841. const toolchains::MachO &MachOTC = getMachOToolChain();
  5842. unsigned Version[3] = {0, 0, 0};
  5843. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  5844. bool HadExtra;
  5845. if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
  5846. Version[2], HadExtra) ||
  5847. HadExtra)
  5848. D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
  5849. }
  5850. // Newer linkers support -demangle. Pass it if supported and not disabled by
  5851. // the user.
  5852. if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  5853. CmdArgs.push_back("-demangle");
  5854. if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
  5855. CmdArgs.push_back("-export_dynamic");
  5856. // If we are using App Extension restrictions, pass a flag to the linker
  5857. // telling it that the compiled code has been audited.
  5858. if (Args.hasFlag(options::OPT_fapplication_extension,
  5859. options::OPT_fno_application_extension, false))
  5860. CmdArgs.push_back("-application_extension");
  5861. if (D.isUsingLTO()) {
  5862. // If we are using LTO, then automatically create a temporary file path for
  5863. // the linker to use, so that it's lifetime will extend past a possible
  5864. // dsymutil step.
  5865. if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
  5866. const char *TmpPath = C.getArgs().MakeArgString(
  5867. D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
  5868. C.addTempFile(TmpPath);
  5869. CmdArgs.push_back("-object_path_lto");
  5870. CmdArgs.push_back(TmpPath);
  5871. }
  5872. // Use -lto_library option to specify the libLTO.dylib path. Try to find
  5873. // it in clang installed libraries. If not found, the option is not used
  5874. // and 'ld' will use its default mechanism to search for libLTO.dylib.
  5875. if (Version[0] >= 133) {
  5876. // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
  5877. StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
  5878. SmallString<128> LibLTOPath(P);
  5879. llvm::sys::path::append(LibLTOPath, "lib");
  5880. llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
  5881. if (llvm::sys::fs::exists(LibLTOPath)) {
  5882. CmdArgs.push_back("-lto_library");
  5883. CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
  5884. } else {
  5885. D.Diag(diag::warn_drv_lto_libpath);
  5886. }
  5887. }
  5888. }
  5889. // Derived from the "link" spec.
  5890. Args.AddAllArgs(CmdArgs, options::OPT_static);
  5891. if (!Args.hasArg(options::OPT_static))
  5892. CmdArgs.push_back("-dynamic");
  5893. if (Args.hasArg(options::OPT_fgnu_runtime)) {
  5894. // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
  5895. // here. How do we wish to handle such things?
  5896. }
  5897. if (!Args.hasArg(options::OPT_dynamiclib)) {
  5898. AddMachOArch(Args, CmdArgs);
  5899. // FIXME: Why do this only on this path?
  5900. Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
  5901. Args.AddLastArg(CmdArgs, options::OPT_bundle);
  5902. Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
  5903. Args.AddAllArgs(CmdArgs, options::OPT_client__name);
  5904. Arg *A;
  5905. if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
  5906. (A = Args.getLastArg(options::OPT_current__version)) ||
  5907. (A = Args.getLastArg(options::OPT_install__name)))
  5908. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  5909. << "-dynamiclib";
  5910. Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
  5911. Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
  5912. Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
  5913. } else {
  5914. CmdArgs.push_back("-dylib");
  5915. Arg *A;
  5916. if ((A = Args.getLastArg(options::OPT_bundle)) ||
  5917. (A = Args.getLastArg(options::OPT_bundle__loader)) ||
  5918. (A = Args.getLastArg(options::OPT_client__name)) ||
  5919. (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
  5920. (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
  5921. (A = Args.getLastArg(options::OPT_private__bundle)))
  5922. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  5923. << "-dynamiclib";
  5924. Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
  5925. "-dylib_compatibility_version");
  5926. Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
  5927. "-dylib_current_version");
  5928. AddMachOArch(Args, CmdArgs);
  5929. Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
  5930. "-dylib_install_name");
  5931. }
  5932. Args.AddLastArg(CmdArgs, options::OPT_all__load);
  5933. Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
  5934. Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
  5935. if (MachOTC.isTargetIOSBased())
  5936. Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
  5937. Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
  5938. Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
  5939. Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
  5940. Args.AddLastArg(CmdArgs, options::OPT_dynamic);
  5941. Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
  5942. Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
  5943. Args.AddAllArgs(CmdArgs, options::OPT_force__load);
  5944. Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
  5945. Args.AddAllArgs(CmdArgs, options::OPT_image__base);
  5946. Args.AddAllArgs(CmdArgs, options::OPT_init);
  5947. // Add the deployment target.
  5948. MachOTC.addMinVersionArgs(Args, CmdArgs);
  5949. Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
  5950. Args.AddLastArg(CmdArgs, options::OPT_multi__module);
  5951. Args.AddLastArg(CmdArgs, options::OPT_single__module);
  5952. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
  5953. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
  5954. if (const Arg *A =
  5955. Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
  5956. options::OPT_fno_pie, options::OPT_fno_PIE)) {
  5957. if (A->getOption().matches(options::OPT_fpie) ||
  5958. A->getOption().matches(options::OPT_fPIE))
  5959. CmdArgs.push_back("-pie");
  5960. else
  5961. CmdArgs.push_back("-no_pie");
  5962. }
  5963. Args.AddLastArg(CmdArgs, options::OPT_prebind);
  5964. Args.AddLastArg(CmdArgs, options::OPT_noprebind);
  5965. Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
  5966. Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
  5967. Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
  5968. Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
  5969. Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
  5970. Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
  5971. Args.AddAllArgs(CmdArgs, options::OPT_segprot);
  5972. Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
  5973. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
  5974. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
  5975. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
  5976. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
  5977. Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
  5978. Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
  5979. // Give --sysroot= preference, over the Apple specific behavior to also use
  5980. // --isysroot as the syslibroot.
  5981. StringRef sysroot = C.getSysRoot();
  5982. if (sysroot != "") {
  5983. CmdArgs.push_back("-syslibroot");
  5984. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  5985. } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  5986. CmdArgs.push_back("-syslibroot");
  5987. CmdArgs.push_back(A->getValue());
  5988. }
  5989. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
  5990. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
  5991. Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
  5992. Args.AddAllArgs(CmdArgs, options::OPT_undefined);
  5993. Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
  5994. Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
  5995. Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
  5996. Args.AddAllArgs(CmdArgs, options::OPT_y);
  5997. Args.AddLastArg(CmdArgs, options::OPT_w);
  5998. Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
  5999. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
  6000. Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
  6001. Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
  6002. Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
  6003. Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
  6004. Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
  6005. Args.AddLastArg(CmdArgs, options::OPT_whyload);
  6006. Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
  6007. Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
  6008. Args.AddLastArg(CmdArgs, options::OPT_dylinker);
  6009. Args.AddLastArg(CmdArgs, options::OPT_Mach);
  6010. }
  6011. void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6012. const InputInfo &Output,
  6013. const InputInfoList &Inputs,
  6014. const ArgList &Args,
  6015. const char *LinkingOutput) const {
  6016. assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
  6017. // If the number of arguments surpasses the system limits, we will encode the
  6018. // input files in a separate file, shortening the command line. To this end,
  6019. // build a list of input file names that can be passed via a file with the
  6020. // -filelist linker option.
  6021. llvm::opt::ArgStringList InputFileList;
  6022. // The logic here is derived from gcc's behavior; most of which
  6023. // comes from specs (starting with link_command). Consult gcc for
  6024. // more information.
  6025. ArgStringList CmdArgs;
  6026. /// Hack(tm) to ignore linking errors when we are doing ARC migration.
  6027. if (Args.hasArg(options::OPT_ccc_arcmt_check,
  6028. options::OPT_ccc_arcmt_migrate)) {
  6029. for (const auto &Arg : Args)
  6030. Arg->claim();
  6031. const char *Exec =
  6032. Args.MakeArgString(getToolChain().GetProgramPath("touch"));
  6033. CmdArgs.push_back(Output.getFilename());
  6034. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
  6035. return;
  6036. }
  6037. // I'm not sure why this particular decomposition exists in gcc, but
  6038. // we follow suite for ease of comparison.
  6039. AddLinkArgs(C, Args, CmdArgs, Inputs);
  6040. // It seems that the 'e' option is completely ignored for dynamic executables
  6041. // (the default), and with static executables, the last one wins, as expected.
  6042. Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
  6043. options::OPT_Z_Flag, options::OPT_u_Group,
  6044. options::OPT_e, options::OPT_r});
  6045. // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
  6046. // members of static archive libraries which implement Objective-C classes or
  6047. // categories.
  6048. if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
  6049. CmdArgs.push_back("-ObjC");
  6050. CmdArgs.push_back("-o");
  6051. CmdArgs.push_back(Output.getFilename());
  6052. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6053. getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
  6054. // SafeStack requires its own runtime libraries
  6055. // These libraries should be linked first, to make sure the
  6056. // __safestack_init constructor executes before everything else
  6057. if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
  6058. getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
  6059. "libclang_rt.safestack_osx.a",
  6060. /*AlwaysLink=*/true);
  6061. }
  6062. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6063. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6064. // Build the input file for -filelist (list of linker input files) in case we
  6065. // need it later
  6066. for (const auto &II : Inputs) {
  6067. if (!II.isFilename()) {
  6068. // This is a linker input argument.
  6069. // We cannot mix input arguments and file names in a -filelist input, thus
  6070. // we prematurely stop our list (remaining files shall be passed as
  6071. // arguments).
  6072. if (InputFileList.size() > 0)
  6073. break;
  6074. continue;
  6075. }
  6076. InputFileList.push_back(II.getFilename());
  6077. }
  6078. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
  6079. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  6080. if (isObjCRuntimeLinked(Args) &&
  6081. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6082. // We use arclite library for both ARC and subscripting support.
  6083. getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
  6084. CmdArgs.push_back("-framework");
  6085. CmdArgs.push_back("Foundation");
  6086. // Link libobj.
  6087. CmdArgs.push_back("-lobjc");
  6088. }
  6089. if (LinkingOutput) {
  6090. CmdArgs.push_back("-arch_multiple");
  6091. CmdArgs.push_back("-final_output");
  6092. CmdArgs.push_back(LinkingOutput);
  6093. }
  6094. if (Args.hasArg(options::OPT_fnested_functions))
  6095. CmdArgs.push_back("-allow_stack_execute");
  6096. getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
  6097. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6098. if (getToolChain().getDriver().CCCIsCXX())
  6099. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6100. // link_ssp spec is empty.
  6101. // Let the tool chain choose which runtime library to link.
  6102. getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
  6103. }
  6104. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6105. // endfile_spec is empty.
  6106. }
  6107. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  6108. Args.AddAllArgs(CmdArgs, options::OPT_F);
  6109. // -iframework should be forwarded as -F.
  6110. for (const Arg *A : Args.filtered(options::OPT_iframework))
  6111. CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
  6112. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6113. if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
  6114. if (A->getValue() == StringRef("Accelerate")) {
  6115. CmdArgs.push_back("-framework");
  6116. CmdArgs.push_back("Accelerate");
  6117. }
  6118. }
  6119. }
  6120. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6121. std::unique_ptr<Command> Cmd =
  6122. llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
  6123. Cmd->setInputFileList(std::move(InputFileList));
  6124. C.addCommand(std::move(Cmd));
  6125. }
  6126. void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
  6127. const InputInfo &Output,
  6128. const InputInfoList &Inputs,
  6129. const ArgList &Args,
  6130. const char *LinkingOutput) const {
  6131. ArgStringList CmdArgs;
  6132. CmdArgs.push_back("-create");
  6133. assert(Output.isFilename() && "Unexpected lipo output.");
  6134. CmdArgs.push_back("-output");
  6135. CmdArgs.push_back(Output.getFilename());
  6136. for (const auto &II : Inputs) {
  6137. assert(II.isFilename() && "Unexpected lipo input.");
  6138. CmdArgs.push_back(II.getFilename());
  6139. }
  6140. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
  6141. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6142. }
  6143. void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
  6144. const InputInfo &Output,
  6145. const InputInfoList &Inputs,
  6146. const ArgList &Args,
  6147. const char *LinkingOutput) const {
  6148. ArgStringList CmdArgs;
  6149. CmdArgs.push_back("-o");
  6150. CmdArgs.push_back(Output.getFilename());
  6151. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6152. const InputInfo &Input = Inputs[0];
  6153. assert(Input.isFilename() && "Unexpected dsymutil input.");
  6154. CmdArgs.push_back(Input.getFilename());
  6155. const char *Exec =
  6156. Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
  6157. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6158. }
  6159. void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
  6160. const InputInfo &Output,
  6161. const InputInfoList &Inputs,
  6162. const ArgList &Args,
  6163. const char *LinkingOutput) const {
  6164. ArgStringList CmdArgs;
  6165. CmdArgs.push_back("--verify");
  6166. CmdArgs.push_back("--debug-info");
  6167. CmdArgs.push_back("--eh-frame");
  6168. CmdArgs.push_back("--quiet");
  6169. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6170. const InputInfo &Input = Inputs[0];
  6171. assert(Input.isFilename() && "Unexpected verify input");
  6172. // Grabbing the output of the earlier dsymutil run.
  6173. CmdArgs.push_back(Input.getFilename());
  6174. const char *Exec =
  6175. Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
  6176. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6177. }
  6178. void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6179. const InputInfo &Output,
  6180. const InputInfoList &Inputs,
  6181. const ArgList &Args,
  6182. const char *LinkingOutput) const {
  6183. claimNoWarnArgs(Args);
  6184. ArgStringList CmdArgs;
  6185. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6186. CmdArgs.push_back("-o");
  6187. CmdArgs.push_back(Output.getFilename());
  6188. for (const auto &II : Inputs)
  6189. CmdArgs.push_back(II.getFilename());
  6190. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6191. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6192. }
  6193. void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6194. const InputInfo &Output,
  6195. const InputInfoList &Inputs,
  6196. const ArgList &Args,
  6197. const char *LinkingOutput) const {
  6198. ArgStringList CmdArgs;
  6199. // Demangle C++ names in errors
  6200. CmdArgs.push_back("-C");
  6201. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6202. CmdArgs.push_back("-e");
  6203. CmdArgs.push_back("_start");
  6204. }
  6205. if (Args.hasArg(options::OPT_static)) {
  6206. CmdArgs.push_back("-Bstatic");
  6207. CmdArgs.push_back("-dn");
  6208. } else {
  6209. CmdArgs.push_back("-Bdynamic");
  6210. if (Args.hasArg(options::OPT_shared)) {
  6211. CmdArgs.push_back("-shared");
  6212. } else {
  6213. CmdArgs.push_back("--dynamic-linker");
  6214. CmdArgs.push_back(
  6215. Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
  6216. }
  6217. }
  6218. if (Output.isFilename()) {
  6219. CmdArgs.push_back("-o");
  6220. CmdArgs.push_back(Output.getFilename());
  6221. } else {
  6222. assert(Output.isNothing() && "Invalid output.");
  6223. }
  6224. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6225. if (!Args.hasArg(options::OPT_shared))
  6226. CmdArgs.push_back(
  6227. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  6228. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  6229. CmdArgs.push_back(
  6230. Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
  6231. CmdArgs.push_back(
  6232. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6233. }
  6234. getToolChain().AddFilePathLibArgs(Args, CmdArgs);
  6235. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  6236. options::OPT_e, options::OPT_r});
  6237. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6238. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6239. if (getToolChain().getDriver().CCCIsCXX())
  6240. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6241. CmdArgs.push_back("-lgcc_s");
  6242. CmdArgs.push_back("-lc");
  6243. if (!Args.hasArg(options::OPT_shared)) {
  6244. CmdArgs.push_back("-lgcc");
  6245. CmdArgs.push_back("-lm");
  6246. }
  6247. }
  6248. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6249. CmdArgs.push_back(
  6250. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6251. }
  6252. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  6253. getToolChain().addProfileRTLibs(Args, CmdArgs);
  6254. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6255. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6256. }
  6257. void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6258. const InputInfo &Output,
  6259. const InputInfoList &Inputs,
  6260. const ArgList &Args,
  6261. const char *LinkingOutput) const {
  6262. claimNoWarnArgs(Args);
  6263. ArgStringList CmdArgs;
  6264. switch (getToolChain().getArch()) {
  6265. case llvm::Triple::x86:
  6266. // When building 32-bit code on OpenBSD/amd64, we have to explicitly
  6267. // instruct as in the base system to assemble 32-bit code.
  6268. CmdArgs.push_back("--32");
  6269. break;
  6270. case llvm::Triple::ppc:
  6271. CmdArgs.push_back("-mppc");
  6272. CmdArgs.push_back("-many");
  6273. break;
  6274. case llvm::Triple::sparc:
  6275. case llvm::Triple::sparcel: {
  6276. CmdArgs.push_back("-32");
  6277. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6278. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6279. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6280. break;
  6281. }
  6282. case llvm::Triple::sparcv9: {
  6283. CmdArgs.push_back("-64");
  6284. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6285. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6286. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6287. break;
  6288. }
  6289. case llvm::Triple::mips64:
  6290. case llvm::Triple::mips64el: {
  6291. StringRef CPUName;
  6292. StringRef ABIName;
  6293. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6294. CmdArgs.push_back("-mabi");
  6295. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6296. if (getToolChain().getArch() == llvm::Triple::mips64)
  6297. CmdArgs.push_back("-EB");
  6298. else
  6299. CmdArgs.push_back("-EL");
  6300. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6301. break;
  6302. }
  6303. default:
  6304. break;
  6305. }
  6306. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6307. CmdArgs.push_back("-o");
  6308. CmdArgs.push_back(Output.getFilename());
  6309. for (const auto &II : Inputs)
  6310. CmdArgs.push_back(II.getFilename());
  6311. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6312. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6313. }
  6314. void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6315. const InputInfo &Output,
  6316. const InputInfoList &Inputs,
  6317. const ArgList &Args,
  6318. const char *LinkingOutput) const {
  6319. const Driver &D = getToolChain().getDriver();
  6320. ArgStringList CmdArgs;
  6321. // Silence warning for "clang -g foo.o -o foo"
  6322. Args.ClaimAllArgs(options::OPT_g_Group);
  6323. // and "clang -emit-llvm foo.o -o foo"
  6324. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6325. // and for "clang -w foo.o -o foo". Other warning options are already
  6326. // handled somewhere else.
  6327. Args.ClaimAllArgs(options::OPT_w);
  6328. if (getToolChain().getArch() == llvm::Triple::mips64)
  6329. CmdArgs.push_back("-EB");
  6330. else if (getToolChain().getArch() == llvm::Triple::mips64el)
  6331. CmdArgs.push_back("-EL");
  6332. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6333. CmdArgs.push_back("-e");
  6334. CmdArgs.push_back("__start");
  6335. }
  6336. if (Args.hasArg(options::OPT_static)) {
  6337. CmdArgs.push_back("-Bstatic");
  6338. } else {
  6339. if (Args.hasArg(options::OPT_rdynamic))
  6340. CmdArgs.push_back("-export-dynamic");
  6341. CmdArgs.push_back("--eh-frame-hdr");
  6342. CmdArgs.push_back("-Bdynamic");
  6343. if (Args.hasArg(options::OPT_shared)) {
  6344. CmdArgs.push_back("-shared");
  6345. } else {
  6346. CmdArgs.push_back("-dynamic-linker");
  6347. CmdArgs.push_back("/usr/libexec/ld.so");
  6348. }
  6349. }
  6350. if (Args.hasArg(options::OPT_nopie))
  6351. CmdArgs.push_back("-nopie");
  6352. if (Output.isFilename()) {
  6353. CmdArgs.push_back("-o");
  6354. CmdArgs.push_back(Output.getFilename());
  6355. } else {
  6356. assert(Output.isNothing() && "Invalid output.");
  6357. }
  6358. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6359. if (!Args.hasArg(options::OPT_shared)) {
  6360. if (Args.hasArg(options::OPT_pg))
  6361. CmdArgs.push_back(
  6362. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  6363. else
  6364. CmdArgs.push_back(
  6365. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  6366. CmdArgs.push_back(
  6367. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6368. } else {
  6369. CmdArgs.push_back(
  6370. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  6371. }
  6372. }
  6373. std::string Triple = getToolChain().getTripleString();
  6374. if (Triple.substr(0, 6) == "x86_64")
  6375. Triple.replace(0, 6, "amd64");
  6376. CmdArgs.push_back(
  6377. Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
  6378. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  6379. options::OPT_e, options::OPT_s, options::OPT_t,
  6380. options::OPT_Z_Flag, options::OPT_r});
  6381. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6382. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6383. if (D.CCCIsCXX()) {
  6384. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6385. if (Args.hasArg(options::OPT_pg))
  6386. CmdArgs.push_back("-lm_p");
  6387. else
  6388. CmdArgs.push_back("-lm");
  6389. }
  6390. // FIXME: For some reason GCC passes -lgcc before adding
  6391. // the default system libraries. Just mimic this for now.
  6392. CmdArgs.push_back("-lgcc");
  6393. if (Args.hasArg(options::OPT_pthread)) {
  6394. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  6395. CmdArgs.push_back("-lpthread_p");
  6396. else
  6397. CmdArgs.push_back("-lpthread");
  6398. }
  6399. if (!Args.hasArg(options::OPT_shared)) {
  6400. if (Args.hasArg(options::OPT_pg))
  6401. CmdArgs.push_back("-lc_p");
  6402. else
  6403. CmdArgs.push_back("-lc");
  6404. }
  6405. CmdArgs.push_back("-lgcc");
  6406. }
  6407. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6408. if (!Args.hasArg(options::OPT_shared))
  6409. CmdArgs.push_back(
  6410. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6411. else
  6412. CmdArgs.push_back(
  6413. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  6414. }
  6415. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6416. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6417. }
  6418. void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6419. const InputInfo &Output,
  6420. const InputInfoList &Inputs,
  6421. const ArgList &Args,
  6422. const char *LinkingOutput) const {
  6423. claimNoWarnArgs(Args);
  6424. ArgStringList CmdArgs;
  6425. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6426. CmdArgs.push_back("-o");
  6427. CmdArgs.push_back(Output.getFilename());
  6428. for (const auto &II : Inputs)
  6429. CmdArgs.push_back(II.getFilename());
  6430. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6431. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6432. }
  6433. void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6434. const InputInfo &Output,
  6435. const InputInfoList &Inputs,
  6436. const ArgList &Args,
  6437. const char *LinkingOutput) const {
  6438. const Driver &D = getToolChain().getDriver();
  6439. ArgStringList CmdArgs;
  6440. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6441. CmdArgs.push_back("-e");
  6442. CmdArgs.push_back("__start");
  6443. }
  6444. if (Args.hasArg(options::OPT_static)) {
  6445. CmdArgs.push_back("-Bstatic");
  6446. } else {
  6447. if (Args.hasArg(options::OPT_rdynamic))
  6448. CmdArgs.push_back("-export-dynamic");
  6449. CmdArgs.push_back("--eh-frame-hdr");
  6450. CmdArgs.push_back("-Bdynamic");
  6451. if (Args.hasArg(options::OPT_shared)) {
  6452. CmdArgs.push_back("-shared");
  6453. } else {
  6454. CmdArgs.push_back("-dynamic-linker");
  6455. CmdArgs.push_back("/usr/libexec/ld.so");
  6456. }
  6457. }
  6458. if (Output.isFilename()) {
  6459. CmdArgs.push_back("-o");
  6460. CmdArgs.push_back(Output.getFilename());
  6461. } else {
  6462. assert(Output.isNothing() && "Invalid output.");
  6463. }
  6464. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6465. if (!Args.hasArg(options::OPT_shared)) {
  6466. if (Args.hasArg(options::OPT_pg))
  6467. CmdArgs.push_back(
  6468. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  6469. else
  6470. CmdArgs.push_back(
  6471. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  6472. CmdArgs.push_back(
  6473. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6474. } else {
  6475. CmdArgs.push_back(
  6476. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  6477. }
  6478. }
  6479. Args.AddAllArgs(CmdArgs,
  6480. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  6481. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6482. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6483. if (D.CCCIsCXX()) {
  6484. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6485. if (Args.hasArg(options::OPT_pg))
  6486. CmdArgs.push_back("-lm_p");
  6487. else
  6488. CmdArgs.push_back("-lm");
  6489. }
  6490. if (Args.hasArg(options::OPT_pthread)) {
  6491. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  6492. CmdArgs.push_back("-lpthread_p");
  6493. else
  6494. CmdArgs.push_back("-lpthread");
  6495. }
  6496. if (!Args.hasArg(options::OPT_shared)) {
  6497. if (Args.hasArg(options::OPT_pg))
  6498. CmdArgs.push_back("-lc_p");
  6499. else
  6500. CmdArgs.push_back("-lc");
  6501. }
  6502. StringRef MyArch;
  6503. switch (getToolChain().getArch()) {
  6504. case llvm::Triple::arm:
  6505. MyArch = "arm";
  6506. break;
  6507. case llvm::Triple::x86:
  6508. MyArch = "i386";
  6509. break;
  6510. case llvm::Triple::x86_64:
  6511. MyArch = "amd64";
  6512. break;
  6513. default:
  6514. llvm_unreachable("Unsupported architecture");
  6515. }
  6516. CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
  6517. }
  6518. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6519. if (!Args.hasArg(options::OPT_shared))
  6520. CmdArgs.push_back(
  6521. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6522. else
  6523. CmdArgs.push_back(
  6524. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  6525. }
  6526. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6527. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6528. }
  6529. void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6530. const InputInfo &Output,
  6531. const InputInfoList &Inputs,
  6532. const ArgList &Args,
  6533. const char *LinkingOutput) const {
  6534. claimNoWarnArgs(Args);
  6535. ArgStringList CmdArgs;
  6536. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  6537. // instruct as in the base system to assemble 32-bit code.
  6538. switch (getToolChain().getArch()) {
  6539. default:
  6540. break;
  6541. case llvm::Triple::x86:
  6542. CmdArgs.push_back("--32");
  6543. break;
  6544. case llvm::Triple::ppc:
  6545. CmdArgs.push_back("-a32");
  6546. break;
  6547. case llvm::Triple::mips:
  6548. case llvm::Triple::mipsel:
  6549. case llvm::Triple::mips64:
  6550. case llvm::Triple::mips64el: {
  6551. StringRef CPUName;
  6552. StringRef ABIName;
  6553. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6554. CmdArgs.push_back("-march");
  6555. CmdArgs.push_back(CPUName.data());
  6556. CmdArgs.push_back("-mabi");
  6557. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6558. if (getToolChain().getArch() == llvm::Triple::mips ||
  6559. getToolChain().getArch() == llvm::Triple::mips64)
  6560. CmdArgs.push_back("-EB");
  6561. else
  6562. CmdArgs.push_back("-EL");
  6563. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6564. break;
  6565. }
  6566. case llvm::Triple::arm:
  6567. case llvm::Triple::armeb:
  6568. case llvm::Triple::thumb:
  6569. case llvm::Triple::thumbeb: {
  6570. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  6571. if (ABI == arm::FloatABI::Hard)
  6572. CmdArgs.push_back("-mfpu=vfp");
  6573. else
  6574. CmdArgs.push_back("-mfpu=softvfp");
  6575. switch (getToolChain().getTriple().getEnvironment()) {
  6576. case llvm::Triple::GNUEABIHF:
  6577. case llvm::Triple::GNUEABI:
  6578. case llvm::Triple::EABI:
  6579. CmdArgs.push_back("-meabi=5");
  6580. break;
  6581. default:
  6582. CmdArgs.push_back("-matpcs");
  6583. }
  6584. break;
  6585. }
  6586. case llvm::Triple::sparc:
  6587. case llvm::Triple::sparcel:
  6588. case llvm::Triple::sparcv9: {
  6589. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6590. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6591. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6592. break;
  6593. }
  6594. }
  6595. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6596. CmdArgs.push_back("-o");
  6597. CmdArgs.push_back(Output.getFilename());
  6598. for (const auto &II : Inputs)
  6599. CmdArgs.push_back(II.getFilename());
  6600. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6601. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6602. }
  6603. void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6604. const InputInfo &Output,
  6605. const InputInfoList &Inputs,
  6606. const ArgList &Args,
  6607. const char *LinkingOutput) const {
  6608. const toolchains::FreeBSD &ToolChain =
  6609. static_cast<const toolchains::FreeBSD &>(getToolChain());
  6610. const Driver &D = ToolChain.getDriver();
  6611. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  6612. const bool IsPIE =
  6613. !Args.hasArg(options::OPT_shared) &&
  6614. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  6615. ArgStringList CmdArgs;
  6616. // Silence warning for "clang -g foo.o -o foo"
  6617. Args.ClaimAllArgs(options::OPT_g_Group);
  6618. // and "clang -emit-llvm foo.o -o foo"
  6619. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6620. // and for "clang -w foo.o -o foo". Other warning options are already
  6621. // handled somewhere else.
  6622. Args.ClaimAllArgs(options::OPT_w);
  6623. if (!D.SysRoot.empty())
  6624. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  6625. if (IsPIE)
  6626. CmdArgs.push_back("-pie");
  6627. if (Args.hasArg(options::OPT_static)) {
  6628. CmdArgs.push_back("-Bstatic");
  6629. } else {
  6630. if (Args.hasArg(options::OPT_rdynamic))
  6631. CmdArgs.push_back("-export-dynamic");
  6632. CmdArgs.push_back("--eh-frame-hdr");
  6633. if (Args.hasArg(options::OPT_shared)) {
  6634. CmdArgs.push_back("-Bshareable");
  6635. } else {
  6636. CmdArgs.push_back("-dynamic-linker");
  6637. CmdArgs.push_back("/libexec/ld-elf.so.1");
  6638. }
  6639. if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
  6640. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
  6641. Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
  6642. CmdArgs.push_back("--hash-style=both");
  6643. }
  6644. }
  6645. CmdArgs.push_back("--enable-new-dtags");
  6646. }
  6647. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  6648. // instruct ld in the base system to link 32-bit code.
  6649. if (Arch == llvm::Triple::x86) {
  6650. CmdArgs.push_back("-m");
  6651. CmdArgs.push_back("elf_i386_fbsd");
  6652. }
  6653. if (Arch == llvm::Triple::ppc) {
  6654. CmdArgs.push_back("-m");
  6655. CmdArgs.push_back("elf32ppc_fbsd");
  6656. }
  6657. if (Output.isFilename()) {
  6658. CmdArgs.push_back("-o");
  6659. CmdArgs.push_back(Output.getFilename());
  6660. } else {
  6661. assert(Output.isNothing() && "Invalid output.");
  6662. }
  6663. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6664. const char *crt1 = nullptr;
  6665. if (!Args.hasArg(options::OPT_shared)) {
  6666. if (Args.hasArg(options::OPT_pg))
  6667. crt1 = "gcrt1.o";
  6668. else if (IsPIE)
  6669. crt1 = "Scrt1.o";
  6670. else
  6671. crt1 = "crt1.o";
  6672. }
  6673. if (crt1)
  6674. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  6675. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  6676. const char *crtbegin = nullptr;
  6677. if (Args.hasArg(options::OPT_static))
  6678. crtbegin = "crtbeginT.o";
  6679. else if (Args.hasArg(options::OPT_shared) || IsPIE)
  6680. crtbegin = "crtbeginS.o";
  6681. else
  6682. crtbegin = "crtbegin.o";
  6683. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  6684. }
  6685. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6686. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  6687. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  6688. Args.AddAllArgs(CmdArgs, options::OPT_e);
  6689. Args.AddAllArgs(CmdArgs, options::OPT_s);
  6690. Args.AddAllArgs(CmdArgs, options::OPT_t);
  6691. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  6692. Args.AddAllArgs(CmdArgs, options::OPT_r);
  6693. if (D.isUsingLTO())
  6694. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  6695. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  6696. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  6697. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6698. addOpenMPRuntime(CmdArgs, ToolChain, Args);
  6699. if (D.CCCIsCXX()) {
  6700. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  6701. if (Args.hasArg(options::OPT_pg))
  6702. CmdArgs.push_back("-lm_p");
  6703. else
  6704. CmdArgs.push_back("-lm");
  6705. }
  6706. if (NeedsSanitizerDeps)
  6707. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  6708. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  6709. // the default system libraries. Just mimic this for now.
  6710. if (Args.hasArg(options::OPT_pg))
  6711. CmdArgs.push_back("-lgcc_p");
  6712. else
  6713. CmdArgs.push_back("-lgcc");
  6714. if (Args.hasArg(options::OPT_static)) {
  6715. CmdArgs.push_back("-lgcc_eh");
  6716. } else if (Args.hasArg(options::OPT_pg)) {
  6717. CmdArgs.push_back("-lgcc_eh_p");
  6718. } else {
  6719. CmdArgs.push_back("--as-needed");
  6720. CmdArgs.push_back("-lgcc_s");
  6721. CmdArgs.push_back("--no-as-needed");
  6722. }
  6723. if (Args.hasArg(options::OPT_pthread)) {
  6724. if (Args.hasArg(options::OPT_pg))
  6725. CmdArgs.push_back("-lpthread_p");
  6726. else
  6727. CmdArgs.push_back("-lpthread");
  6728. }
  6729. if (Args.hasArg(options::OPT_pg)) {
  6730. if (Args.hasArg(options::OPT_shared))
  6731. CmdArgs.push_back("-lc");
  6732. else
  6733. CmdArgs.push_back("-lc_p");
  6734. CmdArgs.push_back("-lgcc_p");
  6735. } else {
  6736. CmdArgs.push_back("-lc");
  6737. CmdArgs.push_back("-lgcc");
  6738. }
  6739. if (Args.hasArg(options::OPT_static)) {
  6740. CmdArgs.push_back("-lgcc_eh");
  6741. } else if (Args.hasArg(options::OPT_pg)) {
  6742. CmdArgs.push_back("-lgcc_eh_p");
  6743. } else {
  6744. CmdArgs.push_back("--as-needed");
  6745. CmdArgs.push_back("-lgcc_s");
  6746. CmdArgs.push_back("--no-as-needed");
  6747. }
  6748. }
  6749. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6750. if (Args.hasArg(options::OPT_shared) || IsPIE)
  6751. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  6752. else
  6753. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  6754. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  6755. }
  6756. ToolChain.addProfileRTLibs(Args, CmdArgs);
  6757. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6758. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6759. }
  6760. void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6761. const InputInfo &Output,
  6762. const InputInfoList &Inputs,
  6763. const ArgList &Args,
  6764. const char *LinkingOutput) const {
  6765. claimNoWarnArgs(Args);
  6766. ArgStringList CmdArgs;
  6767. // GNU as needs different flags for creating the correct output format
  6768. // on architectures with different ABIs or optional feature sets.
  6769. switch (getToolChain().getArch()) {
  6770. case llvm::Triple::x86:
  6771. CmdArgs.push_back("--32");
  6772. break;
  6773. case llvm::Triple::arm:
  6774. case llvm::Triple::armeb:
  6775. case llvm::Triple::thumb:
  6776. case llvm::Triple::thumbeb: {
  6777. StringRef MArch, MCPU;
  6778. getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
  6779. std::string Arch =
  6780. arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
  6781. CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
  6782. break;
  6783. }
  6784. case llvm::Triple::mips:
  6785. case llvm::Triple::mipsel:
  6786. case llvm::Triple::mips64:
  6787. case llvm::Triple::mips64el: {
  6788. StringRef CPUName;
  6789. StringRef ABIName;
  6790. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6791. CmdArgs.push_back("-march");
  6792. CmdArgs.push_back(CPUName.data());
  6793. CmdArgs.push_back("-mabi");
  6794. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6795. if (getToolChain().getArch() == llvm::Triple::mips ||
  6796. getToolChain().getArch() == llvm::Triple::mips64)
  6797. CmdArgs.push_back("-EB");
  6798. else
  6799. CmdArgs.push_back("-EL");
  6800. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6801. break;
  6802. }
  6803. case llvm::Triple::sparc:
  6804. case llvm::Triple::sparcel: {
  6805. CmdArgs.push_back("-32");
  6806. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6807. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6808. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6809. break;
  6810. }
  6811. case llvm::Triple::sparcv9: {
  6812. CmdArgs.push_back("-64");
  6813. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6814. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6815. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6816. break;
  6817. }
  6818. default:
  6819. break;
  6820. }
  6821. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6822. CmdArgs.push_back("-o");
  6823. CmdArgs.push_back(Output.getFilename());
  6824. for (const auto &II : Inputs)
  6825. CmdArgs.push_back(II.getFilename());
  6826. const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
  6827. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6828. }
  6829. void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6830. const InputInfo &Output,
  6831. const InputInfoList &Inputs,
  6832. const ArgList &Args,
  6833. const char *LinkingOutput) const {
  6834. const Driver &D = getToolChain().getDriver();
  6835. ArgStringList CmdArgs;
  6836. if (!D.SysRoot.empty())
  6837. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  6838. CmdArgs.push_back("--eh-frame-hdr");
  6839. if (Args.hasArg(options::OPT_static)) {
  6840. CmdArgs.push_back("-Bstatic");
  6841. } else {
  6842. if (Args.hasArg(options::OPT_rdynamic))
  6843. CmdArgs.push_back("-export-dynamic");
  6844. if (Args.hasArg(options::OPT_shared)) {
  6845. CmdArgs.push_back("-Bshareable");
  6846. } else {
  6847. CmdArgs.push_back("-dynamic-linker");
  6848. CmdArgs.push_back("/libexec/ld.elf_so");
  6849. }
  6850. }
  6851. // Many NetBSD architectures support more than one ABI.
  6852. // Determine the correct emulation for ld.
  6853. switch (getToolChain().getArch()) {
  6854. case llvm::Triple::x86:
  6855. CmdArgs.push_back("-m");
  6856. CmdArgs.push_back("elf_i386");
  6857. break;
  6858. case llvm::Triple::arm:
  6859. case llvm::Triple::thumb:
  6860. CmdArgs.push_back("-m");
  6861. switch (getToolChain().getTriple().getEnvironment()) {
  6862. case llvm::Triple::EABI:
  6863. case llvm::Triple::GNUEABI:
  6864. CmdArgs.push_back("armelf_nbsd_eabi");
  6865. break;
  6866. case llvm::Triple::EABIHF:
  6867. case llvm::Triple::GNUEABIHF:
  6868. CmdArgs.push_back("armelf_nbsd_eabihf");
  6869. break;
  6870. default:
  6871. CmdArgs.push_back("armelf_nbsd");
  6872. break;
  6873. }
  6874. break;
  6875. case llvm::Triple::armeb:
  6876. case llvm::Triple::thumbeb:
  6877. arm::appendEBLinkFlags(
  6878. Args, CmdArgs,
  6879. llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
  6880. CmdArgs.push_back("-m");
  6881. switch (getToolChain().getTriple().getEnvironment()) {
  6882. case llvm::Triple::EABI:
  6883. case llvm::Triple::GNUEABI:
  6884. CmdArgs.push_back("armelfb_nbsd_eabi");
  6885. break;
  6886. case llvm::Triple::EABIHF:
  6887. case llvm::Triple::GNUEABIHF:
  6888. CmdArgs.push_back("armelfb_nbsd_eabihf");
  6889. break;
  6890. default:
  6891. CmdArgs.push_back("armelfb_nbsd");
  6892. break;
  6893. }
  6894. break;
  6895. case llvm::Triple::mips64:
  6896. case llvm::Triple::mips64el:
  6897. if (mips::hasMipsAbiArg(Args, "32")) {
  6898. CmdArgs.push_back("-m");
  6899. if (getToolChain().getArch() == llvm::Triple::mips64)
  6900. CmdArgs.push_back("elf32btsmip");
  6901. else
  6902. CmdArgs.push_back("elf32ltsmip");
  6903. } else if (mips::hasMipsAbiArg(Args, "64")) {
  6904. CmdArgs.push_back("-m");
  6905. if (getToolChain().getArch() == llvm::Triple::mips64)
  6906. CmdArgs.push_back("elf64btsmip");
  6907. else
  6908. CmdArgs.push_back("elf64ltsmip");
  6909. }
  6910. break;
  6911. case llvm::Triple::ppc:
  6912. CmdArgs.push_back("-m");
  6913. CmdArgs.push_back("elf32ppc_nbsd");
  6914. break;
  6915. case llvm::Triple::ppc64:
  6916. case llvm::Triple::ppc64le:
  6917. CmdArgs.push_back("-m");
  6918. CmdArgs.push_back("elf64ppc");
  6919. break;
  6920. case llvm::Triple::sparc:
  6921. CmdArgs.push_back("-m");
  6922. CmdArgs.push_back("elf32_sparc");
  6923. break;
  6924. case llvm::Triple::sparcv9:
  6925. CmdArgs.push_back("-m");
  6926. CmdArgs.push_back("elf64_sparc");
  6927. break;
  6928. default:
  6929. break;
  6930. }
  6931. if (Output.isFilename()) {
  6932. CmdArgs.push_back("-o");
  6933. CmdArgs.push_back(Output.getFilename());
  6934. } else {
  6935. assert(Output.isNothing() && "Invalid output.");
  6936. }
  6937. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6938. if (!Args.hasArg(options::OPT_shared)) {
  6939. CmdArgs.push_back(
  6940. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  6941. CmdArgs.push_back(
  6942. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  6943. CmdArgs.push_back(
  6944. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6945. } else {
  6946. CmdArgs.push_back(
  6947. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  6948. CmdArgs.push_back(
  6949. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  6950. }
  6951. }
  6952. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6953. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  6954. Args.AddAllArgs(CmdArgs, options::OPT_e);
  6955. Args.AddAllArgs(CmdArgs, options::OPT_s);
  6956. Args.AddAllArgs(CmdArgs, options::OPT_t);
  6957. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  6958. Args.AddAllArgs(CmdArgs, options::OPT_r);
  6959. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6960. unsigned Major, Minor, Micro;
  6961. getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
  6962. bool useLibgcc = true;
  6963. if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
  6964. switch (getToolChain().getArch()) {
  6965. case llvm::Triple::aarch64:
  6966. case llvm::Triple::arm:
  6967. case llvm::Triple::armeb:
  6968. case llvm::Triple::thumb:
  6969. case llvm::Triple::thumbeb:
  6970. case llvm::Triple::ppc:
  6971. case llvm::Triple::ppc64:
  6972. case llvm::Triple::ppc64le:
  6973. case llvm::Triple::x86:
  6974. case llvm::Triple::x86_64:
  6975. useLibgcc = false;
  6976. break;
  6977. default:
  6978. break;
  6979. }
  6980. }
  6981. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6982. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  6983. if (D.CCCIsCXX()) {
  6984. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6985. CmdArgs.push_back("-lm");
  6986. }
  6987. if (Args.hasArg(options::OPT_pthread))
  6988. CmdArgs.push_back("-lpthread");
  6989. CmdArgs.push_back("-lc");
  6990. if (useLibgcc) {
  6991. if (Args.hasArg(options::OPT_static)) {
  6992. // libgcc_eh depends on libc, so resolve as much as possible,
  6993. // pull in any new requirements from libc and then get the rest
  6994. // of libgcc.
  6995. CmdArgs.push_back("-lgcc_eh");
  6996. CmdArgs.push_back("-lc");
  6997. CmdArgs.push_back("-lgcc");
  6998. } else {
  6999. CmdArgs.push_back("-lgcc");
  7000. CmdArgs.push_back("--as-needed");
  7001. CmdArgs.push_back("-lgcc_s");
  7002. CmdArgs.push_back("--no-as-needed");
  7003. }
  7004. }
  7005. }
  7006. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7007. if (!Args.hasArg(options::OPT_shared))
  7008. CmdArgs.push_back(
  7009. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7010. else
  7011. CmdArgs.push_back(
  7012. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7013. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  7014. }
  7015. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7016. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7017. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7018. }
  7019. void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7020. const InputInfo &Output,
  7021. const InputInfoList &Inputs,
  7022. const ArgList &Args,
  7023. const char *LinkingOutput) const {
  7024. claimNoWarnArgs(Args);
  7025. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  7026. llvm::Triple Triple = llvm::Triple(TripleStr);
  7027. ArgStringList CmdArgs;
  7028. llvm::Reloc::Model RelocationModel;
  7029. unsigned PICLevel;
  7030. bool IsPIE;
  7031. std::tie(RelocationModel, PICLevel, IsPIE) =
  7032. ParsePICArgs(getToolChain(), Triple, Args);
  7033. switch (getToolChain().getArch()) {
  7034. default:
  7035. break;
  7036. // Add --32/--64 to make sure we get the format we want.
  7037. // This is incomplete
  7038. case llvm::Triple::x86:
  7039. CmdArgs.push_back("--32");
  7040. break;
  7041. case llvm::Triple::x86_64:
  7042. if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
  7043. CmdArgs.push_back("--x32");
  7044. else
  7045. CmdArgs.push_back("--64");
  7046. break;
  7047. case llvm::Triple::ppc:
  7048. CmdArgs.push_back("-a32");
  7049. CmdArgs.push_back("-mppc");
  7050. CmdArgs.push_back("-many");
  7051. break;
  7052. case llvm::Triple::ppc64:
  7053. CmdArgs.push_back("-a64");
  7054. CmdArgs.push_back("-mppc64");
  7055. CmdArgs.push_back("-many");
  7056. break;
  7057. case llvm::Triple::ppc64le:
  7058. CmdArgs.push_back("-a64");
  7059. CmdArgs.push_back("-mppc64");
  7060. CmdArgs.push_back("-many");
  7061. CmdArgs.push_back("-mlittle-endian");
  7062. break;
  7063. case llvm::Triple::sparc:
  7064. case llvm::Triple::sparcel: {
  7065. CmdArgs.push_back("-32");
  7066. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7067. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7068. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7069. break;
  7070. }
  7071. case llvm::Triple::sparcv9: {
  7072. CmdArgs.push_back("-64");
  7073. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7074. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7075. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7076. break;
  7077. }
  7078. case llvm::Triple::arm:
  7079. case llvm::Triple::armeb:
  7080. case llvm::Triple::thumb:
  7081. case llvm::Triple::thumbeb: {
  7082. const llvm::Triple &Triple2 = getToolChain().getTriple();
  7083. switch (Triple2.getSubArch()) {
  7084. case llvm::Triple::ARMSubArch_v7:
  7085. CmdArgs.push_back("-mfpu=neon");
  7086. break;
  7087. case llvm::Triple::ARMSubArch_v8:
  7088. CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
  7089. break;
  7090. default:
  7091. break;
  7092. }
  7093. switch (arm::getARMFloatABI(getToolChain(), Args)) {
  7094. case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
  7095. case arm::FloatABI::Soft:
  7096. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
  7097. break;
  7098. case arm::FloatABI::SoftFP:
  7099. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
  7100. break;
  7101. case arm::FloatABI::Hard:
  7102. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
  7103. break;
  7104. }
  7105. Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
  7106. // FIXME: remove krait check when GNU tools support krait cpu
  7107. // for now replace it with -march=armv7-a to avoid a lower
  7108. // march from being picked in the absence of a cpu flag.
  7109. Arg *A;
  7110. if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
  7111. StringRef(A->getValue()).lower() == "krait")
  7112. CmdArgs.push_back("-march=armv7-a");
  7113. else
  7114. Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
  7115. Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
  7116. break;
  7117. }
  7118. case llvm::Triple::mips:
  7119. case llvm::Triple::mipsel:
  7120. case llvm::Triple::mips64:
  7121. case llvm::Triple::mips64el: {
  7122. StringRef CPUName;
  7123. StringRef ABIName;
  7124. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7125. ABIName = getGnuCompatibleMipsABIName(ABIName);
  7126. CmdArgs.push_back("-march");
  7127. CmdArgs.push_back(CPUName.data());
  7128. CmdArgs.push_back("-mabi");
  7129. CmdArgs.push_back(ABIName.data());
  7130. // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
  7131. // or -mshared (not implemented) is in effect.
  7132. if (RelocationModel == llvm::Reloc::Static)
  7133. CmdArgs.push_back("-mno-shared");
  7134. // LLVM doesn't support -mplt yet and acts as if it is always given.
  7135. // However, -mplt has no effect with the N64 ABI.
  7136. CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
  7137. if (getToolChain().getArch() == llvm::Triple::mips ||
  7138. getToolChain().getArch() == llvm::Triple::mips64)
  7139. CmdArgs.push_back("-EB");
  7140. else
  7141. CmdArgs.push_back("-EL");
  7142. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  7143. if (StringRef(A->getValue()) == "2008")
  7144. CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
  7145. }
  7146. // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
  7147. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  7148. options::OPT_mfp64)) {
  7149. A->claim();
  7150. A->render(Args, CmdArgs);
  7151. } else if (mips::shouldUseFPXX(
  7152. Args, getToolChain().getTriple(), CPUName, ABIName,
  7153. getMipsFloatABI(getToolChain().getDriver(), Args)))
  7154. CmdArgs.push_back("-mfpxx");
  7155. // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
  7156. // -mno-mips16 is actually -no-mips16.
  7157. if (Arg *A =
  7158. Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
  7159. if (A->getOption().matches(options::OPT_mips16)) {
  7160. A->claim();
  7161. A->render(Args, CmdArgs);
  7162. } else {
  7163. A->claim();
  7164. CmdArgs.push_back("-no-mips16");
  7165. }
  7166. }
  7167. Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
  7168. options::OPT_mno_micromips);
  7169. Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
  7170. Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
  7171. if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
  7172. // Do not use AddLastArg because not all versions of MIPS assembler
  7173. // support -mmsa / -mno-msa options.
  7174. if (A->getOption().matches(options::OPT_mmsa))
  7175. CmdArgs.push_back(Args.MakeArgString("-mmsa"));
  7176. }
  7177. Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
  7178. options::OPT_msoft_float);
  7179. Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
  7180. options::OPT_msingle_float);
  7181. Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
  7182. options::OPT_mno_odd_spreg);
  7183. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7184. break;
  7185. }
  7186. case llvm::Triple::systemz: {
  7187. // Always pass an -march option, since our default of z10 is later
  7188. // than the GNU assembler's default.
  7189. StringRef CPUName = getSystemZTargetCPU(Args);
  7190. CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
  7191. break;
  7192. }
  7193. }
  7194. Args.AddAllArgs(CmdArgs, options::OPT_I);
  7195. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7196. CmdArgs.push_back("-o");
  7197. CmdArgs.push_back(Output.getFilename());
  7198. for (const auto &II : Inputs)
  7199. CmdArgs.push_back(II.getFilename());
  7200. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7201. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7202. // Handle the debug info splitting at object creation time if we're
  7203. // creating an object.
  7204. // TODO: Currently only works on linux with newer objcopy.
  7205. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  7206. getToolChain().getTriple().isOSLinux())
  7207. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  7208. SplitDebugName(Args, Inputs[0]));
  7209. }
  7210. static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
  7211. ArgStringList &CmdArgs, const ArgList &Args) {
  7212. bool isAndroid = Triple.isAndroid();
  7213. bool isCygMing = Triple.isOSCygMing();
  7214. bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
  7215. Args.hasArg(options::OPT_static);
  7216. if (!D.CCCIsCXX())
  7217. CmdArgs.push_back("-lgcc");
  7218. if (StaticLibgcc || isAndroid) {
  7219. if (D.CCCIsCXX())
  7220. CmdArgs.push_back("-lgcc");
  7221. } else {
  7222. if (!D.CCCIsCXX() && !isCygMing)
  7223. CmdArgs.push_back("--as-needed");
  7224. CmdArgs.push_back("-lgcc_s");
  7225. if (!D.CCCIsCXX() && !isCygMing)
  7226. CmdArgs.push_back("--no-as-needed");
  7227. }
  7228. if (StaticLibgcc && !isAndroid)
  7229. CmdArgs.push_back("-lgcc_eh");
  7230. else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
  7231. CmdArgs.push_back("-lgcc");
  7232. // According to Android ABI, we have to link with libdl if we are
  7233. // linking with non-static libgcc.
  7234. //
  7235. // NOTE: This fixes a link error on Android MIPS as well. The non-static
  7236. // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
  7237. if (isAndroid && !StaticLibgcc)
  7238. CmdArgs.push_back("-ldl");
  7239. }
  7240. static std::string getLinuxDynamicLinker(const ArgList &Args,
  7241. const toolchains::Linux &ToolChain) {
  7242. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7243. if (ToolChain.getTriple().isAndroid()) {
  7244. if (ToolChain.getTriple().isArch64Bit())
  7245. return "/system/bin/linker64";
  7246. else
  7247. return "/system/bin/linker";
  7248. } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
  7249. Arch == llvm::Triple::sparcel)
  7250. return "/lib/ld-linux.so.2";
  7251. else if (Arch == llvm::Triple::aarch64)
  7252. return "/lib/ld-linux-aarch64.so.1";
  7253. else if (Arch == llvm::Triple::aarch64_be)
  7254. return "/lib/ld-linux-aarch64_be.so.1";
  7255. else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
  7256. if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
  7257. arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
  7258. return "/lib/ld-linux-armhf.so.3";
  7259. else
  7260. return "/lib/ld-linux.so.3";
  7261. } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
  7262. // TODO: check which dynamic linker name.
  7263. if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
  7264. arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
  7265. return "/lib/ld-linux-armhf.so.3";
  7266. else
  7267. return "/lib/ld-linux.so.3";
  7268. } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
  7269. Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
  7270. std::string LibDir =
  7271. "/lib" + mips::getMipsABILibSuffix(Args, ToolChain.getTriple());
  7272. StringRef LibName;
  7273. bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
  7274. if (mips::isUCLibc(Args))
  7275. LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
  7276. else if (!ToolChain.getTriple().hasEnvironment()) {
  7277. bool LE = (ToolChain.getTriple().getArch() == llvm::Triple::mipsel) ||
  7278. (ToolChain.getTriple().getArch() == llvm::Triple::mips64el);
  7279. LibName = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
  7280. } else
  7281. LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
  7282. return (LibDir + "/" + LibName).str();
  7283. } else if (Arch == llvm::Triple::ppc)
  7284. return "/lib/ld.so.1";
  7285. else if (Arch == llvm::Triple::ppc64) {
  7286. if (ppc::hasPPCAbiArg(Args, "elfv2"))
  7287. return "/lib64/ld64.so.2";
  7288. return "/lib64/ld64.so.1";
  7289. } else if (Arch == llvm::Triple::ppc64le) {
  7290. if (ppc::hasPPCAbiArg(Args, "elfv1"))
  7291. return "/lib64/ld64.so.1";
  7292. return "/lib64/ld64.so.2";
  7293. } else if (Arch == llvm::Triple::systemz)
  7294. return "/lib/ld64.so.1";
  7295. else if (Arch == llvm::Triple::sparcv9)
  7296. return "/lib64/ld-linux.so.2";
  7297. else if (Arch == llvm::Triple::x86_64 &&
  7298. ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
  7299. return "/libx32/ld-linux-x32.so.2";
  7300. else
  7301. return "/lib64/ld-linux-x86-64.so.2";
  7302. }
  7303. static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
  7304. ArgStringList &CmdArgs, const ArgList &Args) {
  7305. // Make use of compiler-rt if --rtlib option is used
  7306. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
  7307. switch (RLT) {
  7308. case ToolChain::RLT_CompilerRT:
  7309. switch (TC.getTriple().getOS()) {
  7310. default:
  7311. llvm_unreachable("unsupported OS");
  7312. case llvm::Triple::Win32:
  7313. case llvm::Triple::Linux:
  7314. addClangRT(TC, Args, CmdArgs);
  7315. break;
  7316. }
  7317. break;
  7318. case ToolChain::RLT_Libgcc:
  7319. AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
  7320. break;
  7321. }
  7322. }
  7323. static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
  7324. switch (T.getArch()) {
  7325. case llvm::Triple::x86:
  7326. return "elf_i386";
  7327. case llvm::Triple::aarch64:
  7328. return "aarch64linux";
  7329. case llvm::Triple::aarch64_be:
  7330. return "aarch64_be_linux";
  7331. case llvm::Triple::arm:
  7332. case llvm::Triple::thumb:
  7333. return "armelf_linux_eabi";
  7334. case llvm::Triple::armeb:
  7335. case llvm::Triple::thumbeb:
  7336. return "armebelf_linux_eabi"; /* TODO: check which NAME. */
  7337. case llvm::Triple::ppc:
  7338. return "elf32ppclinux";
  7339. case llvm::Triple::ppc64:
  7340. return "elf64ppc";
  7341. case llvm::Triple::ppc64le:
  7342. return "elf64lppc";
  7343. case llvm::Triple::sparc:
  7344. case llvm::Triple::sparcel:
  7345. return "elf32_sparc";
  7346. case llvm::Triple::sparcv9:
  7347. return "elf64_sparc";
  7348. case llvm::Triple::mips:
  7349. return "elf32btsmip";
  7350. case llvm::Triple::mipsel:
  7351. return "elf32ltsmip";
  7352. case llvm::Triple::mips64:
  7353. if (mips::hasMipsAbiArg(Args, "n32"))
  7354. return "elf32btsmipn32";
  7355. return "elf64btsmip";
  7356. case llvm::Triple::mips64el:
  7357. if (mips::hasMipsAbiArg(Args, "n32"))
  7358. return "elf32ltsmipn32";
  7359. return "elf64ltsmip";
  7360. case llvm::Triple::systemz:
  7361. return "elf64_s390";
  7362. case llvm::Triple::x86_64:
  7363. if (T.getEnvironment() == llvm::Triple::GNUX32)
  7364. return "elf32_x86_64";
  7365. return "elf_x86_64";
  7366. default:
  7367. llvm_unreachable("Unexpected arch");
  7368. }
  7369. }
  7370. void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7371. const InputInfo &Output,
  7372. const InputInfoList &Inputs,
  7373. const ArgList &Args,
  7374. const char *LinkingOutput) const {
  7375. const toolchains::Linux &ToolChain =
  7376. static_cast<const toolchains::Linux &>(getToolChain());
  7377. const Driver &D = ToolChain.getDriver();
  7378. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  7379. llvm::Triple Triple = llvm::Triple(TripleStr);
  7380. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7381. const bool isAndroid = ToolChain.getTriple().isAndroid();
  7382. const bool IsPIE =
  7383. !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
  7384. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  7385. const bool HasCRTBeginEndFiles =
  7386. ToolChain.getTriple().hasEnvironment() ||
  7387. (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
  7388. ArgStringList CmdArgs;
  7389. // Silence warning for "clang -g foo.o -o foo"
  7390. Args.ClaimAllArgs(options::OPT_g_Group);
  7391. // and "clang -emit-llvm foo.o -o foo"
  7392. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7393. // and for "clang -w foo.o -o foo". Other warning options are already
  7394. // handled somewhere else.
  7395. Args.ClaimAllArgs(options::OPT_w);
  7396. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  7397. if (llvm::sys::path::filename(Exec) == "lld") {
  7398. CmdArgs.push_back("-flavor");
  7399. CmdArgs.push_back("old-gnu");
  7400. CmdArgs.push_back("-target");
  7401. CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
  7402. }
  7403. if (!D.SysRoot.empty())
  7404. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7405. if (IsPIE)
  7406. CmdArgs.push_back("-pie");
  7407. if (Args.hasArg(options::OPT_rdynamic))
  7408. CmdArgs.push_back("-export-dynamic");
  7409. if (Args.hasArg(options::OPT_s))
  7410. CmdArgs.push_back("-s");
  7411. if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
  7412. arm::appendEBLinkFlags(Args, CmdArgs, Triple);
  7413. for (const auto &Opt : ToolChain.ExtraOpts)
  7414. CmdArgs.push_back(Opt.c_str());
  7415. if (!Args.hasArg(options::OPT_static)) {
  7416. CmdArgs.push_back("--eh-frame-hdr");
  7417. }
  7418. CmdArgs.push_back("-m");
  7419. CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
  7420. if (Args.hasArg(options::OPT_static)) {
  7421. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  7422. Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
  7423. CmdArgs.push_back("-Bstatic");
  7424. else
  7425. CmdArgs.push_back("-static");
  7426. } else if (Args.hasArg(options::OPT_shared)) {
  7427. CmdArgs.push_back("-shared");
  7428. }
  7429. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  7430. Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
  7431. (!Args.hasArg(options::OPT_static) &&
  7432. !Args.hasArg(options::OPT_shared))) {
  7433. CmdArgs.push_back("-dynamic-linker");
  7434. CmdArgs.push_back(Args.MakeArgString(
  7435. D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
  7436. }
  7437. CmdArgs.push_back("-o");
  7438. CmdArgs.push_back(Output.getFilename());
  7439. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7440. if (!isAndroid) {
  7441. const char *crt1 = nullptr;
  7442. if (!Args.hasArg(options::OPT_shared)) {
  7443. if (Args.hasArg(options::OPT_pg))
  7444. crt1 = "gcrt1.o";
  7445. else if (IsPIE)
  7446. crt1 = "Scrt1.o";
  7447. else
  7448. crt1 = "crt1.o";
  7449. }
  7450. if (crt1)
  7451. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  7452. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  7453. }
  7454. const char *crtbegin;
  7455. if (Args.hasArg(options::OPT_static))
  7456. crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
  7457. else if (Args.hasArg(options::OPT_shared))
  7458. crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
  7459. else if (IsPIE)
  7460. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
  7461. else
  7462. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
  7463. if (HasCRTBeginEndFiles)
  7464. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  7465. // Add crtfastmath.o if available and fast math is enabled.
  7466. ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  7467. }
  7468. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7469. Args.AddAllArgs(CmdArgs, options::OPT_u);
  7470. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  7471. if (D.isUsingLTO())
  7472. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  7473. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  7474. CmdArgs.push_back("--no-demangle");
  7475. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  7476. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  7477. // The profile runtime also needs access to system libraries.
  7478. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7479. if (D.CCCIsCXX() &&
  7480. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7481. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  7482. !Args.hasArg(options::OPT_static);
  7483. if (OnlyLibstdcxxStatic)
  7484. CmdArgs.push_back("-Bstatic");
  7485. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7486. if (OnlyLibstdcxxStatic)
  7487. CmdArgs.push_back("-Bdynamic");
  7488. CmdArgs.push_back("-lm");
  7489. }
  7490. // Silence warnings when linking C code with a C++ '-stdlib' argument.
  7491. Args.ClaimAllArgs(options::OPT_stdlib_EQ);
  7492. if (!Args.hasArg(options::OPT_nostdlib)) {
  7493. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  7494. if (Args.hasArg(options::OPT_static))
  7495. CmdArgs.push_back("--start-group");
  7496. if (NeedsSanitizerDeps)
  7497. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  7498. bool WantPthread = Args.hasArg(options::OPT_pthread) ||
  7499. Args.hasArg(options::OPT_pthreads);
  7500. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  7501. options::OPT_fno_openmp, false)) {
  7502. // OpenMP runtimes implies pthreads when using the GNU toolchain.
  7503. // FIXME: Does this really make sense for all GNU toolchains?
  7504. WantPthread = true;
  7505. // Also link the particular OpenMP runtimes.
  7506. switch (getOpenMPRuntime(ToolChain, Args)) {
  7507. case OMPRT_OMP:
  7508. CmdArgs.push_back("-lomp");
  7509. break;
  7510. case OMPRT_GOMP:
  7511. CmdArgs.push_back("-lgomp");
  7512. // FIXME: Exclude this for platforms with libgomp that don't require
  7513. // librt. Most modern Linux platforms require it, but some may not.
  7514. CmdArgs.push_back("-lrt");
  7515. break;
  7516. case OMPRT_IOMP5:
  7517. CmdArgs.push_back("-liomp5");
  7518. break;
  7519. case OMPRT_Unknown:
  7520. // Already diagnosed.
  7521. break;
  7522. }
  7523. }
  7524. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  7525. if (WantPthread && !isAndroid)
  7526. CmdArgs.push_back("-lpthread");
  7527. CmdArgs.push_back("-lc");
  7528. if (Args.hasArg(options::OPT_static))
  7529. CmdArgs.push_back("--end-group");
  7530. else
  7531. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  7532. }
  7533. if (!Args.hasArg(options::OPT_nostartfiles)) {
  7534. const char *crtend;
  7535. if (Args.hasArg(options::OPT_shared))
  7536. crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
  7537. else if (IsPIE)
  7538. crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
  7539. else
  7540. crtend = isAndroid ? "crtend_android.o" : "crtend.o";
  7541. if (HasCRTBeginEndFiles)
  7542. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  7543. if (!isAndroid)
  7544. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  7545. }
  7546. } else if (Args.hasArg(options::OPT_rtlib_EQ))
  7547. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  7548. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7549. }
  7550. // NaCl ARM assembly (inline or standalone) can be written with a set of macros
  7551. // for the various SFI requirements like register masking. The assembly tool
  7552. // inserts the file containing the macros as an input into all the assembly
  7553. // jobs.
  7554. void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
  7555. const InputInfo &Output,
  7556. const InputInfoList &Inputs,
  7557. const ArgList &Args,
  7558. const char *LinkingOutput) const {
  7559. const toolchains::NaClToolChain &ToolChain =
  7560. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  7561. InputInfo NaClMacros(ToolChain.GetNaClArmMacrosPath(), types::TY_PP_Asm,
  7562. "nacl-arm-macros.s");
  7563. InputInfoList NewInputs;
  7564. NewInputs.push_back(NaClMacros);
  7565. NewInputs.append(Inputs.begin(), Inputs.end());
  7566. gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
  7567. LinkingOutput);
  7568. }
  7569. // This is quite similar to gnutools::Linker::ConstructJob with changes that
  7570. // we use static by default, do not yet support sanitizers or LTO, and a few
  7571. // others. Eventually we can support more of that and hopefully migrate back
  7572. // to gnutools::Linker.
  7573. void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7574. const InputInfo &Output,
  7575. const InputInfoList &Inputs,
  7576. const ArgList &Args,
  7577. const char *LinkingOutput) const {
  7578. const toolchains::NaClToolChain &ToolChain =
  7579. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  7580. const Driver &D = ToolChain.getDriver();
  7581. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7582. const bool IsStatic =
  7583. !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
  7584. ArgStringList CmdArgs;
  7585. // Silence warning for "clang -g foo.o -o foo"
  7586. Args.ClaimAllArgs(options::OPT_g_Group);
  7587. // and "clang -emit-llvm foo.o -o foo"
  7588. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7589. // and for "clang -w foo.o -o foo". Other warning options are already
  7590. // handled somewhere else.
  7591. Args.ClaimAllArgs(options::OPT_w);
  7592. if (!D.SysRoot.empty())
  7593. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7594. if (Args.hasArg(options::OPT_rdynamic))
  7595. CmdArgs.push_back("-export-dynamic");
  7596. if (Args.hasArg(options::OPT_s))
  7597. CmdArgs.push_back("-s");
  7598. // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
  7599. // from there is --build-id, which we do want.
  7600. CmdArgs.push_back("--build-id");
  7601. if (!IsStatic)
  7602. CmdArgs.push_back("--eh-frame-hdr");
  7603. CmdArgs.push_back("-m");
  7604. if (Arch == llvm::Triple::x86)
  7605. CmdArgs.push_back("elf_i386_nacl");
  7606. else if (Arch == llvm::Triple::arm)
  7607. CmdArgs.push_back("armelf_nacl");
  7608. else if (Arch == llvm::Triple::x86_64)
  7609. CmdArgs.push_back("elf_x86_64_nacl");
  7610. else if (Arch == llvm::Triple::mipsel)
  7611. CmdArgs.push_back("mipselelf_nacl");
  7612. else
  7613. D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
  7614. << "Native Client";
  7615. if (IsStatic)
  7616. CmdArgs.push_back("-static");
  7617. else if (Args.hasArg(options::OPT_shared))
  7618. CmdArgs.push_back("-shared");
  7619. CmdArgs.push_back("-o");
  7620. CmdArgs.push_back(Output.getFilename());
  7621. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7622. if (!Args.hasArg(options::OPT_shared))
  7623. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  7624. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  7625. const char *crtbegin;
  7626. if (IsStatic)
  7627. crtbegin = "crtbeginT.o";
  7628. else if (Args.hasArg(options::OPT_shared))
  7629. crtbegin = "crtbeginS.o";
  7630. else
  7631. crtbegin = "crtbegin.o";
  7632. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  7633. }
  7634. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7635. Args.AddAllArgs(CmdArgs, options::OPT_u);
  7636. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  7637. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  7638. CmdArgs.push_back("--no-demangle");
  7639. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  7640. if (D.CCCIsCXX() &&
  7641. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7642. bool OnlyLibstdcxxStatic =
  7643. Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
  7644. if (OnlyLibstdcxxStatic)
  7645. CmdArgs.push_back("-Bstatic");
  7646. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7647. if (OnlyLibstdcxxStatic)
  7648. CmdArgs.push_back("-Bdynamic");
  7649. CmdArgs.push_back("-lm");
  7650. }
  7651. if (!Args.hasArg(options::OPT_nostdlib)) {
  7652. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  7653. // Always use groups, since it has no effect on dynamic libraries.
  7654. CmdArgs.push_back("--start-group");
  7655. CmdArgs.push_back("-lc");
  7656. // NaCl's libc++ currently requires libpthread, so just always include it
  7657. // in the group for C++.
  7658. if (Args.hasArg(options::OPT_pthread) ||
  7659. Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
  7660. // Gold, used by Mips, handles nested groups differently than ld, and
  7661. // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
  7662. // which is not a desired behaviour here.
  7663. // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
  7664. if (getToolChain().getArch() == llvm::Triple::mipsel)
  7665. CmdArgs.push_back("-lnacl");
  7666. CmdArgs.push_back("-lpthread");
  7667. }
  7668. CmdArgs.push_back("-lgcc");
  7669. CmdArgs.push_back("--as-needed");
  7670. if (IsStatic)
  7671. CmdArgs.push_back("-lgcc_eh");
  7672. else
  7673. CmdArgs.push_back("-lgcc_s");
  7674. CmdArgs.push_back("--no-as-needed");
  7675. // Mips needs to create and use pnacl_legacy library that contains
  7676. // definitions from bitcode/pnaclmm.c and definitions for
  7677. // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
  7678. if (getToolChain().getArch() == llvm::Triple::mipsel)
  7679. CmdArgs.push_back("-lpnacl_legacy");
  7680. CmdArgs.push_back("--end-group");
  7681. }
  7682. if (!Args.hasArg(options::OPT_nostartfiles)) {
  7683. const char *crtend;
  7684. if (Args.hasArg(options::OPT_shared))
  7685. crtend = "crtendS.o";
  7686. else
  7687. crtend = "crtend.o";
  7688. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  7689. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  7690. }
  7691. }
  7692. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  7693. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7694. }
  7695. void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7696. const InputInfo &Output,
  7697. const InputInfoList &Inputs,
  7698. const ArgList &Args,
  7699. const char *LinkingOutput) const {
  7700. claimNoWarnArgs(Args);
  7701. ArgStringList CmdArgs;
  7702. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7703. CmdArgs.push_back("-o");
  7704. CmdArgs.push_back(Output.getFilename());
  7705. for (const auto &II : Inputs)
  7706. CmdArgs.push_back(II.getFilename());
  7707. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7708. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7709. }
  7710. void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7711. const InputInfo &Output,
  7712. const InputInfoList &Inputs,
  7713. const ArgList &Args,
  7714. const char *LinkingOutput) const {
  7715. const Driver &D = getToolChain().getDriver();
  7716. ArgStringList CmdArgs;
  7717. if (Output.isFilename()) {
  7718. CmdArgs.push_back("-o");
  7719. CmdArgs.push_back(Output.getFilename());
  7720. } else {
  7721. assert(Output.isNothing() && "Invalid output.");
  7722. }
  7723. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7724. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  7725. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7726. CmdArgs.push_back(
  7727. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7728. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  7729. }
  7730. Args.AddAllArgs(CmdArgs,
  7731. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  7732. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7733. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7734. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7735. if (D.CCCIsCXX()) {
  7736. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7737. CmdArgs.push_back("-lm");
  7738. }
  7739. }
  7740. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7741. if (Args.hasArg(options::OPT_pthread))
  7742. CmdArgs.push_back("-lpthread");
  7743. CmdArgs.push_back("-lc");
  7744. CmdArgs.push_back("-lCompilerRT-Generic");
  7745. CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
  7746. CmdArgs.push_back(
  7747. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7748. }
  7749. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7750. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7751. }
  7752. /// DragonFly Tools
  7753. // For now, DragonFly Assemble does just about the same as for
  7754. // FreeBSD, but this may change soon.
  7755. void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7756. const InputInfo &Output,
  7757. const InputInfoList &Inputs,
  7758. const ArgList &Args,
  7759. const char *LinkingOutput) const {
  7760. claimNoWarnArgs(Args);
  7761. ArgStringList CmdArgs;
  7762. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  7763. // instruct as in the base system to assemble 32-bit code.
  7764. if (getToolChain().getArch() == llvm::Triple::x86)
  7765. CmdArgs.push_back("--32");
  7766. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7767. CmdArgs.push_back("-o");
  7768. CmdArgs.push_back(Output.getFilename());
  7769. for (const auto &II : Inputs)
  7770. CmdArgs.push_back(II.getFilename());
  7771. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7772. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7773. }
  7774. void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7775. const InputInfo &Output,
  7776. const InputInfoList &Inputs,
  7777. const ArgList &Args,
  7778. const char *LinkingOutput) const {
  7779. const Driver &D = getToolChain().getDriver();
  7780. ArgStringList CmdArgs;
  7781. bool UseGCC47 = llvm::sys::fs::exists("/usr/lib/gcc47");
  7782. if (!D.SysRoot.empty())
  7783. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7784. CmdArgs.push_back("--eh-frame-hdr");
  7785. if (Args.hasArg(options::OPT_static)) {
  7786. CmdArgs.push_back("-Bstatic");
  7787. } else {
  7788. if (Args.hasArg(options::OPT_rdynamic))
  7789. CmdArgs.push_back("-export-dynamic");
  7790. if (Args.hasArg(options::OPT_shared))
  7791. CmdArgs.push_back("-Bshareable");
  7792. else {
  7793. CmdArgs.push_back("-dynamic-linker");
  7794. CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
  7795. }
  7796. CmdArgs.push_back("--hash-style=both");
  7797. }
  7798. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  7799. // instruct ld in the base system to link 32-bit code.
  7800. if (getToolChain().getArch() == llvm::Triple::x86) {
  7801. CmdArgs.push_back("-m");
  7802. CmdArgs.push_back("elf_i386");
  7803. }
  7804. if (Output.isFilename()) {
  7805. CmdArgs.push_back("-o");
  7806. CmdArgs.push_back(Output.getFilename());
  7807. } else {
  7808. assert(Output.isNothing() && "Invalid output.");
  7809. }
  7810. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7811. if (!Args.hasArg(options::OPT_shared)) {
  7812. if (Args.hasArg(options::OPT_pg))
  7813. CmdArgs.push_back(
  7814. Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
  7815. else {
  7816. if (Args.hasArg(options::OPT_pie))
  7817. CmdArgs.push_back(
  7818. Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
  7819. else
  7820. CmdArgs.push_back(
  7821. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  7822. }
  7823. }
  7824. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7825. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  7826. CmdArgs.push_back(
  7827. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7828. else
  7829. CmdArgs.push_back(
  7830. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7831. }
  7832. Args.AddAllArgs(CmdArgs,
  7833. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  7834. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7835. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7836. // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
  7837. // rpaths
  7838. if (UseGCC47)
  7839. CmdArgs.push_back("-L/usr/lib/gcc47");
  7840. else
  7841. CmdArgs.push_back("-L/usr/lib/gcc44");
  7842. if (!Args.hasArg(options::OPT_static)) {
  7843. if (UseGCC47) {
  7844. CmdArgs.push_back("-rpath");
  7845. CmdArgs.push_back("/usr/lib/gcc47");
  7846. } else {
  7847. CmdArgs.push_back("-rpath");
  7848. CmdArgs.push_back("/usr/lib/gcc44");
  7849. }
  7850. }
  7851. if (D.CCCIsCXX()) {
  7852. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7853. CmdArgs.push_back("-lm");
  7854. }
  7855. if (Args.hasArg(options::OPT_pthread))
  7856. CmdArgs.push_back("-lpthread");
  7857. if (!Args.hasArg(options::OPT_nolibc)) {
  7858. CmdArgs.push_back("-lc");
  7859. }
  7860. if (UseGCC47) {
  7861. if (Args.hasArg(options::OPT_static) ||
  7862. Args.hasArg(options::OPT_static_libgcc)) {
  7863. CmdArgs.push_back("-lgcc");
  7864. CmdArgs.push_back("-lgcc_eh");
  7865. } else {
  7866. if (Args.hasArg(options::OPT_shared_libgcc)) {
  7867. CmdArgs.push_back("-lgcc_pic");
  7868. if (!Args.hasArg(options::OPT_shared))
  7869. CmdArgs.push_back("-lgcc");
  7870. } else {
  7871. CmdArgs.push_back("-lgcc");
  7872. CmdArgs.push_back("--as-needed");
  7873. CmdArgs.push_back("-lgcc_pic");
  7874. CmdArgs.push_back("--no-as-needed");
  7875. }
  7876. }
  7877. } else {
  7878. if (Args.hasArg(options::OPT_shared)) {
  7879. CmdArgs.push_back("-lgcc_pic");
  7880. } else {
  7881. CmdArgs.push_back("-lgcc");
  7882. }
  7883. }
  7884. }
  7885. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7886. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  7887. CmdArgs.push_back(
  7888. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7889. else
  7890. CmdArgs.push_back(
  7891. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7892. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  7893. }
  7894. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7895. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7896. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7897. }
  7898. // Try to find Exe from a Visual Studio distribution. This first tries to find
  7899. // an installed copy of Visual Studio and, failing that, looks in the PATH,
  7900. // making sure that whatever executable that's found is not a same-named exe
  7901. // from clang itself to prevent clang from falling back to itself.
  7902. static std::string FindVisualStudioExecutable(const ToolChain &TC,
  7903. const char *Exe,
  7904. const char *ClangProgramPath) {
  7905. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  7906. std::string visualStudioBinDir;
  7907. if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
  7908. visualStudioBinDir)) {
  7909. SmallString<128> FilePath(visualStudioBinDir);
  7910. llvm::sys::path::append(FilePath, Exe);
  7911. if (llvm::sys::fs::can_execute(FilePath.c_str()))
  7912. return FilePath.str();
  7913. }
  7914. return Exe;
  7915. }
  7916. void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7917. const InputInfo &Output,
  7918. const InputInfoList &Inputs,
  7919. const ArgList &Args,
  7920. const char *LinkingOutput) const {
  7921. ArgStringList CmdArgs;
  7922. const ToolChain &TC = getToolChain();
  7923. assert((Output.isFilename() || Output.isNothing()) && "invalid output");
  7924. if (Output.isFilename())
  7925. CmdArgs.push_back(
  7926. Args.MakeArgString(std::string("-out:") + Output.getFilename()));
  7927. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
  7928. !C.getDriver().IsCLMode())
  7929. CmdArgs.push_back("-defaultlib:libcmt");
  7930. if (!llvm::sys::Process::GetEnv("LIB")) {
  7931. // If the VC environment hasn't been configured (perhaps because the user
  7932. // did not run vcvarsall), try to build a consistent link environment. If
  7933. // the environment variable is set however, assume the user knows what
  7934. // they're doing.
  7935. std::string VisualStudioDir;
  7936. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  7937. if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
  7938. SmallString<128> LibDir(VisualStudioDir);
  7939. llvm::sys::path::append(LibDir, "VC", "lib");
  7940. switch (MSVC.getArch()) {
  7941. case llvm::Triple::x86:
  7942. // x86 just puts the libraries directly in lib
  7943. break;
  7944. case llvm::Triple::x86_64:
  7945. llvm::sys::path::append(LibDir, "amd64");
  7946. break;
  7947. case llvm::Triple::arm:
  7948. llvm::sys::path::append(LibDir, "arm");
  7949. break;
  7950. default:
  7951. break;
  7952. }
  7953. CmdArgs.push_back(
  7954. Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
  7955. if (MSVC.useUniversalCRT(VisualStudioDir)) {
  7956. std::string UniversalCRTLibPath;
  7957. if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
  7958. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  7959. UniversalCRTLibPath.c_str()));
  7960. }
  7961. }
  7962. std::string WindowsSdkLibPath;
  7963. if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
  7964. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  7965. WindowsSdkLibPath.c_str()));
  7966. }
  7967. CmdArgs.push_back("-nologo");
  7968. if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
  7969. CmdArgs.push_back("-debug");
  7970. bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
  7971. options::OPT_shared);
  7972. if (DLL) {
  7973. CmdArgs.push_back(Args.MakeArgString("-dll"));
  7974. SmallString<128> ImplibName(Output.getFilename());
  7975. llvm::sys::path::replace_extension(ImplibName, "lib");
  7976. CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
  7977. }
  7978. if (TC.getSanitizerArgs().needsAsanRt()) {
  7979. CmdArgs.push_back(Args.MakeArgString("-debug"));
  7980. CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
  7981. if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
  7982. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  7983. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  7984. // Make sure the dynamic runtime thunk is not optimized out at link time
  7985. // to ensure proper SEH handling.
  7986. CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
  7987. } else if (DLL) {
  7988. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  7989. } else {
  7990. for (const auto &Lib : {"asan", "asan_cxx"})
  7991. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  7992. }
  7993. }
  7994. Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
  7995. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  7996. options::OPT_fno_openmp, false)) {
  7997. CmdArgs.push_back("-nodefaultlib:vcomp.lib");
  7998. CmdArgs.push_back("-nodefaultlib:vcompd.lib");
  7999. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8000. TC.getDriver().Dir + "/../lib"));
  8001. switch (getOpenMPRuntime(getToolChain(), Args)) {
  8002. case OMPRT_OMP:
  8003. CmdArgs.push_back("-defaultlib:libomp.lib");
  8004. break;
  8005. case OMPRT_IOMP5:
  8006. CmdArgs.push_back("-defaultlib:libiomp5md.lib");
  8007. break;
  8008. case OMPRT_GOMP:
  8009. break;
  8010. case OMPRT_Unknown:
  8011. // Already diagnosed.
  8012. break;
  8013. }
  8014. }
  8015. // Add filenames, libraries, and other linker inputs.
  8016. for (const auto &Input : Inputs) {
  8017. if (Input.isFilename()) {
  8018. CmdArgs.push_back(Input.getFilename());
  8019. continue;
  8020. }
  8021. const Arg &A = Input.getInputArg();
  8022. // Render -l options differently for the MSVC linker.
  8023. if (A.getOption().matches(options::OPT_l)) {
  8024. StringRef Lib = A.getValue();
  8025. const char *LinkLibArg;
  8026. if (Lib.endswith(".lib"))
  8027. LinkLibArg = Args.MakeArgString(Lib);
  8028. else
  8029. LinkLibArg = Args.MakeArgString(Lib + ".lib");
  8030. CmdArgs.push_back(LinkLibArg);
  8031. continue;
  8032. }
  8033. // Otherwise, this is some other kind of linker input option like -Wl, -z,
  8034. // or -L. Render it, even if MSVC doesn't understand it.
  8035. A.renderAsInput(Args, CmdArgs);
  8036. }
  8037. // We need to special case some linker paths. In the case of lld, we need to
  8038. // translate 'lld' into 'lld-link', and in the case of the regular msvc
  8039. // linker, we need to use a special search algorithm.
  8040. llvm::SmallString<128> linkPath;
  8041. StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
  8042. if (Linker.equals_lower("lld"))
  8043. Linker = "lld-link";
  8044. if (Linker.equals_lower("link")) {
  8045. // If we're using the MSVC linker, it's not sufficient to just use link
  8046. // from the program PATH, because other environments like GnuWin32 install
  8047. // their own link.exe which may come first.
  8048. linkPath = FindVisualStudioExecutable(TC, "link.exe",
  8049. C.getDriver().getClangProgramPath());
  8050. } else {
  8051. linkPath = Linker;
  8052. llvm::sys::path::replace_extension(linkPath, "exe");
  8053. linkPath = TC.GetProgramPath(linkPath.c_str());
  8054. }
  8055. const char *Exec = Args.MakeArgString(linkPath);
  8056. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8057. }
  8058. void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  8059. const InputInfo &Output,
  8060. const InputInfoList &Inputs,
  8061. const ArgList &Args,
  8062. const char *LinkingOutput) const {
  8063. C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
  8064. }
  8065. std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
  8066. Compilation &C, const JobAction &JA, const InputInfo &Output,
  8067. const InputInfoList &Inputs, const ArgList &Args,
  8068. const char *LinkingOutput) const {
  8069. ArgStringList CmdArgs;
  8070. CmdArgs.push_back("/nologo");
  8071. CmdArgs.push_back("/c"); // Compile only.
  8072. CmdArgs.push_back("/W0"); // No warnings.
  8073. // The goal is to be able to invoke this tool correctly based on
  8074. // any flag accepted by clang-cl.
  8075. // These are spelled the same way in clang and cl.exe,.
  8076. Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
  8077. // Optimization level.
  8078. if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
  8079. CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
  8080. : "/Oi-");
  8081. if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
  8082. if (A->getOption().getID() == options::OPT_O0) {
  8083. CmdArgs.push_back("/Od");
  8084. } else {
  8085. CmdArgs.push_back("/Og");
  8086. StringRef OptLevel = A->getValue();
  8087. if (OptLevel == "s" || OptLevel == "z")
  8088. CmdArgs.push_back("/Os");
  8089. else
  8090. CmdArgs.push_back("/Ot");
  8091. CmdArgs.push_back("/Ob2");
  8092. }
  8093. }
  8094. if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
  8095. options::OPT_fno_omit_frame_pointer))
  8096. CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
  8097. ? "/Oy"
  8098. : "/Oy-");
  8099. if (!Args.hasArg(options::OPT_fwritable_strings))
  8100. CmdArgs.push_back("/GF");
  8101. // Flags for which clang-cl has an alias.
  8102. // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
  8103. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  8104. /*default=*/false))
  8105. CmdArgs.push_back("/GR-");
  8106. if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
  8107. options::OPT_fno_function_sections))
  8108. CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
  8109. ? "/Gy"
  8110. : "/Gy-");
  8111. if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
  8112. options::OPT_fno_data_sections))
  8113. CmdArgs.push_back(
  8114. A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
  8115. if (Args.hasArg(options::OPT_fsyntax_only))
  8116. CmdArgs.push_back("/Zs");
  8117. if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
  8118. options::OPT__SLASH_Z7))
  8119. CmdArgs.push_back("/Z7");
  8120. std::vector<std::string> Includes =
  8121. Args.getAllArgValues(options::OPT_include);
  8122. for (const auto &Include : Includes)
  8123. CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
  8124. // Flags that can simply be passed through.
  8125. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
  8126. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
  8127. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
  8128. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
  8129. // The order of these flags is relevant, so pick the last one.
  8130. if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
  8131. options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
  8132. A->render(Args, CmdArgs);
  8133. // Input filename.
  8134. assert(Inputs.size() == 1);
  8135. const InputInfo &II = Inputs[0];
  8136. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
  8137. CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
  8138. if (II.isFilename())
  8139. CmdArgs.push_back(II.getFilename());
  8140. else
  8141. II.getInputArg().renderAsInput(Args, CmdArgs);
  8142. // Output filename.
  8143. assert(Output.getType() == types::TY_Object);
  8144. const char *Fo =
  8145. Args.MakeArgString(std::string("/Fo") + Output.getFilename());
  8146. CmdArgs.push_back(Fo);
  8147. const Driver &D = getToolChain().getDriver();
  8148. std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
  8149. D.getClangProgramPath());
  8150. return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8151. CmdArgs, Inputs);
  8152. }
  8153. /// MinGW Tools
  8154. void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8155. const InputInfo &Output,
  8156. const InputInfoList &Inputs,
  8157. const ArgList &Args,
  8158. const char *LinkingOutput) const {
  8159. claimNoWarnArgs(Args);
  8160. ArgStringList CmdArgs;
  8161. if (getToolChain().getArch() == llvm::Triple::x86) {
  8162. CmdArgs.push_back("--32");
  8163. } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
  8164. CmdArgs.push_back("--64");
  8165. }
  8166. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8167. CmdArgs.push_back("-o");
  8168. CmdArgs.push_back(Output.getFilename());
  8169. for (const auto &II : Inputs)
  8170. CmdArgs.push_back(II.getFilename());
  8171. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8172. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8173. if (Args.hasArg(options::OPT_gsplit_dwarf))
  8174. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  8175. SplitDebugName(Args, Inputs[0]));
  8176. }
  8177. void MinGW::Linker::AddLibGCC(const ArgList &Args,
  8178. ArgStringList &CmdArgs) const {
  8179. if (Args.hasArg(options::OPT_mthreads))
  8180. CmdArgs.push_back("-lmingwthrd");
  8181. CmdArgs.push_back("-lmingw32");
  8182. // Make use of compiler-rt if --rtlib option is used
  8183. ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
  8184. if (RLT == ToolChain::RLT_Libgcc) {
  8185. bool Static = Args.hasArg(options::OPT_static_libgcc) ||
  8186. Args.hasArg(options::OPT_static);
  8187. bool Shared = Args.hasArg(options::OPT_shared);
  8188. bool CXX = getToolChain().getDriver().CCCIsCXX();
  8189. if (Static || (!CXX && !Shared)) {
  8190. CmdArgs.push_back("-lgcc");
  8191. CmdArgs.push_back("-lgcc_eh");
  8192. } else {
  8193. CmdArgs.push_back("-lgcc_s");
  8194. CmdArgs.push_back("-lgcc");
  8195. }
  8196. } else {
  8197. AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
  8198. }
  8199. CmdArgs.push_back("-lmoldname");
  8200. CmdArgs.push_back("-lmingwex");
  8201. CmdArgs.push_back("-lmsvcrt");
  8202. }
  8203. void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8204. const InputInfo &Output,
  8205. const InputInfoList &Inputs,
  8206. const ArgList &Args,
  8207. const char *LinkingOutput) const {
  8208. const ToolChain &TC = getToolChain();
  8209. const Driver &D = TC.getDriver();
  8210. // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
  8211. ArgStringList CmdArgs;
  8212. // Silence warning for "clang -g foo.o -o foo"
  8213. Args.ClaimAllArgs(options::OPT_g_Group);
  8214. // and "clang -emit-llvm foo.o -o foo"
  8215. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8216. // and for "clang -w foo.o -o foo". Other warning options are already
  8217. // handled somewhere else.
  8218. Args.ClaimAllArgs(options::OPT_w);
  8219. StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
  8220. if (LinkerName.equals_lower("lld")) {
  8221. CmdArgs.push_back("-flavor");
  8222. CmdArgs.push_back("gnu");
  8223. } else if (!LinkerName.equals_lower("ld")) {
  8224. D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
  8225. }
  8226. if (!D.SysRoot.empty())
  8227. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8228. if (Args.hasArg(options::OPT_s))
  8229. CmdArgs.push_back("-s");
  8230. CmdArgs.push_back("-m");
  8231. if (TC.getArch() == llvm::Triple::x86)
  8232. CmdArgs.push_back("i386pe");
  8233. if (TC.getArch() == llvm::Triple::x86_64)
  8234. CmdArgs.push_back("i386pep");
  8235. if (TC.getArch() == llvm::Triple::arm)
  8236. CmdArgs.push_back("thumb2pe");
  8237. if (Args.hasArg(options::OPT_mwindows)) {
  8238. CmdArgs.push_back("--subsystem");
  8239. CmdArgs.push_back("windows");
  8240. } else if (Args.hasArg(options::OPT_mconsole)) {
  8241. CmdArgs.push_back("--subsystem");
  8242. CmdArgs.push_back("console");
  8243. }
  8244. if (Args.hasArg(options::OPT_static))
  8245. CmdArgs.push_back("-Bstatic");
  8246. else {
  8247. if (Args.hasArg(options::OPT_mdll))
  8248. CmdArgs.push_back("--dll");
  8249. else if (Args.hasArg(options::OPT_shared))
  8250. CmdArgs.push_back("--shared");
  8251. CmdArgs.push_back("-Bdynamic");
  8252. if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
  8253. CmdArgs.push_back("-e");
  8254. if (TC.getArch() == llvm::Triple::x86)
  8255. CmdArgs.push_back("_DllMainCRTStartup@12");
  8256. else
  8257. CmdArgs.push_back("DllMainCRTStartup");
  8258. CmdArgs.push_back("--enable-auto-image-base");
  8259. }
  8260. }
  8261. CmdArgs.push_back("-o");
  8262. CmdArgs.push_back(Output.getFilename());
  8263. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8264. // FIXME: add -N, -n flags
  8265. Args.AddLastArg(CmdArgs, options::OPT_r);
  8266. Args.AddLastArg(CmdArgs, options::OPT_s);
  8267. Args.AddLastArg(CmdArgs, options::OPT_t);
  8268. Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
  8269. Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
  8270. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8271. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
  8272. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
  8273. } else {
  8274. if (Args.hasArg(options::OPT_municode))
  8275. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
  8276. else
  8277. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
  8278. }
  8279. if (Args.hasArg(options::OPT_pg))
  8280. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
  8281. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  8282. }
  8283. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8284. TC.AddFilePathLibArgs(Args, CmdArgs);
  8285. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  8286. // TODO: Add ASan stuff here
  8287. // TODO: Add profile stuff here
  8288. if (D.CCCIsCXX() &&
  8289. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8290. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  8291. !Args.hasArg(options::OPT_static);
  8292. if (OnlyLibstdcxxStatic)
  8293. CmdArgs.push_back("-Bstatic");
  8294. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  8295. if (OnlyLibstdcxxStatic)
  8296. CmdArgs.push_back("-Bdynamic");
  8297. }
  8298. if (!Args.hasArg(options::OPT_nostdlib)) {
  8299. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8300. if (Args.hasArg(options::OPT_static))
  8301. CmdArgs.push_back("--start-group");
  8302. if (Args.hasArg(options::OPT_fstack_protector) ||
  8303. Args.hasArg(options::OPT_fstack_protector_strong) ||
  8304. Args.hasArg(options::OPT_fstack_protector_all)) {
  8305. CmdArgs.push_back("-lssp_nonshared");
  8306. CmdArgs.push_back("-lssp");
  8307. }
  8308. if (Args.hasArg(options::OPT_fopenmp))
  8309. CmdArgs.push_back("-lgomp");
  8310. AddLibGCC(Args, CmdArgs);
  8311. if (Args.hasArg(options::OPT_pg))
  8312. CmdArgs.push_back("-lgmon");
  8313. if (Args.hasArg(options::OPT_pthread))
  8314. CmdArgs.push_back("-lpthread");
  8315. // add system libraries
  8316. if (Args.hasArg(options::OPT_mwindows)) {
  8317. CmdArgs.push_back("-lgdi32");
  8318. CmdArgs.push_back("-lcomdlg32");
  8319. }
  8320. CmdArgs.push_back("-ladvapi32");
  8321. CmdArgs.push_back("-lshell32");
  8322. CmdArgs.push_back("-luser32");
  8323. CmdArgs.push_back("-lkernel32");
  8324. if (Args.hasArg(options::OPT_static))
  8325. CmdArgs.push_back("--end-group");
  8326. else if (!LinkerName.equals_lower("lld"))
  8327. AddLibGCC(Args, CmdArgs);
  8328. }
  8329. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8330. // Add crtfastmath.o if available and fast math is enabled.
  8331. TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  8332. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  8333. }
  8334. }
  8335. const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
  8336. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8337. }
  8338. /// XCore Tools
  8339. // We pass assemble and link construction to the xcc tool.
  8340. void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8341. const InputInfo &Output,
  8342. const InputInfoList &Inputs,
  8343. const ArgList &Args,
  8344. const char *LinkingOutput) const {
  8345. claimNoWarnArgs(Args);
  8346. ArgStringList CmdArgs;
  8347. CmdArgs.push_back("-o");
  8348. CmdArgs.push_back(Output.getFilename());
  8349. CmdArgs.push_back("-c");
  8350. if (Args.hasArg(options::OPT_v))
  8351. CmdArgs.push_back("-v");
  8352. if (Arg *A = Args.getLastArg(options::OPT_g_Group))
  8353. if (!A->getOption().matches(options::OPT_g0))
  8354. CmdArgs.push_back("-g");
  8355. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  8356. false))
  8357. CmdArgs.push_back("-fverbose-asm");
  8358. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8359. for (const auto &II : Inputs)
  8360. CmdArgs.push_back(II.getFilename());
  8361. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8362. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8363. }
  8364. void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8365. const InputInfo &Output,
  8366. const InputInfoList &Inputs,
  8367. const ArgList &Args,
  8368. const char *LinkingOutput) const {
  8369. ArgStringList CmdArgs;
  8370. if (Output.isFilename()) {
  8371. CmdArgs.push_back("-o");
  8372. CmdArgs.push_back(Output.getFilename());
  8373. } else {
  8374. assert(Output.isNothing() && "Invalid output.");
  8375. }
  8376. if (Args.hasArg(options::OPT_v))
  8377. CmdArgs.push_back("-v");
  8378. // Pass -fexceptions through to the linker if it was present.
  8379. if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  8380. false))
  8381. CmdArgs.push_back("-fexceptions");
  8382. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8383. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8384. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8385. }
  8386. void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8387. const InputInfo &Output,
  8388. const InputInfoList &Inputs,
  8389. const ArgList &Args,
  8390. const char *LinkingOutput) const {
  8391. claimNoWarnArgs(Args);
  8392. const auto &TC =
  8393. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  8394. ArgStringList CmdArgs;
  8395. const char *Exec;
  8396. switch (TC.getArch()) {
  8397. default:
  8398. llvm_unreachable("unsupported architecture");
  8399. case llvm::Triple::arm:
  8400. case llvm::Triple::thumb:
  8401. break;
  8402. case llvm::Triple::x86:
  8403. CmdArgs.push_back("--32");
  8404. break;
  8405. case llvm::Triple::x86_64:
  8406. CmdArgs.push_back("--64");
  8407. break;
  8408. }
  8409. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8410. CmdArgs.push_back("-o");
  8411. CmdArgs.push_back(Output.getFilename());
  8412. for (const auto &Input : Inputs)
  8413. CmdArgs.push_back(Input.getFilename());
  8414. const std::string Assembler = TC.GetProgramPath("as");
  8415. Exec = Args.MakeArgString(Assembler);
  8416. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8417. }
  8418. void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8419. const InputInfo &Output,
  8420. const InputInfoList &Inputs,
  8421. const ArgList &Args,
  8422. const char *LinkingOutput) const {
  8423. const auto &TC =
  8424. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  8425. const llvm::Triple &T = TC.getTriple();
  8426. const Driver &D = TC.getDriver();
  8427. SmallString<128> EntryPoint;
  8428. ArgStringList CmdArgs;
  8429. const char *Exec;
  8430. // Silence warning for "clang -g foo.o -o foo"
  8431. Args.ClaimAllArgs(options::OPT_g_Group);
  8432. // and "clang -emit-llvm foo.o -o foo"
  8433. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8434. // and for "clang -w foo.o -o foo"
  8435. Args.ClaimAllArgs(options::OPT_w);
  8436. // Other warning options are already handled somewhere else.
  8437. if (!D.SysRoot.empty())
  8438. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8439. if (Args.hasArg(options::OPT_pie))
  8440. CmdArgs.push_back("-pie");
  8441. if (Args.hasArg(options::OPT_rdynamic))
  8442. CmdArgs.push_back("-export-dynamic");
  8443. if (Args.hasArg(options::OPT_s))
  8444. CmdArgs.push_back("--strip-all");
  8445. CmdArgs.push_back("-m");
  8446. switch (TC.getArch()) {
  8447. default:
  8448. llvm_unreachable("unsupported architecture");
  8449. case llvm::Triple::arm:
  8450. case llvm::Triple::thumb:
  8451. // FIXME: this is incorrect for WinCE
  8452. CmdArgs.push_back("thumb2pe");
  8453. break;
  8454. case llvm::Triple::x86:
  8455. CmdArgs.push_back("i386pe");
  8456. EntryPoint.append("_");
  8457. break;
  8458. case llvm::Triple::x86_64:
  8459. CmdArgs.push_back("i386pep");
  8460. break;
  8461. }
  8462. if (Args.hasArg(options::OPT_shared)) {
  8463. switch (T.getArch()) {
  8464. default:
  8465. llvm_unreachable("unsupported architecture");
  8466. case llvm::Triple::arm:
  8467. case llvm::Triple::thumb:
  8468. case llvm::Triple::x86_64:
  8469. EntryPoint.append("_DllMainCRTStartup");
  8470. break;
  8471. case llvm::Triple::x86:
  8472. EntryPoint.append("_DllMainCRTStartup@12");
  8473. break;
  8474. }
  8475. CmdArgs.push_back("-shared");
  8476. CmdArgs.push_back("-Bdynamic");
  8477. CmdArgs.push_back("--enable-auto-image-base");
  8478. CmdArgs.push_back("--entry");
  8479. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  8480. } else {
  8481. EntryPoint.append("mainCRTStartup");
  8482. CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
  8483. : "-Bdynamic");
  8484. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8485. CmdArgs.push_back("--entry");
  8486. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  8487. }
  8488. // FIXME: handle subsystem
  8489. }
  8490. // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
  8491. CmdArgs.push_back("--allow-multiple-definition");
  8492. CmdArgs.push_back("-o");
  8493. CmdArgs.push_back(Output.getFilename());
  8494. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
  8495. SmallString<261> ImpLib(Output.getFilename());
  8496. llvm::sys::path::replace_extension(ImpLib, ".lib");
  8497. CmdArgs.push_back("--out-implib");
  8498. CmdArgs.push_back(Args.MakeArgString(ImpLib));
  8499. }
  8500. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8501. const std::string CRTPath(D.SysRoot + "/usr/lib/");
  8502. const char *CRTBegin;
  8503. CRTBegin =
  8504. Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
  8505. CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
  8506. }
  8507. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8508. TC.AddFilePathLibArgs(Args, CmdArgs);
  8509. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  8510. if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
  8511. !Args.hasArg(options::OPT_nodefaultlibs)) {
  8512. bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
  8513. !Args.hasArg(options::OPT_static);
  8514. if (StaticCXX)
  8515. CmdArgs.push_back("-Bstatic");
  8516. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  8517. if (StaticCXX)
  8518. CmdArgs.push_back("-Bdynamic");
  8519. }
  8520. if (!Args.hasArg(options::OPT_nostdlib)) {
  8521. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8522. // TODO handle /MT[d] /MD[d]
  8523. CmdArgs.push_back("-lmsvcrt");
  8524. AddRunTimeLibs(TC, D, CmdArgs, Args);
  8525. }
  8526. }
  8527. if (TC.getSanitizerArgs().needsAsanRt()) {
  8528. // TODO handle /MT[d] /MD[d]
  8529. if (Args.hasArg(options::OPT_shared)) {
  8530. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  8531. } else {
  8532. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  8533. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  8534. // Make sure the dynamic runtime thunk is not optimized out at link time
  8535. // to ensure proper SEH handling.
  8536. CmdArgs.push_back(Args.MakeArgString("--undefined"));
  8537. CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
  8538. ? "___asan_seh_interceptor"
  8539. : "__asan_seh_interceptor"));
  8540. }
  8541. }
  8542. Exec = Args.MakeArgString(TC.GetLinkerPath());
  8543. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8544. }
  8545. void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  8546. const InputInfo &Output,
  8547. const InputInfoList &Inputs,
  8548. const ArgList &Args,
  8549. const char *LinkingOutput) const {
  8550. ArgStringList CmdArgs;
  8551. assert(Inputs.size() == 1);
  8552. const InputInfo &II = Inputs[0];
  8553. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
  8554. II.getType() == types::TY_PP_CXX);
  8555. if (JA.getKind() == Action::PreprocessJobClass) {
  8556. Args.ClaimAllArgs();
  8557. CmdArgs.push_back("-E");
  8558. } else {
  8559. assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
  8560. CmdArgs.push_back("-S");
  8561. CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
  8562. }
  8563. CmdArgs.push_back("-mcpu=myriad2");
  8564. CmdArgs.push_back("-DMYRIAD2");
  8565. // Append all -I, -iquote, -isystem paths, defines/undefines,
  8566. // 'f' flags, optimize flags, and warning options.
  8567. // These are spelled the same way in clang and moviCompile.
  8568. Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
  8569. options::OPT_std_EQ, options::OPT_D, options::OPT_U,
  8570. options::OPT_f_Group, options::OPT_f_clang_Group,
  8571. options::OPT_g_Group, options::OPT_M_Group,
  8572. options::OPT_O_Group, options::OPT_W_Group});
  8573. // If we're producing a dependency file, and assembly is the final action,
  8574. // then the name of the target in the dependency file should be the '.o'
  8575. // file, not the '.s' file produced by this step. For example, instead of
  8576. // /tmp/mumble.s: mumble.c .../someheader.h
  8577. // the filename on the lefthand side should be "mumble.o"
  8578. if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
  8579. C.getActions().size() == 1 &&
  8580. C.getActions()[0]->getKind() == Action::AssembleJobClass) {
  8581. Arg *A = Args.getLastArg(options::OPT_o);
  8582. if (A) {
  8583. CmdArgs.push_back("-MT");
  8584. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  8585. }
  8586. }
  8587. CmdArgs.push_back(II.getFilename());
  8588. CmdArgs.push_back("-o");
  8589. CmdArgs.push_back(Output.getFilename());
  8590. std::string Exec =
  8591. Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
  8592. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8593. CmdArgs, Inputs));
  8594. }
  8595. void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8596. const InputInfo &Output,
  8597. const InputInfoList &Inputs,
  8598. const ArgList &Args,
  8599. const char *LinkingOutput) const {
  8600. ArgStringList CmdArgs;
  8601. assert(Inputs.size() == 1);
  8602. const InputInfo &II = Inputs[0];
  8603. assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
  8604. assert(Output.getType() == types::TY_Object);
  8605. CmdArgs.push_back("-no6thSlotCompression");
  8606. CmdArgs.push_back("-cv:myriad2"); // Chip Version
  8607. CmdArgs.push_back("-noSPrefixing");
  8608. CmdArgs.push_back("-a"); // Mystery option.
  8609. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8610. for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
  8611. A->claim();
  8612. CmdArgs.push_back(
  8613. Args.MakeArgString(std::string("-i:") + A->getValue(0)));
  8614. }
  8615. CmdArgs.push_back("-elf"); // Output format.
  8616. CmdArgs.push_back(II.getFilename());
  8617. CmdArgs.push_back(
  8618. Args.MakeArgString(std::string("-o:") + Output.getFilename()));
  8619. std::string Exec =
  8620. Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
  8621. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8622. CmdArgs, Inputs));
  8623. }
  8624. void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8625. const InputInfo &Output,
  8626. const InputInfoList &Inputs,
  8627. const ArgList &Args,
  8628. const char *LinkingOutput) const {
  8629. const auto &TC =
  8630. static_cast<const toolchains::MyriadToolChain &>(getToolChain());
  8631. const llvm::Triple &T = TC.getTriple();
  8632. ArgStringList CmdArgs;
  8633. bool UseStartfiles = !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
  8634. bool UseDefaultLibs =
  8635. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
  8636. if (T.getArch() == llvm::Triple::sparc)
  8637. CmdArgs.push_back("-EB");
  8638. else // SHAVE assumes little-endian, and sparcel is expressly so.
  8639. CmdArgs.push_back("-EL");
  8640. // The remaining logic is mostly like gnutools::Linker::ConstructJob,
  8641. // but we never pass through a --sysroot option and various other bits.
  8642. // For example, there are no sanitizers (yet) nor gold linker.
  8643. // Eat some arguments that may be present but have no effect.
  8644. Args.ClaimAllArgs(options::OPT_g_Group);
  8645. Args.ClaimAllArgs(options::OPT_w);
  8646. Args.ClaimAllArgs(options::OPT_static_libgcc);
  8647. if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
  8648. CmdArgs.push_back("-s");
  8649. CmdArgs.push_back("-o");
  8650. CmdArgs.push_back(Output.getFilename());
  8651. if (UseStartfiles) {
  8652. // If you want startfiles, it means you want the builtin crti and crtbegin,
  8653. // but not crt0. Myriad link commands provide their own crt0.o as needed.
  8654. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
  8655. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  8656. }
  8657. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  8658. options::OPT_e, options::OPT_s, options::OPT_t,
  8659. options::OPT_Z_Flag, options::OPT_r});
  8660. TC.AddFilePathLibArgs(Args, CmdArgs);
  8661. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8662. if (UseDefaultLibs) {
  8663. if (C.getDriver().CCCIsCXX())
  8664. CmdArgs.push_back("-lstdc++");
  8665. if (T.getOS() == llvm::Triple::RTEMS) {
  8666. CmdArgs.push_back("--start-group");
  8667. CmdArgs.push_back("-lc");
  8668. // You must provide your own "-L" option to enable finding these.
  8669. CmdArgs.push_back("-lrtemscpu");
  8670. CmdArgs.push_back("-lrtemsbsp");
  8671. CmdArgs.push_back("--end-group");
  8672. } else {
  8673. CmdArgs.push_back("-lc");
  8674. }
  8675. CmdArgs.push_back("-lgcc");
  8676. }
  8677. if (UseStartfiles) {
  8678. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  8679. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
  8680. }
  8681. std::string Exec =
  8682. Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
  8683. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8684. CmdArgs, Inputs));
  8685. }
  8686. void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
  8687. const InputInfo &Output,
  8688. const InputInfoList &Inputs,
  8689. const ArgList &Args,
  8690. const char *LinkingOutput) const {
  8691. claimNoWarnArgs(Args);
  8692. ArgStringList CmdArgs;
  8693. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8694. CmdArgs.push_back("-o");
  8695. CmdArgs.push_back(Output.getFilename());
  8696. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  8697. const InputInfo &Input = Inputs[0];
  8698. assert(Input.isFilename() && "Invalid input.");
  8699. CmdArgs.push_back(Input.getFilename());
  8700. const char *Exec =
  8701. Args.MakeArgString(getToolChain().GetProgramPath("ps4-as"));
  8702. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8703. }
  8704. static void AddPS4ProfileRT(const ToolChain &TC, const ArgList &Args,
  8705. ArgStringList &CmdArgs) {
  8706. if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  8707. false) ||
  8708. Args.hasArg(options::OPT_fprofile_generate) ||
  8709. Args.hasArg(options::OPT_fprofile_instr_generate) ||
  8710. Args.hasArg(options::OPT_fcreate_profile) ||
  8711. Args.hasArg(options::OPT_coverage)))
  8712. return;
  8713. assert(TC.getTriple().isPS4CPU() &&
  8714. "Profiling libraries are only implemented for the PS4 CPU");
  8715. CmdArgs.push_back("-lclang_rt.profile-x86_64");
  8716. }
  8717. static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
  8718. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  8719. if (SanArgs.needsUbsanRt()) {
  8720. CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
  8721. }
  8722. if (SanArgs.needsAsanRt()) {
  8723. CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
  8724. }
  8725. }
  8726. static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
  8727. const JobAction &JA, const InputInfo &Output,
  8728. const InputInfoList &Inputs,
  8729. const ArgList &Args,
  8730. const char *LinkingOutput) {
  8731. const toolchains::FreeBSD &ToolChain =
  8732. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  8733. const Driver &D = ToolChain.getDriver();
  8734. ArgStringList CmdArgs;
  8735. // Silence warning for "clang -g foo.o -o foo"
  8736. Args.ClaimAllArgs(options::OPT_g_Group);
  8737. // and "clang -emit-llvm foo.o -o foo"
  8738. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8739. // and for "clang -w foo.o -o foo". Other warning options are already
  8740. // handled somewhere else.
  8741. Args.ClaimAllArgs(options::OPT_w);
  8742. if (!D.SysRoot.empty())
  8743. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8744. if (Args.hasArg(options::OPT_pie))
  8745. CmdArgs.push_back("-pie");
  8746. if (Args.hasArg(options::OPT_rdynamic))
  8747. CmdArgs.push_back("-export-dynamic");
  8748. if (Args.hasArg(options::OPT_shared))
  8749. CmdArgs.push_back("--oformat=so");
  8750. if (Output.isFilename()) {
  8751. CmdArgs.push_back("-o");
  8752. CmdArgs.push_back(Output.getFilename());
  8753. } else {
  8754. assert(Output.isNothing() && "Invalid output.");
  8755. }
  8756. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  8757. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8758. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  8759. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8760. Args.AddAllArgs(CmdArgs, options::OPT_s);
  8761. Args.AddAllArgs(CmdArgs, options::OPT_t);
  8762. Args.AddAllArgs(CmdArgs, options::OPT_r);
  8763. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  8764. CmdArgs.push_back("--no-demangle");
  8765. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  8766. if (Args.hasArg(options::OPT_pthread)) {
  8767. CmdArgs.push_back("-lpthread");
  8768. }
  8769. AddPS4ProfileRT(ToolChain, Args, CmdArgs);
  8770. const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
  8771. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  8772. }
  8773. static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
  8774. const JobAction &JA, const InputInfo &Output,
  8775. const InputInfoList &Inputs,
  8776. const ArgList &Args,
  8777. const char *LinkingOutput) {
  8778. const toolchains::FreeBSD &ToolChain =
  8779. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  8780. const Driver &D = ToolChain.getDriver();
  8781. ArgStringList CmdArgs;
  8782. // Silence warning for "clang -g foo.o -o foo"
  8783. Args.ClaimAllArgs(options::OPT_g_Group);
  8784. // and "clang -emit-llvm foo.o -o foo"
  8785. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8786. // and for "clang -w foo.o -o foo". Other warning options are already
  8787. // handled somewhere else.
  8788. Args.ClaimAllArgs(options::OPT_w);
  8789. if (!D.SysRoot.empty())
  8790. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8791. if (Args.hasArg(options::OPT_pie))
  8792. CmdArgs.push_back("-pie");
  8793. if (Args.hasArg(options::OPT_static)) {
  8794. CmdArgs.push_back("-Bstatic");
  8795. } else {
  8796. if (Args.hasArg(options::OPT_rdynamic))
  8797. CmdArgs.push_back("-export-dynamic");
  8798. CmdArgs.push_back("--eh-frame-hdr");
  8799. if (Args.hasArg(options::OPT_shared)) {
  8800. CmdArgs.push_back("-Bshareable");
  8801. } else {
  8802. CmdArgs.push_back("-dynamic-linker");
  8803. CmdArgs.push_back("/libexec/ld-elf.so.1");
  8804. }
  8805. CmdArgs.push_back("--enable-new-dtags");
  8806. }
  8807. if (Output.isFilename()) {
  8808. CmdArgs.push_back("-o");
  8809. CmdArgs.push_back(Output.getFilename());
  8810. } else {
  8811. assert(Output.isNothing() && "Invalid output.");
  8812. }
  8813. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  8814. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8815. const char *crt1 = nullptr;
  8816. if (!Args.hasArg(options::OPT_shared)) {
  8817. if (Args.hasArg(options::OPT_pg))
  8818. crt1 = "gcrt1.o";
  8819. else if (Args.hasArg(options::OPT_pie))
  8820. crt1 = "Scrt1.o";
  8821. else
  8822. crt1 = "crt1.o";
  8823. }
  8824. if (crt1)
  8825. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  8826. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  8827. const char *crtbegin = nullptr;
  8828. if (Args.hasArg(options::OPT_static))
  8829. crtbegin = "crtbeginT.o";
  8830. else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8831. crtbegin = "crtbeginS.o";
  8832. else
  8833. crtbegin = "crtbegin.o";
  8834. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  8835. }
  8836. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8837. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  8838. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  8839. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8840. Args.AddAllArgs(CmdArgs, options::OPT_s);
  8841. Args.AddAllArgs(CmdArgs, options::OPT_t);
  8842. Args.AddAllArgs(CmdArgs, options::OPT_r);
  8843. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  8844. CmdArgs.push_back("--no-demangle");
  8845. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  8846. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8847. // For PS4, we always want to pass libm, libstdc++ and libkernel
  8848. // libraries for both C and C++ compilations.
  8849. CmdArgs.push_back("-lkernel");
  8850. if (D.CCCIsCXX()) {
  8851. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  8852. if (Args.hasArg(options::OPT_pg))
  8853. CmdArgs.push_back("-lm_p");
  8854. else
  8855. CmdArgs.push_back("-lm");
  8856. }
  8857. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  8858. // the default system libraries. Just mimic this for now.
  8859. if (Args.hasArg(options::OPT_pg))
  8860. CmdArgs.push_back("-lgcc_p");
  8861. else
  8862. CmdArgs.push_back("-lcompiler_rt");
  8863. if (Args.hasArg(options::OPT_static)) {
  8864. CmdArgs.push_back("-lstdc++");
  8865. } else if (Args.hasArg(options::OPT_pg)) {
  8866. CmdArgs.push_back("-lgcc_eh_p");
  8867. } else {
  8868. CmdArgs.push_back("--as-needed");
  8869. CmdArgs.push_back("-lstdc++");
  8870. CmdArgs.push_back("--no-as-needed");
  8871. }
  8872. if (Args.hasArg(options::OPT_pthread)) {
  8873. if (Args.hasArg(options::OPT_pg))
  8874. CmdArgs.push_back("-lpthread_p");
  8875. else
  8876. CmdArgs.push_back("-lpthread");
  8877. }
  8878. if (Args.hasArg(options::OPT_pg)) {
  8879. if (Args.hasArg(options::OPT_shared))
  8880. CmdArgs.push_back("-lc");
  8881. else {
  8882. if (Args.hasArg(options::OPT_static)) {
  8883. CmdArgs.push_back("--start-group");
  8884. CmdArgs.push_back("-lc_p");
  8885. CmdArgs.push_back("-lpthread_p");
  8886. CmdArgs.push_back("--end-group");
  8887. } else {
  8888. CmdArgs.push_back("-lc_p");
  8889. }
  8890. }
  8891. CmdArgs.push_back("-lgcc_p");
  8892. } else {
  8893. if (Args.hasArg(options::OPT_static)) {
  8894. CmdArgs.push_back("--start-group");
  8895. CmdArgs.push_back("-lc");
  8896. CmdArgs.push_back("-lpthread");
  8897. CmdArgs.push_back("--end-group");
  8898. } else {
  8899. CmdArgs.push_back("-lc");
  8900. }
  8901. CmdArgs.push_back("-lcompiler_rt");
  8902. }
  8903. if (Args.hasArg(options::OPT_static)) {
  8904. CmdArgs.push_back("-lstdc++");
  8905. } else if (Args.hasArg(options::OPT_pg)) {
  8906. CmdArgs.push_back("-lgcc_eh_p");
  8907. } else {
  8908. CmdArgs.push_back("--as-needed");
  8909. CmdArgs.push_back("-lstdc++");
  8910. CmdArgs.push_back("--no-as-needed");
  8911. }
  8912. }
  8913. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8914. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8915. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  8916. else
  8917. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  8918. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  8919. }
  8920. AddPS4ProfileRT(ToolChain, Args, CmdArgs);
  8921. const char *Exec =
  8922. #ifdef LLVM_ON_WIN32
  8923. Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld.gold.exe"));
  8924. #else
  8925. Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
  8926. #endif
  8927. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  8928. }
  8929. void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
  8930. const InputInfo &Output,
  8931. const InputInfoList &Inputs,
  8932. const ArgList &Args,
  8933. const char *LinkingOutput) const {
  8934. const toolchains::FreeBSD &ToolChain =
  8935. static_cast<const toolchains::FreeBSD &>(getToolChain());
  8936. const Driver &D = ToolChain.getDriver();
  8937. bool PS4Linker;
  8938. StringRef LinkerOptName;
  8939. if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
  8940. LinkerOptName = A->getValue();
  8941. if (LinkerOptName != "ps4" && LinkerOptName != "gold")
  8942. D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
  8943. }
  8944. if (LinkerOptName == "gold")
  8945. PS4Linker = false;
  8946. else if (LinkerOptName == "ps4")
  8947. PS4Linker = true;
  8948. else
  8949. PS4Linker = !Args.hasArg(options::OPT_shared);
  8950. if (PS4Linker)
  8951. ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  8952. else
  8953. ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  8954. }