Tools.cpp 428 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761
  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/ScopedPrinter.h"
  44. #include "llvm/Support/TargetParser.h"
  45. #ifdef LLVM_ON_UNIX
  46. #include <unistd.h> // For getuid().
  47. #endif
  48. using namespace clang::driver;
  49. using namespace clang::driver::tools;
  50. using namespace clang;
  51. using namespace llvm::opt;
  52. static void handleTargetFeaturesGroup(const ArgList &Args,
  53. std::vector<StringRef> &Features,
  54. OptSpecifier Group) {
  55. for (const Arg *A : Args.filtered(Group)) {
  56. StringRef Name = A->getOption().getName();
  57. A->claim();
  58. // Skip over "-m".
  59. assert(Name.startswith("m") && "Invalid feature name.");
  60. Name = Name.substr(1);
  61. bool IsNegative = Name.startswith("no-");
  62. if (IsNegative)
  63. Name = Name.substr(3);
  64. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  65. }
  66. }
  67. static const char *getSparcAsmModeForCPU(StringRef Name,
  68. const llvm::Triple &Triple) {
  69. if (Triple.getArch() == llvm::Triple::sparcv9) {
  70. return llvm::StringSwitch<const char *>(Name)
  71. .Case("niagara", "-Av9b")
  72. .Case("niagara2", "-Av9b")
  73. .Case("niagara3", "-Av9d")
  74. .Case("niagara4", "-Av9d")
  75. .Default("-Av9");
  76. } else {
  77. return llvm::StringSwitch<const char *>(Name)
  78. .Case("v8", "-Av8")
  79. .Case("supersparc", "-Av8")
  80. .Case("sparclite", "-Asparclite")
  81. .Case("f934", "-Asparclite")
  82. .Case("hypersparc", "-Av8")
  83. .Case("sparclite86x", "-Asparclite")
  84. .Case("sparclet", "-Asparclet")
  85. .Case("tsc701", "-Asparclet")
  86. .Case("v9", "-Av8plus")
  87. .Case("ultrasparc", "-Av8plus")
  88. .Case("ultrasparc3", "-Av8plus")
  89. .Case("niagara", "-Av8plusb")
  90. .Case("niagara2", "-Av8plusb")
  91. .Case("niagara3", "-Av8plusd")
  92. .Case("niagara4", "-Av8plusd")
  93. .Case("leon2", "-Av8")
  94. .Case("at697e", "-Av8")
  95. .Case("at697f", "-Av8")
  96. .Case("leon3", "-Av8")
  97. .Case("ut699", "-Av8")
  98. .Case("gr712rc", "-Av8")
  99. .Case("leon4", "-Av8")
  100. .Case("gr740", "-Av8")
  101. .Default("-Av8");
  102. }
  103. }
  104. static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
  105. if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
  106. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
  107. !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
  108. D.Diag(diag::err_drv_argument_only_allowed_with)
  109. << A->getBaseArg().getAsString(Args)
  110. << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
  111. }
  112. }
  113. }
  114. static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
  115. // In gcc, only ARM checks this, but it seems reasonable to check universally.
  116. if (Args.hasArg(options::OPT_static))
  117. if (const Arg *A =
  118. Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
  119. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  120. << "-static";
  121. }
  122. // Add backslashes to escape spaces and other backslashes.
  123. // This is used for the space-separated argument list specified with
  124. // the -dwarf-debug-flags option.
  125. static void EscapeSpacesAndBackslashes(const char *Arg,
  126. SmallVectorImpl<char> &Res) {
  127. for (; *Arg; ++Arg) {
  128. switch (*Arg) {
  129. default:
  130. break;
  131. case ' ':
  132. case '\\':
  133. Res.push_back('\\');
  134. break;
  135. }
  136. Res.push_back(*Arg);
  137. }
  138. }
  139. // Quote target names for inclusion in GNU Make dependency files.
  140. // Only the characters '$', '#', ' ', '\t' are quoted.
  141. static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
  142. for (unsigned i = 0, e = Target.size(); i != e; ++i) {
  143. switch (Target[i]) {
  144. case ' ':
  145. case '\t':
  146. // Escape the preceding backslashes
  147. for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
  148. Res.push_back('\\');
  149. // Escape the space/tab
  150. Res.push_back('\\');
  151. break;
  152. case '$':
  153. Res.push_back('$');
  154. break;
  155. case '#':
  156. Res.push_back('\\');
  157. break;
  158. default:
  159. break;
  160. }
  161. Res.push_back(Target[i]);
  162. }
  163. }
  164. static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
  165. const char *ArgName, const char *EnvVar) {
  166. const char *DirList = ::getenv(EnvVar);
  167. bool CombinedArg = false;
  168. if (!DirList)
  169. return; // Nothing to do.
  170. StringRef Name(ArgName);
  171. if (Name.equals("-I") || Name.equals("-L"))
  172. CombinedArg = true;
  173. StringRef Dirs(DirList);
  174. if (Dirs.empty()) // Empty string should not add '.'.
  175. return;
  176. StringRef::size_type Delim;
  177. while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
  178. if (Delim == 0) { // Leading colon.
  179. if (CombinedArg) {
  180. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  181. } else {
  182. CmdArgs.push_back(ArgName);
  183. CmdArgs.push_back(".");
  184. }
  185. } else {
  186. if (CombinedArg) {
  187. CmdArgs.push_back(
  188. Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
  189. } else {
  190. CmdArgs.push_back(ArgName);
  191. CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
  192. }
  193. }
  194. Dirs = Dirs.substr(Delim + 1);
  195. }
  196. if (Dirs.empty()) { // Trailing colon.
  197. if (CombinedArg) {
  198. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  199. } else {
  200. CmdArgs.push_back(ArgName);
  201. CmdArgs.push_back(".");
  202. }
  203. } else { // Add the last path.
  204. if (CombinedArg) {
  205. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
  206. } else {
  207. CmdArgs.push_back(ArgName);
  208. CmdArgs.push_back(Args.MakeArgString(Dirs));
  209. }
  210. }
  211. }
  212. static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
  213. const ArgList &Args, ArgStringList &CmdArgs) {
  214. const Driver &D = TC.getDriver();
  215. // Add extra linker input arguments which are not treated as inputs
  216. // (constructed via -Xarch_).
  217. Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
  218. for (const auto &II : Inputs) {
  219. if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
  220. // Don't try to pass LLVM inputs unless we have native support.
  221. D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
  222. // Add filenames immediately.
  223. if (II.isFilename()) {
  224. CmdArgs.push_back(II.getFilename());
  225. continue;
  226. }
  227. // Otherwise, this is a linker input argument.
  228. const Arg &A = II.getInputArg();
  229. // Handle reserved library options.
  230. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
  231. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  232. else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
  233. TC.AddCCKextLibArgs(Args, CmdArgs);
  234. else if (A.getOption().matches(options::OPT_z)) {
  235. // Pass -z prefix for gcc linker compatibility.
  236. A.claim();
  237. A.render(Args, CmdArgs);
  238. } else {
  239. A.renderAsInput(Args, CmdArgs);
  240. }
  241. }
  242. // LIBRARY_PATH - included following the user specified library paths.
  243. // and only supported on native toolchains.
  244. if (!TC.isCrossCompiling())
  245. addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
  246. }
  247. /// \brief Determine whether Objective-C automated reference counting is
  248. /// enabled.
  249. static bool isObjCAutoRefCount(const ArgList &Args) {
  250. return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
  251. }
  252. /// \brief Determine whether we are linking the ObjC runtime.
  253. static bool isObjCRuntimeLinked(const ArgList &Args) {
  254. if (isObjCAutoRefCount(Args)) {
  255. Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
  256. return true;
  257. }
  258. return Args.hasArg(options::OPT_fobjc_link_runtime);
  259. }
  260. static bool forwardToGCC(const Option &O) {
  261. // Don't forward inputs from the original command line. They are added from
  262. // InputInfoList.
  263. return O.getKind() != Option::InputClass &&
  264. !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
  265. }
  266. /// Apply \a Work on the current tool chain \a RegularToolChain and any other
  267. /// offloading tool chain that is associated with the current action \a JA.
  268. static void
  269. forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
  270. const ToolChain &RegularToolChain,
  271. llvm::function_ref<void(const ToolChain &)> Work) {
  272. // Apply Work on the current/regular tool chain.
  273. Work(RegularToolChain);
  274. // Apply Work on all the offloading tool chains associated with the current
  275. // action.
  276. if (JA.isHostOffloading(Action::OFK_Cuda))
  277. Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
  278. else if (JA.isDeviceOffloading(Action::OFK_Cuda))
  279. Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
  280. //
  281. // TODO: Add support for other offloading programming models here.
  282. //
  283. }
  284. void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
  285. const Driver &D, const ArgList &Args,
  286. ArgStringList &CmdArgs,
  287. const InputInfo &Output,
  288. const InputInfoList &Inputs) const {
  289. Arg *A;
  290. const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
  291. CheckPreprocessingOptions(D, Args);
  292. Args.AddLastArg(CmdArgs, options::OPT_C);
  293. Args.AddLastArg(CmdArgs, options::OPT_CC);
  294. // Handle dependency file generation.
  295. if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
  296. (A = Args.getLastArg(options::OPT_MD)) ||
  297. (A = Args.getLastArg(options::OPT_MMD))) {
  298. // Determine the output location.
  299. const char *DepFile;
  300. if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
  301. DepFile = MF->getValue();
  302. C.addFailureResultFile(DepFile, &JA);
  303. } else if (Output.getType() == types::TY_Dependencies) {
  304. DepFile = Output.getFilename();
  305. } else if (A->getOption().matches(options::OPT_M) ||
  306. A->getOption().matches(options::OPT_MM)) {
  307. DepFile = "-";
  308. } else {
  309. DepFile = getDependencyFileName(Args, Inputs);
  310. C.addFailureResultFile(DepFile, &JA);
  311. }
  312. CmdArgs.push_back("-dependency-file");
  313. CmdArgs.push_back(DepFile);
  314. // Add a default target if one wasn't specified.
  315. if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
  316. const char *DepTarget;
  317. // If user provided -o, that is the dependency target, except
  318. // when we are only generating a dependency file.
  319. Arg *OutputOpt = Args.getLastArg(options::OPT_o);
  320. if (OutputOpt && Output.getType() != types::TY_Dependencies) {
  321. DepTarget = OutputOpt->getValue();
  322. } else {
  323. // Otherwise derive from the base input.
  324. //
  325. // FIXME: This should use the computed output file location.
  326. SmallString<128> P(Inputs[0].getBaseInput());
  327. llvm::sys::path::replace_extension(P, "o");
  328. DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
  329. }
  330. CmdArgs.push_back("-MT");
  331. SmallString<128> Quoted;
  332. QuoteTarget(DepTarget, Quoted);
  333. CmdArgs.push_back(Args.MakeArgString(Quoted));
  334. }
  335. if (A->getOption().matches(options::OPT_M) ||
  336. A->getOption().matches(options::OPT_MD))
  337. CmdArgs.push_back("-sys-header-deps");
  338. if ((isa<PrecompileJobAction>(JA) &&
  339. !Args.hasArg(options::OPT_fno_module_file_deps)) ||
  340. Args.hasArg(options::OPT_fmodule_file_deps))
  341. CmdArgs.push_back("-module-file-deps");
  342. }
  343. if (Args.hasArg(options::OPT_MG)) {
  344. if (!A || A->getOption().matches(options::OPT_MD) ||
  345. A->getOption().matches(options::OPT_MMD))
  346. D.Diag(diag::err_drv_mg_requires_m_or_mm);
  347. CmdArgs.push_back("-MG");
  348. }
  349. Args.AddLastArg(CmdArgs, options::OPT_MP);
  350. Args.AddLastArg(CmdArgs, options::OPT_MV);
  351. // Convert all -MQ <target> args to -MT <quoted target>
  352. for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
  353. A->claim();
  354. if (A->getOption().matches(options::OPT_MQ)) {
  355. CmdArgs.push_back("-MT");
  356. SmallString<128> Quoted;
  357. QuoteTarget(A->getValue(), Quoted);
  358. CmdArgs.push_back(Args.MakeArgString(Quoted));
  359. // -MT flag - no change
  360. } else {
  361. A->render(Args, CmdArgs);
  362. }
  363. }
  364. // Add offload include arguments specific for CUDA. This must happen before
  365. // we -I or -include anything else, because we must pick up the CUDA headers
  366. // from the particular CUDA installation, rather than from e.g.
  367. // /usr/local/include.
  368. if (JA.isOffloading(Action::OFK_Cuda))
  369. getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
  370. // Add -i* options, and automatically translate to
  371. // -include-pch/-include-pth for transparent PCH support. It's
  372. // wonky, but we include looking for .gch so we can support seamless
  373. // replacement into a build system already set up to be generating
  374. // .gch files.
  375. int YcIndex = -1, YuIndex = -1;
  376. {
  377. int AI = -1;
  378. const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
  379. const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
  380. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  381. // Walk the whole i_Group and skip non "-include" flags so that the index
  382. // here matches the index in the next loop below.
  383. ++AI;
  384. if (!A->getOption().matches(options::OPT_include))
  385. continue;
  386. if (YcArg && strcmp(A->getValue(), YcArg->getValue()) == 0)
  387. YcIndex = AI;
  388. if (YuArg && strcmp(A->getValue(), YuArg->getValue()) == 0)
  389. YuIndex = AI;
  390. }
  391. }
  392. if (isa<PrecompileJobAction>(JA) && YcIndex != -1) {
  393. Driver::InputList Inputs;
  394. D.BuildInputs(getToolChain(), C.getArgs(), Inputs);
  395. assert(Inputs.size() == 1 && "Need one input when building pch");
  396. CmdArgs.push_back(Args.MakeArgString(Twine("-find-pch-source=") +
  397. Inputs[0].second->getValue()));
  398. }
  399. bool RenderedImplicitInclude = false;
  400. int AI = -1;
  401. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  402. ++AI;
  403. if (getToolChain().getDriver().IsCLMode() &&
  404. A->getOption().matches(options::OPT_include)) {
  405. // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
  406. // include is compiled into foo.h, and everything after goes into
  407. // the .obj file. /Yufoo.h means that all includes prior to and including
  408. // foo.h are completely skipped and replaced with a use of the pch file
  409. // for foo.h. (Each flag can have at most one value, multiple /Yc flags
  410. // just mean that the last one wins.) If /Yc and /Yu are both present
  411. // and refer to the same file, /Yc wins.
  412. // Note that OPT__SLASH_FI gets mapped to OPT_include.
  413. // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
  414. // cl.exe seems to support both flags with different values, but that
  415. // seems strange (which flag does /Fp now refer to?), so don't implement
  416. // that until someone needs it.
  417. int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
  418. if (PchIndex != -1) {
  419. if (isa<PrecompileJobAction>(JA)) {
  420. // When building the pch, skip all includes after the pch.
  421. assert(YcIndex != -1 && PchIndex == YcIndex);
  422. if (AI >= YcIndex)
  423. continue;
  424. } else {
  425. // When using the pch, skip all includes prior to the pch.
  426. if (AI < PchIndex) {
  427. A->claim();
  428. continue;
  429. }
  430. if (AI == PchIndex) {
  431. A->claim();
  432. CmdArgs.push_back("-include-pch");
  433. CmdArgs.push_back(
  434. Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
  435. continue;
  436. }
  437. }
  438. }
  439. } else if (A->getOption().matches(options::OPT_include)) {
  440. // Handling of gcc-style gch precompiled headers.
  441. bool IsFirstImplicitInclude = !RenderedImplicitInclude;
  442. RenderedImplicitInclude = true;
  443. // Use PCH if the user requested it.
  444. bool UsePCH = D.CCCUsePCH;
  445. bool FoundPTH = false;
  446. bool FoundPCH = false;
  447. SmallString<128> P(A->getValue());
  448. // We want the files to have a name like foo.h.pch. Add a dummy extension
  449. // so that replace_extension does the right thing.
  450. P += ".dummy";
  451. if (UsePCH) {
  452. llvm::sys::path::replace_extension(P, "pch");
  453. if (llvm::sys::fs::exists(P))
  454. FoundPCH = true;
  455. }
  456. if (!FoundPCH) {
  457. llvm::sys::path::replace_extension(P, "pth");
  458. if (llvm::sys::fs::exists(P))
  459. FoundPTH = true;
  460. }
  461. if (!FoundPCH && !FoundPTH) {
  462. llvm::sys::path::replace_extension(P, "gch");
  463. if (llvm::sys::fs::exists(P)) {
  464. FoundPCH = UsePCH;
  465. FoundPTH = !UsePCH;
  466. }
  467. }
  468. if (FoundPCH || FoundPTH) {
  469. if (IsFirstImplicitInclude) {
  470. A->claim();
  471. if (UsePCH)
  472. CmdArgs.push_back("-include-pch");
  473. else
  474. CmdArgs.push_back("-include-pth");
  475. CmdArgs.push_back(Args.MakeArgString(P));
  476. continue;
  477. } else {
  478. // Ignore the PCH if not first on command line and emit warning.
  479. D.Diag(diag::warn_drv_pch_not_first_include) << P
  480. << A->getAsString(Args);
  481. }
  482. }
  483. } else if (A->getOption().matches(options::OPT_isystem_after)) {
  484. // Handling of paths which must come late. These entries are handled by
  485. // the toolchain itself after the resource dir is inserted in the right
  486. // search order.
  487. // Do not claim the argument so that the use of the argument does not
  488. // silently go unnoticed on toolchains which do not honour the option.
  489. continue;
  490. }
  491. // Not translated, render as usual.
  492. A->claim();
  493. A->render(Args, CmdArgs);
  494. }
  495. Args.AddAllArgs(CmdArgs,
  496. {options::OPT_D, options::OPT_U, options::OPT_I_Group,
  497. options::OPT_F, options::OPT_index_header_map});
  498. // Add -Wp, and -Xpreprocessor if using the preprocessor.
  499. // FIXME: There is a very unfortunate problem here, some troubled
  500. // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
  501. // really support that we would have to parse and then translate
  502. // those options. :(
  503. Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
  504. options::OPT_Xpreprocessor);
  505. // -I- is a deprecated GCC feature, reject it.
  506. if (Arg *A = Args.getLastArg(options::OPT_I_))
  507. D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
  508. // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
  509. // -isysroot to the CC1 invocation.
  510. StringRef sysroot = C.getSysRoot();
  511. if (sysroot != "") {
  512. if (!Args.hasArg(options::OPT_isysroot)) {
  513. CmdArgs.push_back("-isysroot");
  514. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  515. }
  516. }
  517. // Parse additional include paths from environment variables.
  518. // FIXME: We should probably sink the logic for handling these from the
  519. // frontend into the driver. It will allow deleting 4 otherwise unused flags.
  520. // CPATH - included following the user specified includes (but prior to
  521. // builtin and standard includes).
  522. addDirectoryList(Args, CmdArgs, "-I", "CPATH");
  523. // C_INCLUDE_PATH - system includes enabled when compiling C.
  524. addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
  525. // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
  526. addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
  527. // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
  528. addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
  529. // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
  530. addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
  531. // While adding the include arguments, we also attempt to retrieve the
  532. // arguments of related offloading toolchains or arguments that are specific
  533. // of an offloading programming model.
  534. // Add C++ include arguments, if needed.
  535. if (types::isCXX(Inputs[0].getType()))
  536. forAllAssociatedToolChains(C, JA, getToolChain(),
  537. [&Args, &CmdArgs](const ToolChain &TC) {
  538. TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  539. });
  540. // Add system include arguments for all targets but IAMCU.
  541. if (!IsIAMCU)
  542. forAllAssociatedToolChains(C, JA, getToolChain(),
  543. [&Args, &CmdArgs](const ToolChain &TC) {
  544. TC.AddClangSystemIncludeArgs(Args, CmdArgs);
  545. });
  546. else {
  547. // For IAMCU add special include arguments.
  548. getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
  549. }
  550. }
  551. // FIXME: Move to target hook.
  552. static bool isSignedCharDefault(const llvm::Triple &Triple) {
  553. switch (Triple.getArch()) {
  554. default:
  555. return true;
  556. case llvm::Triple::aarch64:
  557. case llvm::Triple::aarch64_be:
  558. case llvm::Triple::arm:
  559. case llvm::Triple::armeb:
  560. case llvm::Triple::thumb:
  561. case llvm::Triple::thumbeb:
  562. if (Triple.isOSDarwin() || Triple.isOSWindows())
  563. return true;
  564. return false;
  565. case llvm::Triple::ppc:
  566. case llvm::Triple::ppc64:
  567. if (Triple.isOSDarwin())
  568. return true;
  569. return false;
  570. case llvm::Triple::hexagon:
  571. case llvm::Triple::ppc64le:
  572. case llvm::Triple::systemz:
  573. case llvm::Triple::xcore:
  574. return false;
  575. }
  576. }
  577. static bool isNoCommonDefault(const llvm::Triple &Triple) {
  578. switch (Triple.getArch()) {
  579. default:
  580. return false;
  581. case llvm::Triple::xcore:
  582. case llvm::Triple::wasm32:
  583. case llvm::Triple::wasm64:
  584. return true;
  585. }
  586. }
  587. // ARM tools start.
  588. // Get SubArch (vN).
  589. static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
  590. llvm::StringRef Arch = Triple.getArchName();
  591. return llvm::ARM::parseArchVersion(Arch);
  592. }
  593. // True if M-profile.
  594. static bool isARMMProfile(const llvm::Triple &Triple) {
  595. llvm::StringRef Arch = Triple.getArchName();
  596. unsigned Profile = llvm::ARM::parseArchProfile(Arch);
  597. return Profile == llvm::ARM::PK_M;
  598. }
  599. // Get Arch/CPU from args.
  600. static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
  601. llvm::StringRef &CPU, bool FromAs = false) {
  602. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  603. CPU = A->getValue();
  604. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  605. Arch = A->getValue();
  606. if (!FromAs)
  607. return;
  608. for (const Arg *A :
  609. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  610. StringRef Value = A->getValue();
  611. if (Value.startswith("-mcpu="))
  612. CPU = Value.substr(6);
  613. if (Value.startswith("-march="))
  614. Arch = Value.substr(7);
  615. }
  616. }
  617. // Handle -mhwdiv=.
  618. // FIXME: Use ARMTargetParser.
  619. static void getARMHWDivFeatures(const Driver &D, const Arg *A,
  620. const ArgList &Args, StringRef HWDiv,
  621. std::vector<StringRef> &Features) {
  622. unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
  623. if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
  624. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  625. }
  626. // Handle -mfpu=.
  627. static void getARMFPUFeatures(const Driver &D, const Arg *A,
  628. const ArgList &Args, StringRef FPU,
  629. std::vector<StringRef> &Features) {
  630. unsigned FPUID = llvm::ARM::parseFPU(FPU);
  631. if (!llvm::ARM::getFPUFeatures(FPUID, Features))
  632. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  633. }
  634. // Decode ARM features from string like +[no]featureA+[no]featureB+...
  635. static bool DecodeARMFeatures(const Driver &D, StringRef text,
  636. std::vector<StringRef> &Features) {
  637. SmallVector<StringRef, 8> Split;
  638. text.split(Split, StringRef("+"), -1, false);
  639. for (StringRef Feature : Split) {
  640. StringRef FeatureName = llvm::ARM::getArchExtFeature(Feature);
  641. if (!FeatureName.empty())
  642. Features.push_back(FeatureName);
  643. else
  644. return false;
  645. }
  646. return true;
  647. }
  648. // Check if -march is valid by checking if it can be canonicalised and parsed.
  649. // getARMArch is used here instead of just checking the -march value in order
  650. // to handle -march=native correctly.
  651. static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
  652. llvm::StringRef ArchName,
  653. std::vector<StringRef> &Features,
  654. const llvm::Triple &Triple) {
  655. std::pair<StringRef, StringRef> Split = ArchName.split("+");
  656. std::string MArch = arm::getARMArch(ArchName, Triple);
  657. if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
  658. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  659. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  660. }
  661. // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
  662. static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
  663. llvm::StringRef CPUName, llvm::StringRef ArchName,
  664. std::vector<StringRef> &Features,
  665. const llvm::Triple &Triple) {
  666. std::pair<StringRef, StringRef> Split = CPUName.split("+");
  667. std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
  668. if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
  669. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  670. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  671. }
  672. static bool useAAPCSForMachO(const llvm::Triple &T) {
  673. // The backend is hardwired to assume AAPCS for M-class processors, ensure
  674. // the frontend matches that.
  675. return T.getEnvironment() == llvm::Triple::EABI ||
  676. T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
  677. }
  678. // Select the float ABI as determined by -msoft-float, -mhard-float, and
  679. // -mfloat-abi=.
  680. arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
  681. const Driver &D = TC.getDriver();
  682. const llvm::Triple &Triple = TC.getEffectiveTriple();
  683. auto SubArch = getARMSubArchVersionNumber(Triple);
  684. arm::FloatABI ABI = FloatABI::Invalid;
  685. if (Arg *A =
  686. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  687. options::OPT_mfloat_abi_EQ)) {
  688. if (A->getOption().matches(options::OPT_msoft_float)) {
  689. ABI = FloatABI::Soft;
  690. } else if (A->getOption().matches(options::OPT_mhard_float)) {
  691. ABI = FloatABI::Hard;
  692. } else {
  693. ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
  694. .Case("soft", FloatABI::Soft)
  695. .Case("softfp", FloatABI::SoftFP)
  696. .Case("hard", FloatABI::Hard)
  697. .Default(FloatABI::Invalid);
  698. if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  699. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  700. ABI = FloatABI::Soft;
  701. }
  702. }
  703. // It is incorrect to select hard float ABI on MachO platforms if the ABI is
  704. // "apcs-gnu".
  705. if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
  706. ABI == FloatABI::Hard) {
  707. D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
  708. << Triple.getArchName();
  709. }
  710. }
  711. // If unspecified, choose the default based on the platform.
  712. if (ABI == FloatABI::Invalid) {
  713. switch (Triple.getOS()) {
  714. case llvm::Triple::Darwin:
  715. case llvm::Triple::MacOSX:
  716. case llvm::Triple::IOS:
  717. case llvm::Triple::TvOS: {
  718. // Darwin defaults to "softfp" for v6 and v7.
  719. ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  720. ABI = Triple.isWatchABI() ? FloatABI::Hard : ABI;
  721. break;
  722. }
  723. case llvm::Triple::WatchOS:
  724. ABI = FloatABI::Hard;
  725. break;
  726. // FIXME: this is invalid for WindowsCE
  727. case llvm::Triple::Win32:
  728. ABI = FloatABI::Hard;
  729. break;
  730. case llvm::Triple::FreeBSD:
  731. switch (Triple.getEnvironment()) {
  732. case llvm::Triple::GNUEABIHF:
  733. ABI = FloatABI::Hard;
  734. break;
  735. default:
  736. // FreeBSD defaults to soft float
  737. ABI = FloatABI::Soft;
  738. break;
  739. }
  740. break;
  741. default:
  742. switch (Triple.getEnvironment()) {
  743. case llvm::Triple::GNUEABIHF:
  744. case llvm::Triple::MuslEABIHF:
  745. case llvm::Triple::EABIHF:
  746. ABI = FloatABI::Hard;
  747. break;
  748. case llvm::Triple::GNUEABI:
  749. case llvm::Triple::MuslEABI:
  750. case llvm::Triple::EABI:
  751. // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
  752. ABI = FloatABI::SoftFP;
  753. break;
  754. case llvm::Triple::Android:
  755. ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  756. break;
  757. default:
  758. // Assume "soft", but warn the user we are guessing.
  759. if (Triple.isOSBinFormatMachO() &&
  760. Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
  761. ABI = FloatABI::Hard;
  762. else
  763. ABI = FloatABI::Soft;
  764. if (Triple.getOS() != llvm::Triple::UnknownOS ||
  765. !Triple.isOSBinFormatMachO())
  766. D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
  767. break;
  768. }
  769. }
  770. }
  771. assert(ABI != FloatABI::Invalid && "must select an ABI");
  772. return ABI;
  773. }
  774. static void getARMTargetFeatures(const ToolChain &TC,
  775. const llvm::Triple &Triple,
  776. const ArgList &Args,
  777. std::vector<StringRef> &Features,
  778. bool ForAS) {
  779. const Driver &D = TC.getDriver();
  780. bool KernelOrKext =
  781. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  782. arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
  783. const Arg *WaCPU = nullptr, *WaFPU = nullptr;
  784. const Arg *WaHDiv = nullptr, *WaArch = nullptr;
  785. if (!ForAS) {
  786. // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
  787. // yet (it uses the -mfloat-abi and -msoft-float options), and it is
  788. // stripped out by the ARM target. We should probably pass this a new
  789. // -target-option, which is handled by the -cc1/-cc1as invocation.
  790. //
  791. // FIXME2: For consistency, it would be ideal if we set up the target
  792. // machine state the same when using the frontend or the assembler. We don't
  793. // currently do that for the assembler, we pass the options directly to the
  794. // backend and never even instantiate the frontend TargetInfo. If we did,
  795. // and used its handleTargetFeatures hook, then we could ensure the
  796. // assembler and the frontend behave the same.
  797. // Use software floating point operations?
  798. if (ABI == arm::FloatABI::Soft)
  799. Features.push_back("+soft-float");
  800. // Use software floating point argument passing?
  801. if (ABI != arm::FloatABI::Hard)
  802. Features.push_back("+soft-float-abi");
  803. } else {
  804. // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
  805. // to the assembler correctly.
  806. for (const Arg *A :
  807. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  808. StringRef Value = A->getValue();
  809. if (Value.startswith("-mfpu=")) {
  810. WaFPU = A;
  811. } else if (Value.startswith("-mcpu=")) {
  812. WaCPU = A;
  813. } else if (Value.startswith("-mhwdiv=")) {
  814. WaHDiv = A;
  815. } else if (Value.startswith("-march=")) {
  816. WaArch = A;
  817. }
  818. }
  819. }
  820. // Check -march. ClangAs gives preference to -Wa,-march=.
  821. const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
  822. StringRef ArchName;
  823. if (WaArch) {
  824. if (ArchArg)
  825. D.Diag(clang::diag::warn_drv_unused_argument)
  826. << ArchArg->getAsString(Args);
  827. ArchName = StringRef(WaArch->getValue()).substr(7);
  828. checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
  829. // FIXME: Set Arch.
  830. D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
  831. } else if (ArchArg) {
  832. ArchName = ArchArg->getValue();
  833. checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
  834. }
  835. // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
  836. const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  837. StringRef CPUName;
  838. if (WaCPU) {
  839. if (CPUArg)
  840. D.Diag(clang::diag::warn_drv_unused_argument)
  841. << CPUArg->getAsString(Args);
  842. CPUName = StringRef(WaCPU->getValue()).substr(6);
  843. checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
  844. } else if (CPUArg) {
  845. CPUName = CPUArg->getValue();
  846. checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
  847. }
  848. // Add CPU features for generic CPUs
  849. if (CPUName == "native") {
  850. llvm::StringMap<bool> HostFeatures;
  851. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  852. for (auto &F : HostFeatures)
  853. Features.push_back(
  854. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  855. }
  856. // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
  857. const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
  858. if (WaFPU) {
  859. if (FPUArg)
  860. D.Diag(clang::diag::warn_drv_unused_argument)
  861. << FPUArg->getAsString(Args);
  862. getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
  863. Features);
  864. } else if (FPUArg) {
  865. getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
  866. }
  867. // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
  868. const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
  869. if (WaHDiv) {
  870. if (HDivArg)
  871. D.Diag(clang::diag::warn_drv_unused_argument)
  872. << HDivArg->getAsString(Args);
  873. getARMHWDivFeatures(D, WaHDiv, Args,
  874. StringRef(WaHDiv->getValue()).substr(8), Features);
  875. } else if (HDivArg)
  876. getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
  877. // Setting -msoft-float effectively disables NEON because of the GCC
  878. // implementation, although the same isn't true of VFP or VFP3.
  879. if (ABI == arm::FloatABI::Soft) {
  880. Features.push_back("-neon");
  881. // Also need to explicitly disable features which imply NEON.
  882. Features.push_back("-crypto");
  883. }
  884. // En/disable crc code generation.
  885. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  886. if (A->getOption().matches(options::OPT_mcrc))
  887. Features.push_back("+crc");
  888. else
  889. Features.push_back("-crc");
  890. }
  891. // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
  892. // neither options are specified, see if we are compiling for kernel/kext and
  893. // decide whether to pass "+long-calls" based on the OS and its version.
  894. if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
  895. options::OPT_mno_long_calls)) {
  896. if (A->getOption().matches(options::OPT_mlong_calls))
  897. Features.push_back("+long-calls");
  898. } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  899. !Triple.isWatchOS()) {
  900. Features.push_back("+long-calls");
  901. }
  902. // Kernel code has more strict alignment requirements.
  903. if (KernelOrKext)
  904. Features.push_back("+strict-align");
  905. else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  906. options::OPT_munaligned_access)) {
  907. if (A->getOption().matches(options::OPT_munaligned_access)) {
  908. // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
  909. if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  910. D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
  911. // v8M Baseline follows on from v6M, so doesn't support unaligned memory
  912. // access either.
  913. else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
  914. D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";
  915. } else
  916. Features.push_back("+strict-align");
  917. } else {
  918. // Assume pre-ARMv6 doesn't support unaligned accesses.
  919. //
  920. // ARMv6 may or may not support unaligned accesses depending on the
  921. // SCTLR.U bit, which is architecture-specific. We assume ARMv6
  922. // Darwin and NetBSD targets support unaligned accesses, and others don't.
  923. //
  924. // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
  925. // which raises an alignment fault on unaligned accesses. Linux
  926. // defaults this bit to 0 and handles it as a system-wide (not
  927. // per-process) setting. It is therefore safe to assume that ARMv7+
  928. // Linux targets support unaligned accesses. The same goes for NaCl.
  929. //
  930. // The above behavior is consistent with GCC.
  931. int VersionNum = getARMSubArchVersionNumber(Triple);
  932. if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
  933. if (VersionNum < 6 ||
  934. Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  935. Features.push_back("+strict-align");
  936. } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
  937. if (VersionNum < 7)
  938. Features.push_back("+strict-align");
  939. } else
  940. Features.push_back("+strict-align");
  941. }
  942. // llvm does not support reserving registers in general. There is support
  943. // for reserving r9 on ARM though (defined as a platform-specific register
  944. // in ARM EABI).
  945. if (Args.hasArg(options::OPT_ffixed_r9))
  946. Features.push_back("+reserve-r9");
  947. // The kext linker doesn't know how to deal with movw/movt.
  948. if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
  949. Features.push_back("+no-movt");
  950. }
  951. void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
  952. ArgStringList &CmdArgs, bool KernelOrKext) const {
  953. // Select the ABI to use.
  954. // FIXME: Support -meabi.
  955. // FIXME: Parts of this are duplicated in the backend, unify this somehow.
  956. const char *ABIName = nullptr;
  957. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  958. ABIName = A->getValue();
  959. } else if (Triple.isOSBinFormatMachO()) {
  960. if (useAAPCSForMachO(Triple)) {
  961. ABIName = "aapcs";
  962. } else if (Triple.isWatchABI()) {
  963. ABIName = "aapcs16";
  964. } else {
  965. ABIName = "apcs-gnu";
  966. }
  967. } else if (Triple.isOSWindows()) {
  968. // FIXME: this is invalid for WindowsCE
  969. ABIName = "aapcs";
  970. } else {
  971. // Select the default based on the platform.
  972. switch (Triple.getEnvironment()) {
  973. case llvm::Triple::Android:
  974. case llvm::Triple::GNUEABI:
  975. case llvm::Triple::GNUEABIHF:
  976. case llvm::Triple::MuslEABI:
  977. case llvm::Triple::MuslEABIHF:
  978. ABIName = "aapcs-linux";
  979. break;
  980. case llvm::Triple::EABIHF:
  981. case llvm::Triple::EABI:
  982. ABIName = "aapcs";
  983. break;
  984. default:
  985. if (Triple.getOS() == llvm::Triple::NetBSD)
  986. ABIName = "apcs-gnu";
  987. else
  988. ABIName = "aapcs";
  989. break;
  990. }
  991. }
  992. CmdArgs.push_back("-target-abi");
  993. CmdArgs.push_back(ABIName);
  994. // Determine floating point ABI from the options & target defaults.
  995. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  996. if (ABI == arm::FloatABI::Soft) {
  997. // Floating point operations and argument passing are soft.
  998. // FIXME: This changes CPP defines, we need -target-soft-float.
  999. CmdArgs.push_back("-msoft-float");
  1000. CmdArgs.push_back("-mfloat-abi");
  1001. CmdArgs.push_back("soft");
  1002. } else if (ABI == arm::FloatABI::SoftFP) {
  1003. // Floating point operations are hard, but argument passing is soft.
  1004. CmdArgs.push_back("-mfloat-abi");
  1005. CmdArgs.push_back("soft");
  1006. } else {
  1007. // Floating point operations and argument passing are hard.
  1008. assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
  1009. CmdArgs.push_back("-mfloat-abi");
  1010. CmdArgs.push_back("hard");
  1011. }
  1012. // Forward the -mglobal-merge option for explicit control over the pass.
  1013. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  1014. options::OPT_mno_global_merge)) {
  1015. CmdArgs.push_back("-backend-option");
  1016. if (A->getOption().matches(options::OPT_mno_global_merge))
  1017. CmdArgs.push_back("-arm-global-merge=false");
  1018. else
  1019. CmdArgs.push_back("-arm-global-merge=true");
  1020. }
  1021. if (!Args.hasFlag(options::OPT_mimplicit_float,
  1022. options::OPT_mno_implicit_float, true))
  1023. CmdArgs.push_back("-no-implicit-float");
  1024. }
  1025. // ARM tools end.
  1026. /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
  1027. /// targeting. Set \p A to the Arg corresponding to the -mcpu or -mtune
  1028. /// arguments if they are provided, or to nullptr otherwise.
  1029. static std::string getAArch64TargetCPU(const ArgList &Args, Arg *&A) {
  1030. std::string CPU;
  1031. // If we have -mtune or -mcpu, use that.
  1032. if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
  1033. CPU = StringRef(A->getValue()).lower();
  1034. } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
  1035. StringRef Mcpu = A->getValue();
  1036. CPU = Mcpu.split("+").first.lower();
  1037. }
  1038. // Handle CPU name is 'native'.
  1039. if (CPU == "native")
  1040. return llvm::sys::getHostCPUName();
  1041. else if (CPU.size())
  1042. return CPU;
  1043. // Make sure we pick "cyclone" if -arch is used.
  1044. // FIXME: Should this be picked by checking the target triple instead?
  1045. if (Args.getLastArg(options::OPT_arch))
  1046. return "cyclone";
  1047. return "generic";
  1048. }
  1049. void Clang::AddAArch64TargetArgs(const ArgList &Args,
  1050. ArgStringList &CmdArgs) const {
  1051. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  1052. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1053. Args.hasArg(options::OPT_mkernel) ||
  1054. Args.hasArg(options::OPT_fapple_kext))
  1055. CmdArgs.push_back("-disable-red-zone");
  1056. if (!Args.hasFlag(options::OPT_mimplicit_float,
  1057. options::OPT_mno_implicit_float, true))
  1058. CmdArgs.push_back("-no-implicit-float");
  1059. const char *ABIName = nullptr;
  1060. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1061. ABIName = A->getValue();
  1062. else if (Triple.isOSDarwin())
  1063. ABIName = "darwinpcs";
  1064. else
  1065. ABIName = "aapcs";
  1066. CmdArgs.push_back("-target-abi");
  1067. CmdArgs.push_back(ABIName);
  1068. if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
  1069. options::OPT_mno_fix_cortex_a53_835769)) {
  1070. CmdArgs.push_back("-backend-option");
  1071. if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
  1072. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  1073. else
  1074. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
  1075. } else if (Triple.isAndroid()) {
  1076. // Enabled A53 errata (835769) workaround by default on android
  1077. CmdArgs.push_back("-backend-option");
  1078. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  1079. }
  1080. // Forward the -mglobal-merge option for explicit control over the pass.
  1081. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  1082. options::OPT_mno_global_merge)) {
  1083. CmdArgs.push_back("-backend-option");
  1084. if (A->getOption().matches(options::OPT_mno_global_merge))
  1085. CmdArgs.push_back("-aarch64-global-merge=false");
  1086. else
  1087. CmdArgs.push_back("-aarch64-global-merge=true");
  1088. }
  1089. }
  1090. // Get CPU and ABI names. They are not independent
  1091. // so we have to calculate them together.
  1092. void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
  1093. StringRef &CPUName, StringRef &ABIName) {
  1094. const char *DefMips32CPU = "mips32r2";
  1095. const char *DefMips64CPU = "mips64r2";
  1096. // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
  1097. // default for mips64(el)?-img-linux-gnu.
  1098. if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
  1099. Triple.getEnvironment() == llvm::Triple::GNU) {
  1100. DefMips32CPU = "mips32r6";
  1101. DefMips64CPU = "mips64r6";
  1102. }
  1103. // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
  1104. if (Triple.isAndroid()) {
  1105. DefMips32CPU = "mips32";
  1106. DefMips64CPU = "mips64r6";
  1107. }
  1108. // MIPS3 is the default for mips64*-unknown-openbsd.
  1109. if (Triple.getOS() == llvm::Triple::OpenBSD)
  1110. DefMips64CPU = "mips3";
  1111. if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
  1112. CPUName = A->getValue();
  1113. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  1114. ABIName = A->getValue();
  1115. // Convert a GNU style Mips ABI name to the name
  1116. // accepted by LLVM Mips backend.
  1117. ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
  1118. .Case("32", "o32")
  1119. .Case("64", "n64")
  1120. .Default(ABIName);
  1121. }
  1122. // Setup default CPU and ABI names.
  1123. if (CPUName.empty() && ABIName.empty()) {
  1124. switch (Triple.getArch()) {
  1125. default:
  1126. llvm_unreachable("Unexpected triple arch name");
  1127. case llvm::Triple::mips:
  1128. case llvm::Triple::mipsel:
  1129. CPUName = DefMips32CPU;
  1130. break;
  1131. case llvm::Triple::mips64:
  1132. case llvm::Triple::mips64el:
  1133. CPUName = DefMips64CPU;
  1134. break;
  1135. }
  1136. }
  1137. if (ABIName.empty() &&
  1138. (Triple.getVendor() == llvm::Triple::MipsTechnologies ||
  1139. Triple.getVendor() == llvm::Triple::ImaginationTechnologies)) {
  1140. ABIName = llvm::StringSwitch<const char *>(CPUName)
  1141. .Case("mips1", "o32")
  1142. .Case("mips2", "o32")
  1143. .Case("mips3", "n64")
  1144. .Case("mips4", "n64")
  1145. .Case("mips5", "n64")
  1146. .Case("mips32", "o32")
  1147. .Case("mips32r2", "o32")
  1148. .Case("mips32r3", "o32")
  1149. .Case("mips32r5", "o32")
  1150. .Case("mips32r6", "o32")
  1151. .Case("mips64", "n64")
  1152. .Case("mips64r2", "n64")
  1153. .Case("mips64r3", "n64")
  1154. .Case("mips64r5", "n64")
  1155. .Case("mips64r6", "n64")
  1156. .Case("octeon", "n64")
  1157. .Case("p5600", "o32")
  1158. .Default("");
  1159. }
  1160. if (ABIName.empty()) {
  1161. // Deduce ABI name from the target triple.
  1162. if (Triple.getArch() == llvm::Triple::mips ||
  1163. Triple.getArch() == llvm::Triple::mipsel)
  1164. ABIName = "o32";
  1165. else
  1166. ABIName = "n64";
  1167. }
  1168. if (CPUName.empty()) {
  1169. // Deduce CPU name from ABI name.
  1170. CPUName = llvm::StringSwitch<const char *>(ABIName)
  1171. .Case("o32", DefMips32CPU)
  1172. .Cases("n32", "n64", DefMips64CPU)
  1173. .Default("");
  1174. }
  1175. // FIXME: Warn on inconsistent use of -march and -mabi.
  1176. }
  1177. std::string mips::getMipsABILibSuffix(const ArgList &Args,
  1178. const llvm::Triple &Triple) {
  1179. StringRef CPUName, ABIName;
  1180. tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1181. return llvm::StringSwitch<std::string>(ABIName)
  1182. .Case("o32", "")
  1183. .Case("n32", "32")
  1184. .Case("n64", "64");
  1185. }
  1186. // Convert ABI name to the GNU tools acceptable variant.
  1187. static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
  1188. return llvm::StringSwitch<llvm::StringRef>(ABI)
  1189. .Case("o32", "32")
  1190. .Case("n64", "64")
  1191. .Default(ABI);
  1192. }
  1193. // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
  1194. // and -mfloat-abi=.
  1195. static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
  1196. mips::FloatABI ABI = mips::FloatABI::Invalid;
  1197. if (Arg *A =
  1198. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1199. options::OPT_mfloat_abi_EQ)) {
  1200. if (A->getOption().matches(options::OPT_msoft_float))
  1201. ABI = mips::FloatABI::Soft;
  1202. else if (A->getOption().matches(options::OPT_mhard_float))
  1203. ABI = mips::FloatABI::Hard;
  1204. else {
  1205. ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
  1206. .Case("soft", mips::FloatABI::Soft)
  1207. .Case("hard", mips::FloatABI::Hard)
  1208. .Default(mips::FloatABI::Invalid);
  1209. if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1210. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1211. ABI = mips::FloatABI::Hard;
  1212. }
  1213. }
  1214. }
  1215. // If unspecified, choose the default based on the platform.
  1216. if (ABI == mips::FloatABI::Invalid) {
  1217. // Assume "hard", because it's a default value used by gcc.
  1218. // When we start to recognize specific target MIPS processors,
  1219. // we will be able to select the default more correctly.
  1220. ABI = mips::FloatABI::Hard;
  1221. }
  1222. assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
  1223. return ABI;
  1224. }
  1225. static void AddTargetFeature(const ArgList &Args,
  1226. std::vector<StringRef> &Features,
  1227. OptSpecifier OnOpt, OptSpecifier OffOpt,
  1228. StringRef FeatureName) {
  1229. if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
  1230. if (A->getOption().matches(OnOpt))
  1231. Features.push_back(Args.MakeArgString("+" + FeatureName));
  1232. else
  1233. Features.push_back(Args.MakeArgString("-" + FeatureName));
  1234. }
  1235. }
  1236. static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1237. const ArgList &Args,
  1238. std::vector<StringRef> &Features) {
  1239. StringRef CPUName;
  1240. StringRef ABIName;
  1241. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1242. ABIName = getGnuCompatibleMipsABIName(ABIName);
  1243. AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
  1244. options::OPT_mabicalls, "noabicalls");
  1245. mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
  1246. if (FloatABI == mips::FloatABI::Soft) {
  1247. // FIXME: Note, this is a hack. We need to pass the selected float
  1248. // mode to the MipsTargetInfoBase to define appropriate macros there.
  1249. // Now it is the only method.
  1250. Features.push_back("+soft-float");
  1251. }
  1252. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  1253. StringRef Val = StringRef(A->getValue());
  1254. if (Val == "2008") {
  1255. if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
  1256. Features.push_back("+nan2008");
  1257. else {
  1258. Features.push_back("-nan2008");
  1259. D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
  1260. }
  1261. } else if (Val == "legacy") {
  1262. if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
  1263. Features.push_back("-nan2008");
  1264. else {
  1265. Features.push_back("+nan2008");
  1266. D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
  1267. }
  1268. } else
  1269. D.Diag(diag::err_drv_unsupported_option_argument)
  1270. << A->getOption().getName() << Val;
  1271. }
  1272. AddTargetFeature(Args, Features, options::OPT_msingle_float,
  1273. options::OPT_mdouble_float, "single-float");
  1274. AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
  1275. "mips16");
  1276. AddTargetFeature(Args, Features, options::OPT_mmicromips,
  1277. options::OPT_mno_micromips, "micromips");
  1278. AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
  1279. "dsp");
  1280. AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
  1281. "dspr2");
  1282. AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
  1283. "msa");
  1284. // Add the last -mfp32/-mfpxx/-mfp64, if none are given and the ABI is O32
  1285. // pass -mfpxx, or if none are given and fp64a is default, pass fp64 and
  1286. // nooddspreg.
  1287. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  1288. options::OPT_mfp64)) {
  1289. if (A->getOption().matches(options::OPT_mfp32))
  1290. Features.push_back(Args.MakeArgString("-fp64"));
  1291. else if (A->getOption().matches(options::OPT_mfpxx)) {
  1292. Features.push_back(Args.MakeArgString("+fpxx"));
  1293. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1294. } else
  1295. Features.push_back(Args.MakeArgString("+fp64"));
  1296. } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
  1297. Features.push_back(Args.MakeArgString("+fpxx"));
  1298. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1299. } else if (mips::isFP64ADefault(Triple, CPUName)) {
  1300. Features.push_back(Args.MakeArgString("+fp64"));
  1301. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1302. }
  1303. AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
  1304. options::OPT_modd_spreg, "nooddspreg");
  1305. }
  1306. void Clang::AddMIPSTargetArgs(const ArgList &Args,
  1307. ArgStringList &CmdArgs) const {
  1308. const Driver &D = getToolChain().getDriver();
  1309. StringRef CPUName;
  1310. StringRef ABIName;
  1311. const llvm::Triple &Triple = getToolChain().getTriple();
  1312. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1313. CmdArgs.push_back("-target-abi");
  1314. CmdArgs.push_back(ABIName.data());
  1315. mips::FloatABI ABI = getMipsFloatABI(D, Args);
  1316. if (ABI == mips::FloatABI::Soft) {
  1317. // Floating point operations and argument passing are soft.
  1318. CmdArgs.push_back("-msoft-float");
  1319. CmdArgs.push_back("-mfloat-abi");
  1320. CmdArgs.push_back("soft");
  1321. } else {
  1322. // Floating point operations and argument passing are hard.
  1323. assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
  1324. CmdArgs.push_back("-mfloat-abi");
  1325. CmdArgs.push_back("hard");
  1326. }
  1327. if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
  1328. if (A->getOption().matches(options::OPT_mxgot)) {
  1329. CmdArgs.push_back("-mllvm");
  1330. CmdArgs.push_back("-mxgot");
  1331. }
  1332. }
  1333. if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
  1334. options::OPT_mno_ldc1_sdc1)) {
  1335. if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
  1336. CmdArgs.push_back("-mllvm");
  1337. CmdArgs.push_back("-mno-ldc1-sdc1");
  1338. }
  1339. }
  1340. if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
  1341. options::OPT_mno_check_zero_division)) {
  1342. if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
  1343. CmdArgs.push_back("-mllvm");
  1344. CmdArgs.push_back("-mno-check-zero-division");
  1345. }
  1346. }
  1347. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  1348. StringRef v = A->getValue();
  1349. CmdArgs.push_back("-mllvm");
  1350. CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
  1351. A->claim();
  1352. }
  1353. if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
  1354. StringRef Val = StringRef(A->getValue());
  1355. if (mips::hasCompactBranches(CPUName)) {
  1356. if (Val == "never" || Val == "always" || Val == "optimal") {
  1357. CmdArgs.push_back("-mllvm");
  1358. CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
  1359. } else
  1360. D.Diag(diag::err_drv_unsupported_option_argument)
  1361. << A->getOption().getName() << Val;
  1362. } else
  1363. D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
  1364. }
  1365. }
  1366. /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
  1367. static std::string getPPCTargetCPU(const ArgList &Args) {
  1368. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1369. StringRef CPUName = A->getValue();
  1370. if (CPUName == "native") {
  1371. std::string CPU = llvm::sys::getHostCPUName();
  1372. if (!CPU.empty() && CPU != "generic")
  1373. return CPU;
  1374. else
  1375. return "";
  1376. }
  1377. return llvm::StringSwitch<const char *>(CPUName)
  1378. .Case("common", "generic")
  1379. .Case("440", "440")
  1380. .Case("440fp", "440")
  1381. .Case("450", "450")
  1382. .Case("601", "601")
  1383. .Case("602", "602")
  1384. .Case("603", "603")
  1385. .Case("603e", "603e")
  1386. .Case("603ev", "603ev")
  1387. .Case("604", "604")
  1388. .Case("604e", "604e")
  1389. .Case("620", "620")
  1390. .Case("630", "pwr3")
  1391. .Case("G3", "g3")
  1392. .Case("7400", "7400")
  1393. .Case("G4", "g4")
  1394. .Case("7450", "7450")
  1395. .Case("G4+", "g4+")
  1396. .Case("750", "750")
  1397. .Case("970", "970")
  1398. .Case("G5", "g5")
  1399. .Case("a2", "a2")
  1400. .Case("a2q", "a2q")
  1401. .Case("e500mc", "e500mc")
  1402. .Case("e5500", "e5500")
  1403. .Case("power3", "pwr3")
  1404. .Case("power4", "pwr4")
  1405. .Case("power5", "pwr5")
  1406. .Case("power5x", "pwr5x")
  1407. .Case("power6", "pwr6")
  1408. .Case("power6x", "pwr6x")
  1409. .Case("power7", "pwr7")
  1410. .Case("power8", "pwr8")
  1411. .Case("power9", "pwr9")
  1412. .Case("pwr3", "pwr3")
  1413. .Case("pwr4", "pwr4")
  1414. .Case("pwr5", "pwr5")
  1415. .Case("pwr5x", "pwr5x")
  1416. .Case("pwr6", "pwr6")
  1417. .Case("pwr6x", "pwr6x")
  1418. .Case("pwr7", "pwr7")
  1419. .Case("pwr8", "pwr8")
  1420. .Case("pwr9", "pwr9")
  1421. .Case("powerpc", "ppc")
  1422. .Case("powerpc64", "ppc64")
  1423. .Case("powerpc64le", "ppc64le")
  1424. .Default("");
  1425. }
  1426. return "";
  1427. }
  1428. static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1429. const ArgList &Args,
  1430. std::vector<StringRef> &Features) {
  1431. handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
  1432. ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
  1433. if (FloatABI == ppc::FloatABI::Soft)
  1434. Features.push_back("-hard-float");
  1435. // Altivec is a bit weird, allow overriding of the Altivec feature here.
  1436. AddTargetFeature(Args, Features, options::OPT_faltivec,
  1437. options::OPT_fno_altivec, "altivec");
  1438. }
  1439. ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
  1440. ppc::FloatABI ABI = ppc::FloatABI::Invalid;
  1441. if (Arg *A =
  1442. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1443. options::OPT_mfloat_abi_EQ)) {
  1444. if (A->getOption().matches(options::OPT_msoft_float))
  1445. ABI = ppc::FloatABI::Soft;
  1446. else if (A->getOption().matches(options::OPT_mhard_float))
  1447. ABI = ppc::FloatABI::Hard;
  1448. else {
  1449. ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
  1450. .Case("soft", ppc::FloatABI::Soft)
  1451. .Case("hard", ppc::FloatABI::Hard)
  1452. .Default(ppc::FloatABI::Invalid);
  1453. if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1454. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1455. ABI = ppc::FloatABI::Hard;
  1456. }
  1457. }
  1458. }
  1459. // If unspecified, choose the default based on the platform.
  1460. if (ABI == ppc::FloatABI::Invalid) {
  1461. ABI = ppc::FloatABI::Hard;
  1462. }
  1463. return ABI;
  1464. }
  1465. void Clang::AddPPCTargetArgs(const ArgList &Args,
  1466. ArgStringList &CmdArgs) const {
  1467. // Select the ABI to use.
  1468. const char *ABIName = nullptr;
  1469. if (getToolChain().getTriple().isOSLinux())
  1470. switch (getToolChain().getArch()) {
  1471. case llvm::Triple::ppc64: {
  1472. // When targeting a processor that supports QPX, or if QPX is
  1473. // specifically enabled, default to using the ABI that supports QPX (so
  1474. // long as it is not specifically disabled).
  1475. bool HasQPX = false;
  1476. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1477. HasQPX = A->getValue() == StringRef("a2q");
  1478. HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
  1479. if (HasQPX) {
  1480. ABIName = "elfv1-qpx";
  1481. break;
  1482. }
  1483. ABIName = "elfv1";
  1484. break;
  1485. }
  1486. case llvm::Triple::ppc64le:
  1487. ABIName = "elfv2";
  1488. break;
  1489. default:
  1490. break;
  1491. }
  1492. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1493. // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
  1494. // the option if given as we don't have backend support for any targets
  1495. // that don't use the altivec abi.
  1496. if (StringRef(A->getValue()) != "altivec")
  1497. ABIName = A->getValue();
  1498. ppc::FloatABI FloatABI =
  1499. ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
  1500. if (FloatABI == ppc::FloatABI::Soft) {
  1501. // Floating point operations and argument passing are soft.
  1502. CmdArgs.push_back("-msoft-float");
  1503. CmdArgs.push_back("-mfloat-abi");
  1504. CmdArgs.push_back("soft");
  1505. } else {
  1506. // Floating point operations and argument passing are hard.
  1507. assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
  1508. CmdArgs.push_back("-mfloat-abi");
  1509. CmdArgs.push_back("hard");
  1510. }
  1511. if (ABIName) {
  1512. CmdArgs.push_back("-target-abi");
  1513. CmdArgs.push_back(ABIName);
  1514. }
  1515. }
  1516. bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
  1517. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  1518. return A && (A->getValue() == StringRef(Value));
  1519. }
  1520. /// Get the (LLVM) name of the R600 gpu we are targeting.
  1521. static std::string getR600TargetGPU(const ArgList &Args) {
  1522. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1523. const char *GPUName = A->getValue();
  1524. return llvm::StringSwitch<const char *>(GPUName)
  1525. .Cases("rv630", "rv635", "r600")
  1526. .Cases("rv610", "rv620", "rs780", "rs880")
  1527. .Case("rv740", "rv770")
  1528. .Case("palm", "cedar")
  1529. .Cases("sumo", "sumo2", "sumo")
  1530. .Case("hemlock", "cypress")
  1531. .Case("aruba", "cayman")
  1532. .Default(GPUName);
  1533. }
  1534. return "";
  1535. }
  1536. static std::string getLanaiTargetCPU(const ArgList &Args) {
  1537. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1538. return A->getValue();
  1539. }
  1540. return "";
  1541. }
  1542. sparc::FloatABI sparc::getSparcFloatABI(const Driver &D,
  1543. const ArgList &Args) {
  1544. sparc::FloatABI ABI = sparc::FloatABI::Invalid;
  1545. if (Arg *A =
  1546. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1547. options::OPT_mfloat_abi_EQ)) {
  1548. if (A->getOption().matches(options::OPT_msoft_float))
  1549. ABI = sparc::FloatABI::Soft;
  1550. else if (A->getOption().matches(options::OPT_mhard_float))
  1551. ABI = sparc::FloatABI::Hard;
  1552. else {
  1553. ABI = llvm::StringSwitch<sparc::FloatABI>(A->getValue())
  1554. .Case("soft", sparc::FloatABI::Soft)
  1555. .Case("hard", sparc::FloatABI::Hard)
  1556. .Default(sparc::FloatABI::Invalid);
  1557. if (ABI == sparc::FloatABI::Invalid &&
  1558. !StringRef(A->getValue()).empty()) {
  1559. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1560. ABI = sparc::FloatABI::Hard;
  1561. }
  1562. }
  1563. }
  1564. // If unspecified, choose the default based on the platform.
  1565. // Only the hard-float ABI on Sparc is standardized, and it is the
  1566. // default. GCC also supports a nonstandard soft-float ABI mode, also
  1567. // implemented in LLVM. However as this is not standard we set the default
  1568. // to be hard-float.
  1569. if (ABI == sparc::FloatABI::Invalid) {
  1570. ABI = sparc::FloatABI::Hard;
  1571. }
  1572. return ABI;
  1573. }
  1574. static void getSparcTargetFeatures(const Driver &D, const ArgList &Args,
  1575. std::vector<StringRef> &Features) {
  1576. sparc::FloatABI FloatABI = sparc::getSparcFloatABI(D, Args);
  1577. if (FloatABI == sparc::FloatABI::Soft)
  1578. Features.push_back("+soft-float");
  1579. }
  1580. void Clang::AddSparcTargetArgs(const ArgList &Args,
  1581. ArgStringList &CmdArgs) const {
  1582. sparc::FloatABI FloatABI =
  1583. sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
  1584. if (FloatABI == sparc::FloatABI::Soft) {
  1585. // Floating point operations and argument passing are soft.
  1586. CmdArgs.push_back("-msoft-float");
  1587. CmdArgs.push_back("-mfloat-abi");
  1588. CmdArgs.push_back("soft");
  1589. } else {
  1590. // Floating point operations and argument passing are hard.
  1591. assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
  1592. CmdArgs.push_back("-mfloat-abi");
  1593. CmdArgs.push_back("hard");
  1594. }
  1595. }
  1596. void Clang::AddSystemZTargetArgs(const ArgList &Args,
  1597. ArgStringList &CmdArgs) const {
  1598. if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
  1599. CmdArgs.push_back("-mbackchain");
  1600. }
  1601. static const char *getSystemZTargetCPU(const ArgList &Args) {
  1602. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1603. return A->getValue();
  1604. return "z10";
  1605. }
  1606. static void getSystemZTargetFeatures(const ArgList &Args,
  1607. std::vector<StringRef> &Features) {
  1608. // -m(no-)htm overrides use of the transactional-execution facility.
  1609. if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
  1610. if (A->getOption().matches(options::OPT_mhtm))
  1611. Features.push_back("+transactional-execution");
  1612. else
  1613. Features.push_back("-transactional-execution");
  1614. }
  1615. // -m(no-)vx overrides use of the vector facility.
  1616. if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
  1617. if (A->getOption().matches(options::OPT_mvx))
  1618. Features.push_back("+vector");
  1619. else
  1620. Features.push_back("-vector");
  1621. }
  1622. }
  1623. static const char *getX86TargetCPU(const ArgList &Args,
  1624. const llvm::Triple &Triple) {
  1625. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1626. if (StringRef(A->getValue()) != "native") {
  1627. if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
  1628. return "core-avx2";
  1629. return A->getValue();
  1630. }
  1631. // FIXME: Reject attempts to use -march=native unless the target matches
  1632. // the host.
  1633. //
  1634. // FIXME: We should also incorporate the detected target features for use
  1635. // with -native.
  1636. std::string CPU = llvm::sys::getHostCPUName();
  1637. if (!CPU.empty() && CPU != "generic")
  1638. return Args.MakeArgString(CPU);
  1639. }
  1640. if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1641. // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
  1642. StringRef Arch = A->getValue();
  1643. const char *CPU;
  1644. if (Triple.getArch() == llvm::Triple::x86) {
  1645. CPU = llvm::StringSwitch<const char *>(Arch)
  1646. .Case("IA32", "i386")
  1647. .Case("SSE", "pentium3")
  1648. .Case("SSE2", "pentium4")
  1649. .Case("AVX", "sandybridge")
  1650. .Case("AVX2", "haswell")
  1651. .Default(nullptr);
  1652. } else {
  1653. CPU = llvm::StringSwitch<const char *>(Arch)
  1654. .Case("AVX", "sandybridge")
  1655. .Case("AVX2", "haswell")
  1656. .Default(nullptr);
  1657. }
  1658. if (CPU)
  1659. return CPU;
  1660. }
  1661. // Select the default CPU if none was given (or detection failed).
  1662. if (Triple.getArch() != llvm::Triple::x86_64 &&
  1663. Triple.getArch() != llvm::Triple::x86)
  1664. return nullptr; // This routine is only handling x86 targets.
  1665. bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
  1666. // FIXME: Need target hooks.
  1667. if (Triple.isOSDarwin()) {
  1668. if (Triple.getArchName() == "x86_64h")
  1669. return "core-avx2";
  1670. return Is64Bit ? "core2" : "yonah";
  1671. }
  1672. // Set up default CPU name for PS4 compilers.
  1673. if (Triple.isPS4CPU())
  1674. return "btver2";
  1675. // On Android use targets compatible with gcc
  1676. if (Triple.isAndroid())
  1677. return Is64Bit ? "x86-64" : "i686";
  1678. // Everything else goes to x86-64 in 64-bit mode.
  1679. if (Is64Bit)
  1680. return "x86-64";
  1681. switch (Triple.getOS()) {
  1682. case llvm::Triple::FreeBSD:
  1683. case llvm::Triple::NetBSD:
  1684. case llvm::Triple::OpenBSD:
  1685. return "i486";
  1686. case llvm::Triple::Haiku:
  1687. return "i586";
  1688. case llvm::Triple::Bitrig:
  1689. return "i686";
  1690. default:
  1691. // Fallback to p4.
  1692. return "pentium4";
  1693. }
  1694. }
  1695. /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
  1696. static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
  1697. // If we have -mcpu=, use that.
  1698. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1699. StringRef CPU = A->getValue();
  1700. #ifdef __wasm__
  1701. // Handle "native" by examining the host. "native" isn't meaningful when
  1702. // cross compiling, so only support this when the host is also WebAssembly.
  1703. if (CPU == "native")
  1704. return llvm::sys::getHostCPUName();
  1705. #endif
  1706. return CPU;
  1707. }
  1708. return "generic";
  1709. }
  1710. static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
  1711. bool FromAs = false) {
  1712. Arg *A;
  1713. switch (T.getArch()) {
  1714. default:
  1715. return "";
  1716. case llvm::Triple::aarch64:
  1717. case llvm::Triple::aarch64_be:
  1718. return getAArch64TargetCPU(Args, A);
  1719. case llvm::Triple::arm:
  1720. case llvm::Triple::armeb:
  1721. case llvm::Triple::thumb:
  1722. case llvm::Triple::thumbeb: {
  1723. StringRef MArch, MCPU;
  1724. getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
  1725. return arm::getARMTargetCPU(MCPU, MArch, T);
  1726. }
  1727. case llvm::Triple::mips:
  1728. case llvm::Triple::mipsel:
  1729. case llvm::Triple::mips64:
  1730. case llvm::Triple::mips64el: {
  1731. StringRef CPUName;
  1732. StringRef ABIName;
  1733. mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
  1734. return CPUName;
  1735. }
  1736. case llvm::Triple::nvptx:
  1737. case llvm::Triple::nvptx64:
  1738. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1739. return A->getValue();
  1740. return "";
  1741. case llvm::Triple::ppc:
  1742. case llvm::Triple::ppc64:
  1743. case llvm::Triple::ppc64le: {
  1744. std::string TargetCPUName = getPPCTargetCPU(Args);
  1745. // LLVM may default to generating code for the native CPU,
  1746. // but, like gcc, we default to a more generic option for
  1747. // each architecture. (except on Darwin)
  1748. if (TargetCPUName.empty() && !T.isOSDarwin()) {
  1749. if (T.getArch() == llvm::Triple::ppc64)
  1750. TargetCPUName = "ppc64";
  1751. else if (T.getArch() == llvm::Triple::ppc64le)
  1752. TargetCPUName = "ppc64le";
  1753. else
  1754. TargetCPUName = "ppc";
  1755. }
  1756. return TargetCPUName;
  1757. }
  1758. case llvm::Triple::sparc:
  1759. case llvm::Triple::sparcel:
  1760. case llvm::Triple::sparcv9:
  1761. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1762. return A->getValue();
  1763. return "";
  1764. case llvm::Triple::x86:
  1765. case llvm::Triple::x86_64:
  1766. return getX86TargetCPU(Args, T);
  1767. case llvm::Triple::hexagon:
  1768. return "hexagon" +
  1769. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  1770. case llvm::Triple::lanai:
  1771. return getLanaiTargetCPU(Args);
  1772. case llvm::Triple::systemz:
  1773. return getSystemZTargetCPU(Args);
  1774. case llvm::Triple::r600:
  1775. case llvm::Triple::amdgcn:
  1776. return getR600TargetGPU(Args);
  1777. case llvm::Triple::wasm32:
  1778. case llvm::Triple::wasm64:
  1779. return getWebAssemblyTargetCPU(Args);
  1780. }
  1781. }
  1782. static unsigned getLTOParallelism(const ArgList &Args, const Driver &D) {
  1783. unsigned Parallelism = 0;
  1784. Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
  1785. if (LtoJobsArg &&
  1786. StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
  1787. D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
  1788. << LtoJobsArg->getValue();
  1789. return Parallelism;
  1790. }
  1791. // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
  1792. // default.
  1793. static bool isUseSeparateSections(const llvm::Triple &Triple) {
  1794. return Triple.getOS() == llvm::Triple::CloudABI ||
  1795. Triple.getArch() == llvm::Triple::wasm32 ||
  1796. Triple.getArch() == llvm::Triple::wasm64;
  1797. }
  1798. static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
  1799. ArgStringList &CmdArgs, bool IsThinLTO,
  1800. const Driver &D) {
  1801. // Tell the linker to load the plugin. This has to come before AddLinkerInputs
  1802. // as gold requires -plugin to come before any -plugin-opt that -Wl might
  1803. // forward.
  1804. CmdArgs.push_back("-plugin");
  1805. std::string Plugin =
  1806. ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
  1807. CmdArgs.push_back(Args.MakeArgString(Plugin));
  1808. // Try to pass driver level flags relevant to LTO code generation down to
  1809. // the plugin.
  1810. // Handle flags for selecting CPU variants.
  1811. std::string CPU = getCPUName(Args, ToolChain.getTriple());
  1812. if (!CPU.empty())
  1813. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
  1814. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  1815. StringRef OOpt;
  1816. if (A->getOption().matches(options::OPT_O4) ||
  1817. A->getOption().matches(options::OPT_Ofast))
  1818. OOpt = "3";
  1819. else if (A->getOption().matches(options::OPT_O))
  1820. OOpt = A->getValue();
  1821. else if (A->getOption().matches(options::OPT_O0))
  1822. OOpt = "0";
  1823. if (!OOpt.empty())
  1824. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
  1825. }
  1826. if (IsThinLTO)
  1827. CmdArgs.push_back("-plugin-opt=thinlto");
  1828. if (unsigned Parallelism = getLTOParallelism(Args, D))
  1829. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=jobs=") +
  1830. llvm::to_string(Parallelism)));
  1831. // If an explicit debugger tuning argument appeared, pass it along.
  1832. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  1833. options::OPT_ggdbN_Group)) {
  1834. if (A->getOption().matches(options::OPT_glldb))
  1835. CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
  1836. else if (A->getOption().matches(options::OPT_gsce))
  1837. CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
  1838. else
  1839. CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
  1840. }
  1841. bool UseSeparateSections =
  1842. isUseSeparateSections(ToolChain.getEffectiveTriple());
  1843. if (Args.hasFlag(options::OPT_ffunction_sections,
  1844. options::OPT_fno_function_sections, UseSeparateSections)) {
  1845. CmdArgs.push_back("-plugin-opt=-function-sections");
  1846. }
  1847. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  1848. UseSeparateSections)) {
  1849. CmdArgs.push_back("-plugin-opt=-data-sections");
  1850. }
  1851. }
  1852. /// This is a helper function for validating the optional refinement step
  1853. /// parameter in reciprocal argument strings. Return false if there is an error
  1854. /// parsing the refinement step. Otherwise, return true and set the Position
  1855. /// of the refinement step in the input string.
  1856. static bool getRefinementStep(StringRef In, const Driver &D,
  1857. const Arg &A, size_t &Position) {
  1858. const char RefinementStepToken = ':';
  1859. Position = In.find(RefinementStepToken);
  1860. if (Position != StringRef::npos) {
  1861. StringRef Option = A.getOption().getName();
  1862. StringRef RefStep = In.substr(Position + 1);
  1863. // Allow exactly one numeric character for the additional refinement
  1864. // step parameter. This is reasonable for all currently-supported
  1865. // operations and architectures because we would expect that a larger value
  1866. // of refinement steps would cause the estimate "optimization" to
  1867. // under-perform the native operation. Also, if the estimate does not
  1868. // converge quickly, it probably will not ever converge, so further
  1869. // refinement steps will not produce a better answer.
  1870. if (RefStep.size() != 1) {
  1871. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1872. return false;
  1873. }
  1874. char RefStepChar = RefStep[0];
  1875. if (RefStepChar < '0' || RefStepChar > '9') {
  1876. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1877. return false;
  1878. }
  1879. }
  1880. return true;
  1881. }
  1882. /// The -mrecip flag requires processing of many optional parameters.
  1883. static void ParseMRecip(const Driver &D, const ArgList &Args,
  1884. ArgStringList &OutStrings) {
  1885. StringRef DisabledPrefixIn = "!";
  1886. StringRef DisabledPrefixOut = "!";
  1887. StringRef EnabledPrefixOut = "";
  1888. StringRef Out = "-mrecip=";
  1889. Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
  1890. if (!A)
  1891. return;
  1892. unsigned NumOptions = A->getNumValues();
  1893. if (NumOptions == 0) {
  1894. // No option is the same as "all".
  1895. OutStrings.push_back(Args.MakeArgString(Out + "all"));
  1896. return;
  1897. }
  1898. // Pass through "all", "none", or "default" with an optional refinement step.
  1899. if (NumOptions == 1) {
  1900. StringRef Val = A->getValue(0);
  1901. size_t RefStepLoc;
  1902. if (!getRefinementStep(Val, D, *A, RefStepLoc))
  1903. return;
  1904. StringRef ValBase = Val.slice(0, RefStepLoc);
  1905. if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
  1906. OutStrings.push_back(Args.MakeArgString(Out + Val));
  1907. return;
  1908. }
  1909. }
  1910. // Each reciprocal type may be enabled or disabled individually.
  1911. // Check each input value for validity, concatenate them all back together,
  1912. // and pass through.
  1913. llvm::StringMap<bool> OptionStrings;
  1914. OptionStrings.insert(std::make_pair("divd", false));
  1915. OptionStrings.insert(std::make_pair("divf", false));
  1916. OptionStrings.insert(std::make_pair("vec-divd", false));
  1917. OptionStrings.insert(std::make_pair("vec-divf", false));
  1918. OptionStrings.insert(std::make_pair("sqrtd", false));
  1919. OptionStrings.insert(std::make_pair("sqrtf", false));
  1920. OptionStrings.insert(std::make_pair("vec-sqrtd", false));
  1921. OptionStrings.insert(std::make_pair("vec-sqrtf", false));
  1922. for (unsigned i = 0; i != NumOptions; ++i) {
  1923. StringRef Val = A->getValue(i);
  1924. bool IsDisabled = Val.startswith(DisabledPrefixIn);
  1925. // Ignore the disablement token for string matching.
  1926. if (IsDisabled)
  1927. Val = Val.substr(1);
  1928. size_t RefStep;
  1929. if (!getRefinementStep(Val, D, *A, RefStep))
  1930. return;
  1931. StringRef ValBase = Val.slice(0, RefStep);
  1932. llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
  1933. if (OptionIter == OptionStrings.end()) {
  1934. // Try again specifying float suffix.
  1935. OptionIter = OptionStrings.find(ValBase.str() + 'f');
  1936. if (OptionIter == OptionStrings.end()) {
  1937. // The input name did not match any known option string.
  1938. D.Diag(diag::err_drv_unknown_argument) << Val;
  1939. return;
  1940. }
  1941. // The option was specified without a float or double suffix.
  1942. // Make sure that the double entry was not already specified.
  1943. // The float entry will be checked below.
  1944. if (OptionStrings[ValBase.str() + 'd']) {
  1945. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1946. return;
  1947. }
  1948. }
  1949. if (OptionIter->second == true) {
  1950. // Duplicate option specified.
  1951. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1952. return;
  1953. }
  1954. // Mark the matched option as found. Do not allow duplicate specifiers.
  1955. OptionIter->second = true;
  1956. // If the precision was not specified, also mark the double entry as found.
  1957. if (ValBase.back() != 'f' && ValBase.back() != 'd')
  1958. OptionStrings[ValBase.str() + 'd'] = true;
  1959. // Build the output string.
  1960. StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
  1961. Out = Args.MakeArgString(Out + Prefix + Val);
  1962. if (i != NumOptions - 1)
  1963. Out = Args.MakeArgString(Out + ",");
  1964. }
  1965. OutStrings.push_back(Args.MakeArgString(Out));
  1966. }
  1967. static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1968. const ArgList &Args,
  1969. std::vector<StringRef> &Features) {
  1970. // If -march=native, autodetect the feature list.
  1971. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1972. if (StringRef(A->getValue()) == "native") {
  1973. llvm::StringMap<bool> HostFeatures;
  1974. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  1975. for (auto &F : HostFeatures)
  1976. Features.push_back(
  1977. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  1978. }
  1979. }
  1980. if (Triple.getArchName() == "x86_64h") {
  1981. // x86_64h implies quite a few of the more modern subtarget features
  1982. // for Haswell class CPUs, but not all of them. Opt-out of a few.
  1983. Features.push_back("-rdrnd");
  1984. Features.push_back("-aes");
  1985. Features.push_back("-pclmul");
  1986. Features.push_back("-rtm");
  1987. Features.push_back("-hle");
  1988. Features.push_back("-fsgsbase");
  1989. }
  1990. const llvm::Triple::ArchType ArchType = Triple.getArch();
  1991. // Add features to be compatible with gcc for Android.
  1992. if (Triple.isAndroid()) {
  1993. if (ArchType == llvm::Triple::x86_64) {
  1994. Features.push_back("+sse4.2");
  1995. Features.push_back("+popcnt");
  1996. } else
  1997. Features.push_back("+ssse3");
  1998. }
  1999. // Set features according to the -arch flag on MSVC.
  2000. if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  2001. StringRef Arch = A->getValue();
  2002. bool ArchUsed = false;
  2003. // First, look for flags that are shared in x86 and x86-64.
  2004. if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
  2005. if (Arch == "AVX" || Arch == "AVX2") {
  2006. ArchUsed = true;
  2007. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  2008. }
  2009. }
  2010. // Then, look for x86-specific flags.
  2011. if (ArchType == llvm::Triple::x86) {
  2012. if (Arch == "IA32") {
  2013. ArchUsed = true;
  2014. } else if (Arch == "SSE" || Arch == "SSE2") {
  2015. ArchUsed = true;
  2016. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  2017. }
  2018. }
  2019. if (!ArchUsed)
  2020. D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
  2021. }
  2022. // Now add any that the user explicitly requested on the command line,
  2023. // which may override the defaults.
  2024. handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
  2025. }
  2026. void Clang::AddX86TargetArgs(const ArgList &Args,
  2027. ArgStringList &CmdArgs) const {
  2028. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  2029. Args.hasArg(options::OPT_mkernel) ||
  2030. Args.hasArg(options::OPT_fapple_kext))
  2031. CmdArgs.push_back("-disable-red-zone");
  2032. // Default to avoid implicit floating-point for kernel/kext code, but allow
  2033. // that to be overridden with -mno-soft-float.
  2034. bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
  2035. Args.hasArg(options::OPT_fapple_kext));
  2036. if (Arg *A = Args.getLastArg(
  2037. options::OPT_msoft_float, options::OPT_mno_soft_float,
  2038. options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
  2039. const Option &O = A->getOption();
  2040. NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
  2041. O.matches(options::OPT_msoft_float));
  2042. }
  2043. if (NoImplicitFloat)
  2044. CmdArgs.push_back("-no-implicit-float");
  2045. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  2046. StringRef Value = A->getValue();
  2047. if (Value == "intel" || Value == "att") {
  2048. CmdArgs.push_back("-mllvm");
  2049. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  2050. } else {
  2051. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  2052. << A->getOption().getName() << Value;
  2053. }
  2054. }
  2055. // Set flags to support MCU ABI.
  2056. if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
  2057. CmdArgs.push_back("-mfloat-abi");
  2058. CmdArgs.push_back("soft");
  2059. CmdArgs.push_back("-mstack-alignment=4");
  2060. }
  2061. }
  2062. void Clang::AddHexagonTargetArgs(const ArgList &Args,
  2063. ArgStringList &CmdArgs) const {
  2064. CmdArgs.push_back("-mqdsp6-compat");
  2065. CmdArgs.push_back("-Wreturn-type");
  2066. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  2067. std::string N = llvm::utostr(G.getValue());
  2068. std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
  2069. CmdArgs.push_back("-mllvm");
  2070. CmdArgs.push_back(Args.MakeArgString(Opt));
  2071. }
  2072. if (!Args.hasArg(options::OPT_fno_short_enums))
  2073. CmdArgs.push_back("-fshort-enums");
  2074. if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
  2075. CmdArgs.push_back("-mllvm");
  2076. CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
  2077. }
  2078. CmdArgs.push_back("-mllvm");
  2079. CmdArgs.push_back("-machine-sink-split=0");
  2080. }
  2081. void Clang::AddLanaiTargetArgs(const ArgList &Args,
  2082. ArgStringList &CmdArgs) const {
  2083. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  2084. StringRef CPUName = A->getValue();
  2085. CmdArgs.push_back("-target-cpu");
  2086. CmdArgs.push_back(Args.MakeArgString(CPUName));
  2087. }
  2088. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  2089. StringRef Value = A->getValue();
  2090. // Only support mregparm=4 to support old usage. Report error for all other
  2091. // cases.
  2092. int Mregparm;
  2093. if (Value.getAsInteger(10, Mregparm)) {
  2094. if (Mregparm != 4) {
  2095. getToolChain().getDriver().Diag(
  2096. diag::err_drv_unsupported_option_argument)
  2097. << A->getOption().getName() << Value;
  2098. }
  2099. }
  2100. }
  2101. }
  2102. void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
  2103. ArgStringList &CmdArgs) const {
  2104. // Default to "hidden" visibility.
  2105. if (!Args.hasArg(options::OPT_fvisibility_EQ,
  2106. options::OPT_fvisibility_ms_compat)) {
  2107. CmdArgs.push_back("-fvisibility");
  2108. CmdArgs.push_back("hidden");
  2109. }
  2110. }
  2111. // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
  2112. static bool DecodeAArch64Features(const Driver &D, StringRef text,
  2113. std::vector<StringRef> &Features) {
  2114. SmallVector<StringRef, 8> Split;
  2115. text.split(Split, StringRef("+"), -1, false);
  2116. for (StringRef Feature : Split) {
  2117. StringRef FeatureName = llvm::AArch64::getArchExtFeature(Feature);
  2118. if (!FeatureName.empty())
  2119. Features.push_back(FeatureName);
  2120. else if (Feature == "neon" || Feature == "noneon")
  2121. D.Diag(diag::err_drv_no_neon_modifier);
  2122. else
  2123. return false;
  2124. }
  2125. return true;
  2126. }
  2127. // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
  2128. // decode CPU and feature.
  2129. static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
  2130. std::vector<StringRef> &Features) {
  2131. std::pair<StringRef, StringRef> Split = Mcpu.split("+");
  2132. CPU = Split.first;
  2133. if (CPU == "generic") {
  2134. Features.push_back("+neon");
  2135. } else {
  2136. unsigned ArchKind = llvm::AArch64::parseCPUArch(CPU);
  2137. unsigned Extersion = llvm::AArch64::getDefaultExtensions(CPU, ArchKind);
  2138. if (!llvm::AArch64::getExtensionFeatures(Extersion, Features))
  2139. return false;
  2140. }
  2141. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  2142. return false;
  2143. return true;
  2144. }
  2145. static bool
  2146. getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
  2147. const ArgList &Args,
  2148. std::vector<StringRef> &Features) {
  2149. std::string MarchLowerCase = March.lower();
  2150. std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
  2151. unsigned ArchKind = llvm::AArch64::parseArch(Split.first);
  2152. if (ArchKind == static_cast<unsigned>(llvm::AArch64::ArchKind::AK_INVALID) ||
  2153. !llvm::AArch64::getArchFeatures(ArchKind, Features) ||
  2154. (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features)))
  2155. return false;
  2156. return true;
  2157. }
  2158. static bool
  2159. getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  2160. const ArgList &Args,
  2161. std::vector<StringRef> &Features) {
  2162. StringRef CPU;
  2163. std::string McpuLowerCase = Mcpu.lower();
  2164. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
  2165. return false;
  2166. return true;
  2167. }
  2168. static bool
  2169. getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
  2170. const ArgList &Args,
  2171. std::vector<StringRef> &Features) {
  2172. std::string MtuneLowerCase = Mtune.lower();
  2173. // Handle CPU name is 'native'.
  2174. if (MtuneLowerCase == "native")
  2175. MtuneLowerCase = llvm::sys::getHostCPUName();
  2176. if (MtuneLowerCase == "cyclone") {
  2177. Features.push_back("+zcm");
  2178. Features.push_back("+zcz");
  2179. }
  2180. return true;
  2181. }
  2182. static bool
  2183. getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  2184. const ArgList &Args,
  2185. std::vector<StringRef> &Features) {
  2186. StringRef CPU;
  2187. std::vector<StringRef> DecodedFeature;
  2188. std::string McpuLowerCase = Mcpu.lower();
  2189. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
  2190. return false;
  2191. return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
  2192. }
  2193. static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
  2194. std::vector<StringRef> &Features) {
  2195. Arg *A;
  2196. bool success = true;
  2197. // Enable NEON by default.
  2198. Features.push_back("+neon");
  2199. if ((A = Args.getLastArg(options::OPT_march_EQ)))
  2200. success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
  2201. else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
  2202. success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  2203. else if (Args.hasArg(options::OPT_arch))
  2204. success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args, A),
  2205. Args, Features);
  2206. if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
  2207. success =
  2208. getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
  2209. else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
  2210. success =
  2211. getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  2212. else if (success && Args.hasArg(options::OPT_arch))
  2213. success = getAArch64MicroArchFeaturesFromMcpu(
  2214. D, getAArch64TargetCPU(Args, A), Args, Features);
  2215. if (!success)
  2216. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  2217. if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
  2218. Features.push_back("-fp-armv8");
  2219. Features.push_back("-crypto");
  2220. Features.push_back("-neon");
  2221. }
  2222. // En/disable crc
  2223. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  2224. if (A->getOption().matches(options::OPT_mcrc))
  2225. Features.push_back("+crc");
  2226. else
  2227. Features.push_back("-crc");
  2228. }
  2229. if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  2230. options::OPT_munaligned_access))
  2231. if (A->getOption().matches(options::OPT_mno_unaligned_access))
  2232. Features.push_back("+strict-align");
  2233. if (Args.hasArg(options::OPT_ffixed_x18))
  2234. Features.push_back("+reserve-x18");
  2235. }
  2236. static void getHexagonTargetFeatures(const ArgList &Args,
  2237. std::vector<StringRef> &Features) {
  2238. handleTargetFeaturesGroup(Args, Features,
  2239. options::OPT_m_hexagon_Features_Group);
  2240. bool UseLongCalls = false;
  2241. if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
  2242. options::OPT_mno_long_calls)) {
  2243. if (A->getOption().matches(options::OPT_mlong_calls))
  2244. UseLongCalls = true;
  2245. }
  2246. Features.push_back(UseLongCalls ? "+long-calls" : "-long-calls");
  2247. }
  2248. static void getWebAssemblyTargetFeatures(const ArgList &Args,
  2249. std::vector<StringRef> &Features) {
  2250. handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
  2251. }
  2252. static void getAMDGPUTargetFeatures(const Driver &D, const ArgList &Args,
  2253. std::vector<StringRef> &Features) {
  2254. if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi)) {
  2255. StringRef value = dAbi->getValue();
  2256. if (value == "1.0") {
  2257. Features.push_back("+amdgpu-debugger-insert-nops");
  2258. Features.push_back("+amdgpu-debugger-reserve-regs");
  2259. Features.push_back("+amdgpu-debugger-emit-prologue");
  2260. } else {
  2261. D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
  2262. }
  2263. }
  2264. handleTargetFeaturesGroup(
  2265. Args, Features, options::OPT_m_amdgpu_Features_Group);
  2266. }
  2267. static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
  2268. const ArgList &Args, ArgStringList &CmdArgs,
  2269. bool ForAS) {
  2270. const Driver &D = TC.getDriver();
  2271. std::vector<StringRef> Features;
  2272. switch (Triple.getArch()) {
  2273. default:
  2274. break;
  2275. case llvm::Triple::mips:
  2276. case llvm::Triple::mipsel:
  2277. case llvm::Triple::mips64:
  2278. case llvm::Triple::mips64el:
  2279. getMIPSTargetFeatures(D, Triple, Args, Features);
  2280. break;
  2281. case llvm::Triple::arm:
  2282. case llvm::Triple::armeb:
  2283. case llvm::Triple::thumb:
  2284. case llvm::Triple::thumbeb:
  2285. getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
  2286. break;
  2287. case llvm::Triple::ppc:
  2288. case llvm::Triple::ppc64:
  2289. case llvm::Triple::ppc64le:
  2290. getPPCTargetFeatures(D, Triple, Args, Features);
  2291. break;
  2292. case llvm::Triple::systemz:
  2293. getSystemZTargetFeatures(Args, Features);
  2294. break;
  2295. case llvm::Triple::aarch64:
  2296. case llvm::Triple::aarch64_be:
  2297. getAArch64TargetFeatures(D, Args, Features);
  2298. break;
  2299. case llvm::Triple::x86:
  2300. case llvm::Triple::x86_64:
  2301. getX86TargetFeatures(D, Triple, Args, Features);
  2302. break;
  2303. case llvm::Triple::hexagon:
  2304. getHexagonTargetFeatures(Args, Features);
  2305. break;
  2306. case llvm::Triple::wasm32:
  2307. case llvm::Triple::wasm64:
  2308. getWebAssemblyTargetFeatures(Args, Features);
  2309. break;
  2310. case llvm::Triple::sparc:
  2311. case llvm::Triple::sparcel:
  2312. case llvm::Triple::sparcv9:
  2313. getSparcTargetFeatures(D, Args, Features);
  2314. break;
  2315. case llvm::Triple::r600:
  2316. case llvm::Triple::amdgcn:
  2317. getAMDGPUTargetFeatures(D, Args, Features);
  2318. break;
  2319. }
  2320. // Find the last of each feature.
  2321. llvm::StringMap<unsigned> LastOpt;
  2322. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2323. StringRef Name = Features[I];
  2324. assert(Name[0] == '-' || Name[0] == '+');
  2325. LastOpt[Name.drop_front(1)] = I;
  2326. }
  2327. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2328. // If this feature was overridden, ignore it.
  2329. StringRef Name = Features[I];
  2330. llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
  2331. assert(LastI != LastOpt.end());
  2332. unsigned Last = LastI->second;
  2333. if (Last != I)
  2334. continue;
  2335. CmdArgs.push_back("-target-feature");
  2336. CmdArgs.push_back(Name.data());
  2337. }
  2338. }
  2339. static bool
  2340. shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
  2341. const llvm::Triple &Triple) {
  2342. // We use the zero-cost exception tables for Objective-C if the non-fragile
  2343. // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
  2344. // later.
  2345. if (runtime.isNonFragile())
  2346. return true;
  2347. if (!Triple.isMacOSX())
  2348. return false;
  2349. return (!Triple.isMacOSXVersionLT(10, 5) &&
  2350. (Triple.getArch() == llvm::Triple::x86_64 ||
  2351. Triple.getArch() == llvm::Triple::arm));
  2352. }
  2353. /// Adds exception related arguments to the driver command arguments. There's a
  2354. /// master flag, -fexceptions and also language specific flags to enable/disable
  2355. /// C++ and Objective-C exceptions. This makes it possible to for example
  2356. /// disable C++ exceptions but enable Objective-C exceptions.
  2357. static void addExceptionArgs(const ArgList &Args, types::ID InputType,
  2358. const ToolChain &TC, bool KernelOrKext,
  2359. const ObjCRuntime &objcRuntime,
  2360. ArgStringList &CmdArgs) {
  2361. const Driver &D = TC.getDriver();
  2362. const llvm::Triple &Triple = TC.getTriple();
  2363. if (KernelOrKext) {
  2364. // -mkernel and -fapple-kext imply no exceptions, so claim exception related
  2365. // arguments now to avoid warnings about unused arguments.
  2366. Args.ClaimAllArgs(options::OPT_fexceptions);
  2367. Args.ClaimAllArgs(options::OPT_fno_exceptions);
  2368. Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
  2369. Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
  2370. Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
  2371. Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
  2372. return;
  2373. }
  2374. // See if the user explicitly enabled exceptions.
  2375. bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  2376. false);
  2377. // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
  2378. // is not necessarily sensible, but follows GCC.
  2379. if (types::isObjC(InputType) &&
  2380. Args.hasFlag(options::OPT_fobjc_exceptions,
  2381. options::OPT_fno_objc_exceptions, true)) {
  2382. CmdArgs.push_back("-fobjc-exceptions");
  2383. EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
  2384. }
  2385. if (types::isCXX(InputType)) {
  2386. // Disable C++ EH by default on XCore and PS4.
  2387. bool CXXExceptionsEnabled =
  2388. Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
  2389. Arg *ExceptionArg = Args.getLastArg(
  2390. options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
  2391. options::OPT_fexceptions, options::OPT_fno_exceptions);
  2392. if (ExceptionArg)
  2393. CXXExceptionsEnabled =
  2394. ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
  2395. ExceptionArg->getOption().matches(options::OPT_fexceptions);
  2396. if (CXXExceptionsEnabled) {
  2397. if (Triple.isPS4CPU()) {
  2398. ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
  2399. assert(ExceptionArg &&
  2400. "On the PS4 exceptions should only be enabled if passing "
  2401. "an argument");
  2402. if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
  2403. const Arg *RTTIArg = TC.getRTTIArg();
  2404. assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
  2405. D.Diag(diag::err_drv_argument_not_allowed_with)
  2406. << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
  2407. } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
  2408. D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
  2409. } else
  2410. assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
  2411. CmdArgs.push_back("-fcxx-exceptions");
  2412. EH = true;
  2413. }
  2414. }
  2415. if (EH)
  2416. CmdArgs.push_back("-fexceptions");
  2417. }
  2418. static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
  2419. bool Default = true;
  2420. if (TC.getTriple().isOSDarwin()) {
  2421. // The native darwin assembler doesn't support the linker_option directives,
  2422. // so we disable them if we think the .s file will be passed to it.
  2423. Default = TC.useIntegratedAs();
  2424. }
  2425. return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
  2426. Default);
  2427. }
  2428. static bool ShouldDisableDwarfDirectory(const ArgList &Args,
  2429. const ToolChain &TC) {
  2430. bool UseDwarfDirectory =
  2431. Args.hasFlag(options::OPT_fdwarf_directory_asm,
  2432. options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
  2433. return !UseDwarfDirectory;
  2434. }
  2435. /// \brief Check whether the given input tree contains any compilation actions.
  2436. static bool ContainsCompileAction(const Action *A) {
  2437. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
  2438. return true;
  2439. for (const auto &AI : A->inputs())
  2440. if (ContainsCompileAction(AI))
  2441. return true;
  2442. return false;
  2443. }
  2444. /// \brief Check if -relax-all should be passed to the internal assembler.
  2445. /// This is done by default when compiling non-assembler source with -O0.
  2446. static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
  2447. bool RelaxDefault = true;
  2448. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2449. RelaxDefault = A->getOption().matches(options::OPT_O0);
  2450. if (RelaxDefault) {
  2451. RelaxDefault = false;
  2452. for (const auto &Act : C.getActions()) {
  2453. if (ContainsCompileAction(Act)) {
  2454. RelaxDefault = true;
  2455. break;
  2456. }
  2457. }
  2458. }
  2459. return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
  2460. RelaxDefault);
  2461. }
  2462. // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
  2463. // to the corresponding DebugInfoKind.
  2464. static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
  2465. assert(A.getOption().matches(options::OPT_gN_Group) &&
  2466. "Not a -g option that specifies a debug-info level");
  2467. if (A.getOption().matches(options::OPT_g0) ||
  2468. A.getOption().matches(options::OPT_ggdb0))
  2469. return codegenoptions::NoDebugInfo;
  2470. if (A.getOption().matches(options::OPT_gline_tables_only) ||
  2471. A.getOption().matches(options::OPT_ggdb1))
  2472. return codegenoptions::DebugLineTablesOnly;
  2473. return codegenoptions::LimitedDebugInfo;
  2474. }
  2475. // Extract the integer N from a string spelled "-dwarf-N", returning 0
  2476. // on mismatch. The StringRef input (rather than an Arg) allows
  2477. // for use by the "-Xassembler" option parser.
  2478. static unsigned DwarfVersionNum(StringRef ArgValue) {
  2479. return llvm::StringSwitch<unsigned>(ArgValue)
  2480. .Case("-gdwarf-2", 2)
  2481. .Case("-gdwarf-3", 3)
  2482. .Case("-gdwarf-4", 4)
  2483. .Case("-gdwarf-5", 5)
  2484. .Default(0);
  2485. }
  2486. static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
  2487. codegenoptions::DebugInfoKind DebugInfoKind,
  2488. unsigned DwarfVersion,
  2489. llvm::DebuggerKind DebuggerTuning) {
  2490. switch (DebugInfoKind) {
  2491. case codegenoptions::DebugLineTablesOnly:
  2492. CmdArgs.push_back("-debug-info-kind=line-tables-only");
  2493. break;
  2494. case codegenoptions::LimitedDebugInfo:
  2495. CmdArgs.push_back("-debug-info-kind=limited");
  2496. break;
  2497. case codegenoptions::FullDebugInfo:
  2498. CmdArgs.push_back("-debug-info-kind=standalone");
  2499. break;
  2500. default:
  2501. break;
  2502. }
  2503. if (DwarfVersion > 0)
  2504. CmdArgs.push_back(
  2505. Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
  2506. switch (DebuggerTuning) {
  2507. case llvm::DebuggerKind::GDB:
  2508. CmdArgs.push_back("-debugger-tuning=gdb");
  2509. break;
  2510. case llvm::DebuggerKind::LLDB:
  2511. CmdArgs.push_back("-debugger-tuning=lldb");
  2512. break;
  2513. case llvm::DebuggerKind::SCE:
  2514. CmdArgs.push_back("-debugger-tuning=sce");
  2515. break;
  2516. default:
  2517. break;
  2518. }
  2519. }
  2520. static void CollectArgsForIntegratedAssembler(Compilation &C,
  2521. const ArgList &Args,
  2522. ArgStringList &CmdArgs,
  2523. const Driver &D) {
  2524. if (UseRelaxAll(C, Args))
  2525. CmdArgs.push_back("-mrelax-all");
  2526. // Only default to -mincremental-linker-compatible if we think we are
  2527. // targeting the MSVC linker.
  2528. bool DefaultIncrementalLinkerCompatible =
  2529. C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
  2530. if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
  2531. options::OPT_mno_incremental_linker_compatible,
  2532. DefaultIncrementalLinkerCompatible))
  2533. CmdArgs.push_back("-mincremental-linker-compatible");
  2534. switch (C.getDefaultToolChain().getArch()) {
  2535. case llvm::Triple::arm:
  2536. case llvm::Triple::armeb:
  2537. case llvm::Triple::thumb:
  2538. case llvm::Triple::thumbeb:
  2539. if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
  2540. StringRef Value = A->getValue();
  2541. if (Value == "always" || Value == "never" || Value == "arm" ||
  2542. Value == "thumb") {
  2543. CmdArgs.push_back("-mllvm");
  2544. CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
  2545. } else {
  2546. D.Diag(diag::err_drv_unsupported_option_argument)
  2547. << A->getOption().getName() << Value;
  2548. }
  2549. }
  2550. break;
  2551. default:
  2552. break;
  2553. }
  2554. // When passing -I arguments to the assembler we sometimes need to
  2555. // unconditionally take the next argument. For example, when parsing
  2556. // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
  2557. // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
  2558. // arg after parsing the '-I' arg.
  2559. bool TakeNextArg = false;
  2560. // When using an integrated assembler, translate -Wa, and -Xassembler
  2561. // options.
  2562. bool CompressDebugSections = false;
  2563. bool UseRelaxRelocations = ENABLE_X86_RELAX_RELOCATIONS;
  2564. const char *MipsTargetFeature = nullptr;
  2565. for (const Arg *A :
  2566. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  2567. A->claim();
  2568. for (StringRef Value : A->getValues()) {
  2569. if (TakeNextArg) {
  2570. CmdArgs.push_back(Value.data());
  2571. TakeNextArg = false;
  2572. continue;
  2573. }
  2574. switch (C.getDefaultToolChain().getArch()) {
  2575. default:
  2576. break;
  2577. case llvm::Triple::mips:
  2578. case llvm::Triple::mipsel:
  2579. case llvm::Triple::mips64:
  2580. case llvm::Triple::mips64el:
  2581. if (Value == "--trap") {
  2582. CmdArgs.push_back("-target-feature");
  2583. CmdArgs.push_back("+use-tcc-in-div");
  2584. continue;
  2585. }
  2586. if (Value == "--break") {
  2587. CmdArgs.push_back("-target-feature");
  2588. CmdArgs.push_back("-use-tcc-in-div");
  2589. continue;
  2590. }
  2591. if (Value.startswith("-msoft-float")) {
  2592. CmdArgs.push_back("-target-feature");
  2593. CmdArgs.push_back("+soft-float");
  2594. continue;
  2595. }
  2596. if (Value.startswith("-mhard-float")) {
  2597. CmdArgs.push_back("-target-feature");
  2598. CmdArgs.push_back("-soft-float");
  2599. continue;
  2600. }
  2601. MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
  2602. .Case("-mips1", "+mips1")
  2603. .Case("-mips2", "+mips2")
  2604. .Case("-mips3", "+mips3")
  2605. .Case("-mips4", "+mips4")
  2606. .Case("-mips5", "+mips5")
  2607. .Case("-mips32", "+mips32")
  2608. .Case("-mips32r2", "+mips32r2")
  2609. .Case("-mips32r3", "+mips32r3")
  2610. .Case("-mips32r5", "+mips32r5")
  2611. .Case("-mips32r6", "+mips32r6")
  2612. .Case("-mips64", "+mips64")
  2613. .Case("-mips64r2", "+mips64r2")
  2614. .Case("-mips64r3", "+mips64r3")
  2615. .Case("-mips64r5", "+mips64r5")
  2616. .Case("-mips64r6", "+mips64r6")
  2617. .Default(nullptr);
  2618. if (MipsTargetFeature)
  2619. continue;
  2620. }
  2621. if (Value == "-force_cpusubtype_ALL") {
  2622. // Do nothing, this is the default and we don't support anything else.
  2623. } else if (Value == "-L") {
  2624. CmdArgs.push_back("-msave-temp-labels");
  2625. } else if (Value == "--fatal-warnings") {
  2626. CmdArgs.push_back("-massembler-fatal-warnings");
  2627. } else if (Value == "--noexecstack") {
  2628. CmdArgs.push_back("-mnoexecstack");
  2629. } else if (Value == "-compress-debug-sections" ||
  2630. Value == "--compress-debug-sections") {
  2631. CompressDebugSections = true;
  2632. } else if (Value == "-nocompress-debug-sections" ||
  2633. Value == "--nocompress-debug-sections") {
  2634. CompressDebugSections = false;
  2635. } else if (Value == "-mrelax-relocations=yes" ||
  2636. Value == "--mrelax-relocations=yes") {
  2637. UseRelaxRelocations = true;
  2638. } else if (Value == "-mrelax-relocations=no" ||
  2639. Value == "--mrelax-relocations=no") {
  2640. UseRelaxRelocations = false;
  2641. } else if (Value.startswith("-I")) {
  2642. CmdArgs.push_back(Value.data());
  2643. // We need to consume the next argument if the current arg is a plain
  2644. // -I. The next arg will be the include directory.
  2645. if (Value == "-I")
  2646. TakeNextArg = true;
  2647. } else if (Value.startswith("-gdwarf-")) {
  2648. // "-gdwarf-N" options are not cc1as options.
  2649. unsigned DwarfVersion = DwarfVersionNum(Value);
  2650. if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
  2651. CmdArgs.push_back(Value.data());
  2652. } else {
  2653. RenderDebugEnablingArgs(Args, CmdArgs,
  2654. codegenoptions::LimitedDebugInfo,
  2655. DwarfVersion, llvm::DebuggerKind::Default);
  2656. }
  2657. } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
  2658. Value.startswith("-mhwdiv") || Value.startswith("-march")) {
  2659. // Do nothing, we'll validate it later.
  2660. } else {
  2661. D.Diag(diag::err_drv_unsupported_option_argument)
  2662. << A->getOption().getName() << Value;
  2663. }
  2664. }
  2665. }
  2666. if (CompressDebugSections) {
  2667. if (llvm::zlib::isAvailable())
  2668. CmdArgs.push_back("-compress-debug-sections");
  2669. else
  2670. D.Diag(diag::warn_debug_compression_unavailable);
  2671. }
  2672. if (UseRelaxRelocations)
  2673. CmdArgs.push_back("--mrelax-relocations");
  2674. if (MipsTargetFeature != nullptr) {
  2675. CmdArgs.push_back("-target-feature");
  2676. CmdArgs.push_back(MipsTargetFeature);
  2677. }
  2678. }
  2679. // This adds the static libclang_rt.builtins-arch.a directly to the command line
  2680. // FIXME: Make sure we can also emit shared objects if they're requested
  2681. // and available, check for possible errors, etc.
  2682. static void addClangRT(const ToolChain &TC, const ArgList &Args,
  2683. ArgStringList &CmdArgs) {
  2684. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
  2685. }
  2686. static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
  2687. const ArgList &Args) {
  2688. if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  2689. options::OPT_fno_openmp, false))
  2690. return;
  2691. switch (TC.getDriver().getOpenMPRuntime(Args)) {
  2692. case Driver::OMPRT_OMP:
  2693. CmdArgs.push_back("-lomp");
  2694. break;
  2695. case Driver::OMPRT_GOMP:
  2696. CmdArgs.push_back("-lgomp");
  2697. break;
  2698. case Driver::OMPRT_IOMP5:
  2699. CmdArgs.push_back("-liomp5");
  2700. break;
  2701. case Driver::OMPRT_Unknown:
  2702. // Already diagnosed.
  2703. break;
  2704. }
  2705. }
  2706. static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
  2707. ArgStringList &CmdArgs, StringRef Sanitizer,
  2708. bool IsShared, bool IsWhole) {
  2709. // Wrap any static runtimes that must be forced into executable in
  2710. // whole-archive.
  2711. if (IsWhole) CmdArgs.push_back("-whole-archive");
  2712. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
  2713. if (IsWhole) CmdArgs.push_back("-no-whole-archive");
  2714. }
  2715. // Tries to use a file with the list of dynamic symbols that need to be exported
  2716. // from the runtime library. Returns true if the file was found.
  2717. static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
  2718. ArgStringList &CmdArgs,
  2719. StringRef Sanitizer) {
  2720. SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
  2721. if (llvm::sys::fs::exists(SanRT + ".syms")) {
  2722. CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
  2723. return true;
  2724. }
  2725. return false;
  2726. }
  2727. static void linkSanitizerRuntimeDeps(const ToolChain &TC,
  2728. ArgStringList &CmdArgs) {
  2729. // Force linking against the system libraries sanitizers depends on
  2730. // (see PR15823 why this is necessary).
  2731. CmdArgs.push_back("--no-as-needed");
  2732. // There's no libpthread or librt on RTEMS.
  2733. if (TC.getTriple().getOS() != llvm::Triple::RTEMS) {
  2734. CmdArgs.push_back("-lpthread");
  2735. CmdArgs.push_back("-lrt");
  2736. }
  2737. CmdArgs.push_back("-lm");
  2738. // There's no libdl on FreeBSD or RTEMS.
  2739. if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
  2740. TC.getTriple().getOS() != llvm::Triple::RTEMS)
  2741. CmdArgs.push_back("-ldl");
  2742. }
  2743. static void
  2744. collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2745. SmallVectorImpl<StringRef> &SharedRuntimes,
  2746. SmallVectorImpl<StringRef> &StaticRuntimes,
  2747. SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
  2748. SmallVectorImpl<StringRef> &HelperStaticRuntimes,
  2749. SmallVectorImpl<StringRef> &RequiredSymbols) {
  2750. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  2751. // Collect shared runtimes.
  2752. if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
  2753. SharedRuntimes.push_back("asan");
  2754. }
  2755. // The stats_client library is also statically linked into DSOs.
  2756. if (SanArgs.needsStatsRt())
  2757. StaticRuntimes.push_back("stats_client");
  2758. // Collect static runtimes.
  2759. if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
  2760. // Don't link static runtimes into DSOs or if compiling for Android.
  2761. return;
  2762. }
  2763. if (SanArgs.needsAsanRt()) {
  2764. if (SanArgs.needsSharedAsanRt()) {
  2765. HelperStaticRuntimes.push_back("asan-preinit");
  2766. } else {
  2767. StaticRuntimes.push_back("asan");
  2768. if (SanArgs.linkCXXRuntimes())
  2769. StaticRuntimes.push_back("asan_cxx");
  2770. }
  2771. }
  2772. if (SanArgs.needsDfsanRt())
  2773. StaticRuntimes.push_back("dfsan");
  2774. if (SanArgs.needsLsanRt())
  2775. StaticRuntimes.push_back("lsan");
  2776. if (SanArgs.needsMsanRt()) {
  2777. StaticRuntimes.push_back("msan");
  2778. if (SanArgs.linkCXXRuntimes())
  2779. StaticRuntimes.push_back("msan_cxx");
  2780. }
  2781. if (SanArgs.needsTsanRt()) {
  2782. StaticRuntimes.push_back("tsan");
  2783. if (SanArgs.linkCXXRuntimes())
  2784. StaticRuntimes.push_back("tsan_cxx");
  2785. }
  2786. if (SanArgs.needsUbsanRt()) {
  2787. StaticRuntimes.push_back("ubsan_standalone");
  2788. if (SanArgs.linkCXXRuntimes())
  2789. StaticRuntimes.push_back("ubsan_standalone_cxx");
  2790. }
  2791. if (SanArgs.needsSafeStackRt())
  2792. StaticRuntimes.push_back("safestack");
  2793. if (SanArgs.needsCfiRt())
  2794. StaticRuntimes.push_back("cfi");
  2795. if (SanArgs.needsCfiDiagRt()) {
  2796. StaticRuntimes.push_back("cfi_diag");
  2797. if (SanArgs.linkCXXRuntimes())
  2798. StaticRuntimes.push_back("ubsan_standalone_cxx");
  2799. }
  2800. if (SanArgs.needsStatsRt()) {
  2801. NonWholeStaticRuntimes.push_back("stats");
  2802. RequiredSymbols.push_back("__sanitizer_stats_register");
  2803. }
  2804. if (SanArgs.needsEsanRt())
  2805. StaticRuntimes.push_back("esan");
  2806. }
  2807. // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
  2808. // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
  2809. static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2810. ArgStringList &CmdArgs) {
  2811. SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
  2812. NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
  2813. collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
  2814. NonWholeStaticRuntimes, HelperStaticRuntimes,
  2815. RequiredSymbols);
  2816. for (auto RT : SharedRuntimes)
  2817. addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
  2818. for (auto RT : HelperStaticRuntimes)
  2819. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  2820. bool AddExportDynamic = false;
  2821. for (auto RT : StaticRuntimes) {
  2822. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  2823. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  2824. }
  2825. for (auto RT : NonWholeStaticRuntimes) {
  2826. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
  2827. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  2828. }
  2829. for (auto S : RequiredSymbols) {
  2830. CmdArgs.push_back("-u");
  2831. CmdArgs.push_back(Args.MakeArgString(S));
  2832. }
  2833. // If there is a static runtime with no dynamic list, force all the symbols
  2834. // to be dynamic to be sure we export sanitizer interface functions.
  2835. if (AddExportDynamic)
  2836. CmdArgs.push_back("-export-dynamic");
  2837. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  2838. if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
  2839. CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
  2840. return !StaticRuntimes.empty();
  2841. }
  2842. static bool addXRayRuntime(const ToolChain &TC, const ArgList &Args,
  2843. ArgStringList &CmdArgs) {
  2844. if (Args.hasFlag(options::OPT_fxray_instrument,
  2845. options::OPT_fnoxray_instrument, false)) {
  2846. CmdArgs.push_back("-whole-archive");
  2847. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray", false));
  2848. CmdArgs.push_back("-no-whole-archive");
  2849. return true;
  2850. }
  2851. return false;
  2852. }
  2853. static void linkXRayRuntimeDeps(const ToolChain &TC, const ArgList &Args,
  2854. ArgStringList &CmdArgs) {
  2855. CmdArgs.push_back("--no-as-needed");
  2856. CmdArgs.push_back("-lpthread");
  2857. CmdArgs.push_back("-lrt");
  2858. CmdArgs.push_back("-lm");
  2859. CmdArgs.push_back("-latomic");
  2860. if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  2861. CmdArgs.push_back("-lc++");
  2862. else
  2863. CmdArgs.push_back("-lstdc++");
  2864. if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
  2865. CmdArgs.push_back("-ldl");
  2866. }
  2867. static bool areOptimizationsEnabled(const ArgList &Args) {
  2868. // Find the last -O arg and see if it is non-zero.
  2869. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2870. return !A->getOption().matches(options::OPT_O0);
  2871. // Defaults to -O0.
  2872. return false;
  2873. }
  2874. static bool mustUseFramePointerForTarget(const llvm::Triple &Triple) {
  2875. switch (Triple.getArch()){
  2876. default:
  2877. return false;
  2878. case llvm::Triple::arm:
  2879. case llvm::Triple::thumb:
  2880. // ARM Darwin targets require a frame pointer to be always present to aid
  2881. // offline debugging via backtraces.
  2882. return Triple.isOSDarwin();
  2883. }
  2884. }
  2885. static bool useFramePointerForTargetByDefault(const ArgList &Args,
  2886. const llvm::Triple &Triple) {
  2887. switch (Triple.getArch()) {
  2888. case llvm::Triple::xcore:
  2889. case llvm::Triple::wasm32:
  2890. case llvm::Triple::wasm64:
  2891. // XCore never wants frame pointers, regardless of OS.
  2892. // WebAssembly never wants frame pointers.
  2893. return false;
  2894. default:
  2895. break;
  2896. }
  2897. if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI) {
  2898. switch (Triple.getArch()) {
  2899. // Don't use a frame pointer on linux if optimizing for certain targets.
  2900. case llvm::Triple::mips64:
  2901. case llvm::Triple::mips64el:
  2902. case llvm::Triple::mips:
  2903. case llvm::Triple::mipsel:
  2904. case llvm::Triple::systemz:
  2905. case llvm::Triple::x86:
  2906. case llvm::Triple::x86_64:
  2907. return !areOptimizationsEnabled(Args);
  2908. default:
  2909. return true;
  2910. }
  2911. }
  2912. if (Triple.isOSWindows()) {
  2913. switch (Triple.getArch()) {
  2914. case llvm::Triple::x86:
  2915. return !areOptimizationsEnabled(Args);
  2916. case llvm::Triple::x86_64:
  2917. return Triple.isOSBinFormatMachO();
  2918. case llvm::Triple::arm:
  2919. case llvm::Triple::thumb:
  2920. // Windows on ARM builds with FPO disabled to aid fast stack walking
  2921. return true;
  2922. default:
  2923. // All other supported Windows ISAs use xdata unwind information, so frame
  2924. // pointers are not generally useful.
  2925. return false;
  2926. }
  2927. }
  2928. return true;
  2929. }
  2930. static bool shouldUseFramePointer(const ArgList &Args,
  2931. const llvm::Triple &Triple) {
  2932. if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
  2933. options::OPT_fomit_frame_pointer))
  2934. return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
  2935. mustUseFramePointerForTarget(Triple);
  2936. if (Args.hasArg(options::OPT_pg))
  2937. return true;
  2938. return useFramePointerForTargetByDefault(Args, Triple);
  2939. }
  2940. static bool shouldUseLeafFramePointer(const ArgList &Args,
  2941. const llvm::Triple &Triple) {
  2942. if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
  2943. options::OPT_momit_leaf_frame_pointer))
  2944. return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer) ||
  2945. mustUseFramePointerForTarget(Triple);
  2946. if (Args.hasArg(options::OPT_pg))
  2947. return true;
  2948. if (Triple.isPS4CPU())
  2949. return false;
  2950. return useFramePointerForTargetByDefault(Args, Triple);
  2951. }
  2952. /// Add a CC1 option to specify the debug compilation directory.
  2953. static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
  2954. SmallString<128> cwd;
  2955. if (!llvm::sys::fs::current_path(cwd)) {
  2956. CmdArgs.push_back("-fdebug-compilation-dir");
  2957. CmdArgs.push_back(Args.MakeArgString(cwd));
  2958. }
  2959. }
  2960. static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
  2961. Arg *FinalOutput = Args.getLastArg(options::OPT_o);
  2962. if (FinalOutput && Args.hasArg(options::OPT_c)) {
  2963. SmallString<128> T(FinalOutput->getValue());
  2964. llvm::sys::path::replace_extension(T, "dwo");
  2965. return Args.MakeArgString(T);
  2966. } else {
  2967. // Use the compilation dir.
  2968. SmallString<128> T(
  2969. Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
  2970. SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
  2971. llvm::sys::path::replace_extension(F, "dwo");
  2972. T += F;
  2973. return Args.MakeArgString(F);
  2974. }
  2975. }
  2976. static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
  2977. const JobAction &JA, const ArgList &Args,
  2978. const InputInfo &Output, const char *OutFile) {
  2979. ArgStringList ExtractArgs;
  2980. ExtractArgs.push_back("--extract-dwo");
  2981. ArgStringList StripArgs;
  2982. StripArgs.push_back("--strip-dwo");
  2983. // Grabbing the output of the earlier compile step.
  2984. StripArgs.push_back(Output.getFilename());
  2985. ExtractArgs.push_back(Output.getFilename());
  2986. ExtractArgs.push_back(OutFile);
  2987. const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
  2988. InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
  2989. // First extract the dwo sections.
  2990. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
  2991. // Then remove them from the original .o file.
  2992. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
  2993. }
  2994. /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
  2995. /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
  2996. static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
  2997. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  2998. if (A->getOption().matches(options::OPT_O4) ||
  2999. A->getOption().matches(options::OPT_Ofast))
  3000. return true;
  3001. if (A->getOption().matches(options::OPT_O0))
  3002. return false;
  3003. assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
  3004. // Vectorize -Os.
  3005. StringRef S(A->getValue());
  3006. if (S == "s")
  3007. return true;
  3008. // Don't vectorize -Oz, unless it's the slp vectorizer.
  3009. if (S == "z")
  3010. return isSlpVec;
  3011. unsigned OptLevel = 0;
  3012. if (S.getAsInteger(10, OptLevel))
  3013. return false;
  3014. return OptLevel > 1;
  3015. }
  3016. return false;
  3017. }
  3018. /// Add -x lang to \p CmdArgs for \p Input.
  3019. static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
  3020. ArgStringList &CmdArgs) {
  3021. // When using -verify-pch, we don't want to provide the type
  3022. // 'precompiled-header' if it was inferred from the file extension
  3023. if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
  3024. return;
  3025. CmdArgs.push_back("-x");
  3026. if (Args.hasArg(options::OPT_rewrite_objc))
  3027. CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
  3028. else
  3029. CmdArgs.push_back(types::getTypeName(Input.getType()));
  3030. }
  3031. static VersionTuple getMSCompatibilityVersion(unsigned Version) {
  3032. if (Version < 100)
  3033. return VersionTuple(Version);
  3034. if (Version < 10000)
  3035. return VersionTuple(Version / 100, Version % 100);
  3036. unsigned Build = 0, Factor = 1;
  3037. for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
  3038. Build = Build + (Version % 10) * Factor;
  3039. return VersionTuple(Version / 100, Version % 100, Build);
  3040. }
  3041. // Claim options we don't want to warn if they are unused. We do this for
  3042. // options that build systems might add but are unused when assembling or only
  3043. // running the preprocessor for example.
  3044. static void claimNoWarnArgs(const ArgList &Args) {
  3045. // Don't warn about unused -f(no-)?lto. This can happen when we're
  3046. // preprocessing, precompiling or assembling.
  3047. Args.ClaimAllArgs(options::OPT_flto_EQ);
  3048. Args.ClaimAllArgs(options::OPT_flto);
  3049. Args.ClaimAllArgs(options::OPT_fno_lto);
  3050. }
  3051. static void appendUserToPath(SmallVectorImpl<char> &Result) {
  3052. #ifdef LLVM_ON_UNIX
  3053. const char *Username = getenv("LOGNAME");
  3054. #else
  3055. const char *Username = getenv("USERNAME");
  3056. #endif
  3057. if (Username) {
  3058. // Validate that LoginName can be used in a path, and get its length.
  3059. size_t Len = 0;
  3060. for (const char *P = Username; *P; ++P, ++Len) {
  3061. if (!isAlphanumeric(*P) && *P != '_') {
  3062. Username = nullptr;
  3063. break;
  3064. }
  3065. }
  3066. if (Username && Len > 0) {
  3067. Result.append(Username, Username + Len);
  3068. return;
  3069. }
  3070. }
  3071. // Fallback to user id.
  3072. #ifdef LLVM_ON_UNIX
  3073. std::string UID = llvm::utostr(getuid());
  3074. #else
  3075. // FIXME: Windows seems to have an 'SID' that might work.
  3076. std::string UID = "9999";
  3077. #endif
  3078. Result.append(UID.begin(), UID.end());
  3079. }
  3080. VersionTuple visualstudio::getMSVCVersion(const Driver *D, const ToolChain &TC,
  3081. const llvm::Triple &Triple,
  3082. const llvm::opt::ArgList &Args,
  3083. bool IsWindowsMSVC) {
  3084. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  3085. IsWindowsMSVC) ||
  3086. Args.hasArg(options::OPT_fmsc_version) ||
  3087. Args.hasArg(options::OPT_fms_compatibility_version)) {
  3088. const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
  3089. const Arg *MSCompatibilityVersion =
  3090. Args.getLastArg(options::OPT_fms_compatibility_version);
  3091. if (MSCVersion && MSCompatibilityVersion) {
  3092. if (D)
  3093. D->Diag(diag::err_drv_argument_not_allowed_with)
  3094. << MSCVersion->getAsString(Args)
  3095. << MSCompatibilityVersion->getAsString(Args);
  3096. return VersionTuple();
  3097. }
  3098. if (MSCompatibilityVersion) {
  3099. VersionTuple MSVT;
  3100. if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
  3101. D->Diag(diag::err_drv_invalid_value)
  3102. << MSCompatibilityVersion->getAsString(Args)
  3103. << MSCompatibilityVersion->getValue();
  3104. return MSVT;
  3105. }
  3106. if (MSCVersion) {
  3107. unsigned Version = 0;
  3108. if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
  3109. D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
  3110. << MSCVersion->getValue();
  3111. return getMSCompatibilityVersion(Version);
  3112. }
  3113. unsigned Major, Minor, Micro;
  3114. Triple.getEnvironmentVersion(Major, Minor, Micro);
  3115. if (Major || Minor || Micro)
  3116. return VersionTuple(Major, Minor, Micro);
  3117. if (IsWindowsMSVC) {
  3118. VersionTuple MSVT = TC.getMSVCVersionFromExe();
  3119. if (!MSVT.empty())
  3120. return MSVT;
  3121. // FIXME: Consider bumping this to 19 (MSVC2015) soon.
  3122. return VersionTuple(18);
  3123. }
  3124. }
  3125. return VersionTuple();
  3126. }
  3127. static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
  3128. const InputInfo &Output, const ArgList &Args,
  3129. ArgStringList &CmdArgs) {
  3130. auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
  3131. options::OPT_fprofile_generate_EQ,
  3132. options::OPT_fno_profile_generate);
  3133. if (PGOGenerateArg &&
  3134. PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
  3135. PGOGenerateArg = nullptr;
  3136. auto *ProfileGenerateArg = Args.getLastArg(
  3137. options::OPT_fprofile_instr_generate,
  3138. options::OPT_fprofile_instr_generate_EQ,
  3139. options::OPT_fno_profile_instr_generate);
  3140. if (ProfileGenerateArg &&
  3141. ProfileGenerateArg->getOption().matches(
  3142. options::OPT_fno_profile_instr_generate))
  3143. ProfileGenerateArg = nullptr;
  3144. if (PGOGenerateArg && ProfileGenerateArg)
  3145. D.Diag(diag::err_drv_argument_not_allowed_with)
  3146. << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
  3147. auto *ProfileUseArg = Args.getLastArg(
  3148. options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
  3149. options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
  3150. options::OPT_fno_profile_instr_use);
  3151. if (ProfileUseArg &&
  3152. ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
  3153. ProfileUseArg = nullptr;
  3154. if (PGOGenerateArg && ProfileUseArg)
  3155. D.Diag(diag::err_drv_argument_not_allowed_with)
  3156. << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
  3157. if (ProfileGenerateArg && ProfileUseArg)
  3158. D.Diag(diag::err_drv_argument_not_allowed_with)
  3159. << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
  3160. if (ProfileGenerateArg) {
  3161. if (ProfileGenerateArg->getOption().matches(
  3162. options::OPT_fprofile_instr_generate_EQ))
  3163. CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
  3164. ProfileGenerateArg->getValue()));
  3165. // The default is to use Clang Instrumentation.
  3166. CmdArgs.push_back("-fprofile-instrument=clang");
  3167. }
  3168. if (PGOGenerateArg) {
  3169. CmdArgs.push_back("-fprofile-instrument=llvm");
  3170. if (PGOGenerateArg->getOption().matches(
  3171. options::OPT_fprofile_generate_EQ)) {
  3172. SmallString<128> Path(PGOGenerateArg->getValue());
  3173. llvm::sys::path::append(Path, "default_%m.profraw");
  3174. CmdArgs.push_back(
  3175. Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
  3176. }
  3177. }
  3178. if (ProfileUseArg) {
  3179. if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
  3180. CmdArgs.push_back(Args.MakeArgString(
  3181. Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
  3182. else if ((ProfileUseArg->getOption().matches(
  3183. options::OPT_fprofile_use_EQ) ||
  3184. ProfileUseArg->getOption().matches(
  3185. options::OPT_fprofile_instr_use))) {
  3186. SmallString<128> Path(
  3187. ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
  3188. if (Path.empty() || llvm::sys::fs::is_directory(Path))
  3189. llvm::sys::path::append(Path, "default.profdata");
  3190. CmdArgs.push_back(
  3191. Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
  3192. }
  3193. }
  3194. if (Args.hasArg(options::OPT_ftest_coverage) ||
  3195. Args.hasArg(options::OPT_coverage))
  3196. CmdArgs.push_back("-femit-coverage-notes");
  3197. if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  3198. false) ||
  3199. Args.hasArg(options::OPT_coverage))
  3200. CmdArgs.push_back("-femit-coverage-data");
  3201. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  3202. options::OPT_fno_coverage_mapping, false) &&
  3203. !ProfileGenerateArg)
  3204. D.Diag(diag::err_drv_argument_only_allowed_with)
  3205. << "-fcoverage-mapping"
  3206. << "-fprofile-instr-generate";
  3207. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  3208. options::OPT_fno_coverage_mapping, false))
  3209. CmdArgs.push_back("-fcoverage-mapping");
  3210. if (C.getArgs().hasArg(options::OPT_c) ||
  3211. C.getArgs().hasArg(options::OPT_S)) {
  3212. if (Output.isFilename()) {
  3213. CmdArgs.push_back("-coverage-notes-file");
  3214. SmallString<128> OutputFilename;
  3215. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
  3216. OutputFilename = FinalOutput->getValue();
  3217. else
  3218. OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
  3219. SmallString<128> CoverageFilename = OutputFilename;
  3220. if (llvm::sys::path::is_relative(CoverageFilename)) {
  3221. SmallString<128> Pwd;
  3222. if (!llvm::sys::fs::current_path(Pwd)) {
  3223. llvm::sys::path::append(Pwd, CoverageFilename);
  3224. CoverageFilename.swap(Pwd);
  3225. }
  3226. }
  3227. llvm::sys::path::replace_extension(CoverageFilename, "gcno");
  3228. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  3229. // Leave -fprofile-dir= an unused argument unless .gcda emission is
  3230. // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
  3231. // the flag used. There is no -fno-profile-dir, so the user has no
  3232. // targeted way to suppress the warning.
  3233. if (Args.hasArg(options::OPT_fprofile_arcs) ||
  3234. Args.hasArg(options::OPT_coverage)) {
  3235. CmdArgs.push_back("-coverage-data-file");
  3236. if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
  3237. CoverageFilename = FProfileDir->getValue();
  3238. llvm::sys::path::append(CoverageFilename, OutputFilename);
  3239. }
  3240. llvm::sys::path::replace_extension(CoverageFilename, "gcda");
  3241. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  3242. }
  3243. }
  3244. }
  3245. }
  3246. static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
  3247. ArgStringList &CmdArgs) {
  3248. if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  3249. false) ||
  3250. Args.hasFlag(options::OPT_fprofile_generate,
  3251. options::OPT_fno_profile_instr_generate, false) ||
  3252. Args.hasFlag(options::OPT_fprofile_generate_EQ,
  3253. options::OPT_fno_profile_instr_generate, false) ||
  3254. Args.hasFlag(options::OPT_fprofile_instr_generate,
  3255. options::OPT_fno_profile_instr_generate, false) ||
  3256. Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
  3257. options::OPT_fno_profile_instr_generate, false) ||
  3258. Args.hasArg(options::OPT_fcreate_profile) ||
  3259. Args.hasArg(options::OPT_coverage)))
  3260. CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
  3261. }
  3262. /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
  3263. /// smooshes them together with platform defaults, to decide whether
  3264. /// this compile should be using PIC mode or not. Returns a tuple of
  3265. /// (RelocationModel, PICLevel, IsPIE).
  3266. static std::tuple<llvm::Reloc::Model, unsigned, bool>
  3267. ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
  3268. const ArgList &Args) {
  3269. // FIXME: why does this code...and so much everywhere else, use both
  3270. // ToolChain.getTriple() and Triple?
  3271. bool PIE = ToolChain.isPIEDefault();
  3272. bool PIC = PIE || ToolChain.isPICDefault();
  3273. // The Darwin/MachO default to use PIC does not apply when using -static.
  3274. if (ToolChain.getTriple().isOSBinFormatMachO() &&
  3275. Args.hasArg(options::OPT_static))
  3276. PIE = PIC = false;
  3277. bool IsPICLevelTwo = PIC;
  3278. bool KernelOrKext =
  3279. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  3280. // Android-specific defaults for PIC/PIE
  3281. if (ToolChain.getTriple().isAndroid()) {
  3282. switch (ToolChain.getArch()) {
  3283. case llvm::Triple::arm:
  3284. case llvm::Triple::armeb:
  3285. case llvm::Triple::thumb:
  3286. case llvm::Triple::thumbeb:
  3287. case llvm::Triple::aarch64:
  3288. case llvm::Triple::mips:
  3289. case llvm::Triple::mipsel:
  3290. case llvm::Triple::mips64:
  3291. case llvm::Triple::mips64el:
  3292. PIC = true; // "-fpic"
  3293. break;
  3294. case llvm::Triple::x86:
  3295. case llvm::Triple::x86_64:
  3296. PIC = true; // "-fPIC"
  3297. IsPICLevelTwo = true;
  3298. break;
  3299. default:
  3300. break;
  3301. }
  3302. }
  3303. // OpenBSD-specific defaults for PIE
  3304. if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
  3305. switch (ToolChain.getArch()) {
  3306. case llvm::Triple::mips64:
  3307. case llvm::Triple::mips64el:
  3308. case llvm::Triple::sparcel:
  3309. case llvm::Triple::x86:
  3310. case llvm::Triple::x86_64:
  3311. IsPICLevelTwo = false; // "-fpie"
  3312. break;
  3313. case llvm::Triple::ppc:
  3314. case llvm::Triple::sparc:
  3315. case llvm::Triple::sparcv9:
  3316. IsPICLevelTwo = true; // "-fPIE"
  3317. break;
  3318. default:
  3319. break;
  3320. }
  3321. }
  3322. // The last argument relating to either PIC or PIE wins, and no
  3323. // other argument is used. If the last argument is any flavor of the
  3324. // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
  3325. // option implicitly enables PIC at the same level.
  3326. Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
  3327. options::OPT_fpic, options::OPT_fno_pic,
  3328. options::OPT_fPIE, options::OPT_fno_PIE,
  3329. options::OPT_fpie, options::OPT_fno_pie);
  3330. // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
  3331. // is forced, then neither PIC nor PIE flags will have no effect.
  3332. if (!ToolChain.isPICDefaultForced()) {
  3333. if (LastPICArg) {
  3334. Option O = LastPICArg->getOption();
  3335. if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
  3336. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
  3337. PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
  3338. PIC =
  3339. PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
  3340. IsPICLevelTwo =
  3341. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
  3342. } else {
  3343. PIE = PIC = false;
  3344. if (Triple.isPS4CPU()) {
  3345. Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
  3346. StringRef Model = ModelArg ? ModelArg->getValue() : "";
  3347. if (Model != "kernel") {
  3348. PIC = true;
  3349. ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
  3350. << LastPICArg->getSpelling();
  3351. }
  3352. }
  3353. }
  3354. }
  3355. }
  3356. // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
  3357. // PIC level would've been set to level 1, force it back to level 2 PIC
  3358. // instead.
  3359. if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
  3360. IsPICLevelTwo |= ToolChain.isPICDefault();
  3361. // This kernel flags are a trump-card: they will disable PIC/PIE
  3362. // generation, independent of the argument order.
  3363. if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  3364. !Triple.isWatchOS()))
  3365. PIC = PIE = false;
  3366. if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
  3367. // This is a very special mode. It trumps the other modes, almost no one
  3368. // uses it, and it isn't even valid on any OS but Darwin.
  3369. if (!ToolChain.getTriple().isOSDarwin())
  3370. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  3371. << A->getSpelling() << ToolChain.getTriple().str();
  3372. // FIXME: Warn when this flag trumps some other PIC or PIE flag.
  3373. // Only a forced PIC mode can cause the actual compile to have PIC defines
  3374. // etc., no flags are sufficient. This behavior was selected to closely
  3375. // match that of llvm-gcc and Apple GCC before that.
  3376. PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
  3377. return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
  3378. }
  3379. bool EmbeddedPISupported;
  3380. switch (ToolChain.getArch()) {
  3381. case llvm::Triple::arm:
  3382. case llvm::Triple::armeb:
  3383. case llvm::Triple::thumb:
  3384. case llvm::Triple::thumbeb:
  3385. EmbeddedPISupported = true;
  3386. break;
  3387. default:
  3388. EmbeddedPISupported = false;
  3389. break;
  3390. }
  3391. bool ROPI = false, RWPI = false;
  3392. Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
  3393. if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
  3394. if (!EmbeddedPISupported)
  3395. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  3396. << LastROPIArg->getSpelling() << ToolChain.getTriple().str();
  3397. ROPI = true;
  3398. }
  3399. Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
  3400. if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
  3401. if (!EmbeddedPISupported)
  3402. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  3403. << LastRWPIArg->getSpelling() << ToolChain.getTriple().str();
  3404. RWPI = true;
  3405. }
  3406. // ROPI and RWPI are not comaptible with PIC or PIE.
  3407. if ((ROPI || RWPI) && (PIC || PIE)) {
  3408. ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
  3409. }
  3410. if (PIC)
  3411. return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
  3412. llvm::Reloc::Model RelocM = llvm::Reloc::Static;
  3413. if (ROPI && RWPI)
  3414. RelocM = llvm::Reloc::ROPI_RWPI;
  3415. else if (ROPI)
  3416. RelocM = llvm::Reloc::ROPI;
  3417. else if (RWPI)
  3418. RelocM = llvm::Reloc::RWPI;
  3419. return std::make_tuple(RelocM, 0U, false);
  3420. }
  3421. static const char *RelocationModelName(llvm::Reloc::Model Model) {
  3422. switch (Model) {
  3423. case llvm::Reloc::Static:
  3424. return "static";
  3425. case llvm::Reloc::PIC_:
  3426. return "pic";
  3427. case llvm::Reloc::DynamicNoPIC:
  3428. return "dynamic-no-pic";
  3429. case llvm::Reloc::ROPI:
  3430. return "ropi";
  3431. case llvm::Reloc::RWPI:
  3432. return "rwpi";
  3433. case llvm::Reloc::ROPI_RWPI:
  3434. return "ropi-rwpi";
  3435. }
  3436. llvm_unreachable("Unknown Reloc::Model kind");
  3437. }
  3438. static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
  3439. ArgStringList &CmdArgs) {
  3440. llvm::Reloc::Model RelocationModel;
  3441. unsigned PICLevel;
  3442. bool IsPIE;
  3443. std::tie(RelocationModel, PICLevel, IsPIE) =
  3444. ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
  3445. if (RelocationModel != llvm::Reloc::Static)
  3446. CmdArgs.push_back("-KPIC");
  3447. }
  3448. void Clang::ConstructJob(Compilation &C, const JobAction &JA,
  3449. const InputInfo &Output, const InputInfoList &Inputs,
  3450. const ArgList &Args, const char *LinkingOutput) const {
  3451. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  3452. const std::string &TripleStr = Triple.getTriple();
  3453. bool KernelOrKext =
  3454. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  3455. const Driver &D = getToolChain().getDriver();
  3456. ArgStringList CmdArgs;
  3457. bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
  3458. bool IsWindowsCygnus =
  3459. getToolChain().getTriple().isWindowsCygwinEnvironment();
  3460. bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
  3461. bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
  3462. bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
  3463. // Check number of inputs for sanity. We need at least one input.
  3464. assert(Inputs.size() >= 1 && "Must have at least one input.");
  3465. const InputInfo &Input = Inputs[0];
  3466. // CUDA compilation may have multiple inputs (source file + results of
  3467. // device-side compilations). All other jobs are expected to have exactly one
  3468. // input.
  3469. bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
  3470. assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
  3471. // C++ is not supported for IAMCU.
  3472. if (IsIAMCU && types::isCXX(Input.getType()))
  3473. D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
  3474. // Invoke ourselves in -cc1 mode.
  3475. //
  3476. // FIXME: Implement custom jobs for internal actions.
  3477. CmdArgs.push_back("-cc1");
  3478. // Add the "effective" target triple.
  3479. CmdArgs.push_back("-triple");
  3480. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  3481. if (IsCuda) {
  3482. // We have to pass the triple of the host if compiling for a CUDA device and
  3483. // vice-versa.
  3484. std::string NormalizedTriple;
  3485. if (JA.isDeviceOffloading(Action::OFK_Cuda))
  3486. NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
  3487. ->getTriple()
  3488. .normalize();
  3489. else
  3490. NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Cuda>()
  3491. ->getTriple()
  3492. .normalize();
  3493. CmdArgs.push_back("-aux-triple");
  3494. CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
  3495. }
  3496. if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
  3497. Triple.getArch() == llvm::Triple::thumb)) {
  3498. unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
  3499. unsigned Version;
  3500. Triple.getArchName().substr(Offset).getAsInteger(10, Version);
  3501. if (Version < 7)
  3502. D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
  3503. << TripleStr;
  3504. }
  3505. // Push all default warning arguments that are specific to
  3506. // the given target. These come before user provided warning options
  3507. // are provided.
  3508. getToolChain().addClangWarningOptions(CmdArgs);
  3509. // Select the appropriate action.
  3510. RewriteKind rewriteKind = RK_None;
  3511. if (isa<AnalyzeJobAction>(JA)) {
  3512. assert(JA.getType() == types::TY_Plist && "Invalid output type.");
  3513. CmdArgs.push_back("-analyze");
  3514. } else if (isa<MigrateJobAction>(JA)) {
  3515. CmdArgs.push_back("-migrate");
  3516. } else if (isa<PreprocessJobAction>(JA)) {
  3517. if (Output.getType() == types::TY_Dependencies)
  3518. CmdArgs.push_back("-Eonly");
  3519. else {
  3520. CmdArgs.push_back("-E");
  3521. if (Args.hasArg(options::OPT_rewrite_objc) &&
  3522. !Args.hasArg(options::OPT_g_Group))
  3523. CmdArgs.push_back("-P");
  3524. }
  3525. } else if (isa<AssembleJobAction>(JA)) {
  3526. CmdArgs.push_back("-emit-obj");
  3527. CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
  3528. // Also ignore explicit -force_cpusubtype_ALL option.
  3529. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  3530. } else if (isa<PrecompileJobAction>(JA)) {
  3531. // Use PCH if the user requested it.
  3532. bool UsePCH = D.CCCUsePCH;
  3533. if (JA.getType() == types::TY_Nothing)
  3534. CmdArgs.push_back("-fsyntax-only");
  3535. else if (JA.getType() == types::TY_ModuleFile)
  3536. CmdArgs.push_back("-emit-module-interface");
  3537. else if (UsePCH)
  3538. CmdArgs.push_back("-emit-pch");
  3539. else
  3540. CmdArgs.push_back("-emit-pth");
  3541. } else if (isa<VerifyPCHJobAction>(JA)) {
  3542. CmdArgs.push_back("-verify-pch");
  3543. } else {
  3544. assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
  3545. "Invalid action for clang tool.");
  3546. if (JA.getType() == types::TY_Nothing) {
  3547. CmdArgs.push_back("-fsyntax-only");
  3548. } else if (JA.getType() == types::TY_LLVM_IR ||
  3549. JA.getType() == types::TY_LTO_IR) {
  3550. CmdArgs.push_back("-emit-llvm");
  3551. } else if (JA.getType() == types::TY_LLVM_BC ||
  3552. JA.getType() == types::TY_LTO_BC) {
  3553. CmdArgs.push_back("-emit-llvm-bc");
  3554. } else if (JA.getType() == types::TY_PP_Asm) {
  3555. CmdArgs.push_back("-S");
  3556. } else if (JA.getType() == types::TY_AST) {
  3557. CmdArgs.push_back("-emit-pch");
  3558. } else if (JA.getType() == types::TY_ModuleFile) {
  3559. CmdArgs.push_back("-module-file-info");
  3560. } else if (JA.getType() == types::TY_RewrittenObjC) {
  3561. CmdArgs.push_back("-rewrite-objc");
  3562. rewriteKind = RK_NonFragile;
  3563. } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
  3564. CmdArgs.push_back("-rewrite-objc");
  3565. rewriteKind = RK_Fragile;
  3566. } else {
  3567. assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
  3568. }
  3569. // Preserve use-list order by default when emitting bitcode, so that
  3570. // loading the bitcode up in 'opt' or 'llc' and running passes gives the
  3571. // same result as running passes here. For LTO, we don't need to preserve
  3572. // the use-list order, since serialization to bitcode is part of the flow.
  3573. if (JA.getType() == types::TY_LLVM_BC)
  3574. CmdArgs.push_back("-emit-llvm-uselists");
  3575. if (D.isUsingLTO())
  3576. Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
  3577. }
  3578. if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
  3579. if (!types::isLLVMIR(Input.getType()))
  3580. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  3581. << "-x ir";
  3582. Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
  3583. }
  3584. // Embed-bitcode option.
  3585. if (C.getDriver().embedBitcodeEnabled() &&
  3586. (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
  3587. // Add flags implied by -fembed-bitcode.
  3588. Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
  3589. // Disable all llvm IR level optimizations.
  3590. CmdArgs.push_back("-disable-llvm-optzns");
  3591. }
  3592. if (C.getDriver().embedBitcodeMarkerOnly())
  3593. CmdArgs.push_back("-fembed-bitcode=marker");
  3594. // We normally speed up the clang process a bit by skipping destructors at
  3595. // exit, but when we're generating diagnostics we can rely on some of the
  3596. // cleanup.
  3597. if (!C.isForDiagnostics())
  3598. CmdArgs.push_back("-disable-free");
  3599. // Disable the verification pass in -asserts builds.
  3600. #ifdef NDEBUG
  3601. CmdArgs.push_back("-disable-llvm-verifier");
  3602. // Discard LLVM value names in -asserts builds.
  3603. CmdArgs.push_back("-discard-value-names");
  3604. #endif
  3605. // Set the main file name, so that debug info works even with
  3606. // -save-temps.
  3607. CmdArgs.push_back("-main-file-name");
  3608. CmdArgs.push_back(getBaseInputName(Args, Input));
  3609. // Some flags which affect the language (via preprocessor
  3610. // defines).
  3611. if (Args.hasArg(options::OPT_static))
  3612. CmdArgs.push_back("-static-define");
  3613. if (isa<AnalyzeJobAction>(JA)) {
  3614. // Enable region store model by default.
  3615. CmdArgs.push_back("-analyzer-store=region");
  3616. // Treat blocks as analysis entry points.
  3617. CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
  3618. CmdArgs.push_back("-analyzer-eagerly-assume");
  3619. // Add default argument set.
  3620. if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
  3621. CmdArgs.push_back("-analyzer-checker=core");
  3622. if (!IsWindowsMSVC) {
  3623. CmdArgs.push_back("-analyzer-checker=unix");
  3624. } else {
  3625. // Enable "unix" checkers that also work on Windows.
  3626. CmdArgs.push_back("-analyzer-checker=unix.API");
  3627. CmdArgs.push_back("-analyzer-checker=unix.Malloc");
  3628. CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
  3629. CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
  3630. CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
  3631. CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
  3632. }
  3633. // Disable some unix checkers for PS4.
  3634. if (IsPS4CPU) {
  3635. CmdArgs.push_back("-analyzer-disable-checker=unix.API");
  3636. CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
  3637. }
  3638. if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
  3639. CmdArgs.push_back("-analyzer-checker=osx");
  3640. CmdArgs.push_back("-analyzer-checker=deadcode");
  3641. if (types::isCXX(Input.getType()))
  3642. CmdArgs.push_back("-analyzer-checker=cplusplus");
  3643. if (!IsPS4CPU) {
  3644. CmdArgs.push_back(
  3645. "-analyzer-checker=security.insecureAPI.UncheckedReturn");
  3646. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
  3647. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
  3648. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
  3649. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
  3650. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
  3651. }
  3652. // Default nullability checks.
  3653. CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
  3654. CmdArgs.push_back(
  3655. "-analyzer-checker=nullability.NullReturnedFromNonnull");
  3656. }
  3657. // Set the output format. The default is plist, for (lame) historical
  3658. // reasons.
  3659. CmdArgs.push_back("-analyzer-output");
  3660. if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
  3661. CmdArgs.push_back(A->getValue());
  3662. else
  3663. CmdArgs.push_back("plist");
  3664. // Disable the presentation of standard compiler warnings when
  3665. // using --analyze. We only want to show static analyzer diagnostics
  3666. // or frontend errors.
  3667. CmdArgs.push_back("-w");
  3668. // Add -Xanalyzer arguments when running as analyzer.
  3669. Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
  3670. }
  3671. CheckCodeGenerationOptions(D, Args);
  3672. llvm::Reloc::Model RelocationModel;
  3673. unsigned PICLevel;
  3674. bool IsPIE;
  3675. std::tie(RelocationModel, PICLevel, IsPIE) =
  3676. ParsePICArgs(getToolChain(), Triple, Args);
  3677. const char *RMName = RelocationModelName(RelocationModel);
  3678. if ((RelocationModel == llvm::Reloc::ROPI ||
  3679. RelocationModel == llvm::Reloc::ROPI_RWPI) &&
  3680. types::isCXX(Input.getType()) &&
  3681. !Args.hasArg(options::OPT_fallow_unsupported))
  3682. D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
  3683. if (RMName) {
  3684. CmdArgs.push_back("-mrelocation-model");
  3685. CmdArgs.push_back(RMName);
  3686. }
  3687. if (PICLevel > 0) {
  3688. CmdArgs.push_back("-pic-level");
  3689. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3690. if (IsPIE)
  3691. CmdArgs.push_back("-pic-is-pie");
  3692. }
  3693. if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
  3694. CmdArgs.push_back("-meabi");
  3695. CmdArgs.push_back(A->getValue());
  3696. }
  3697. CmdArgs.push_back("-mthread-model");
  3698. if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
  3699. CmdArgs.push_back(A->getValue());
  3700. else
  3701. CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
  3702. Args.AddLastArg(CmdArgs, options::OPT_fveclib);
  3703. if (!Args.hasFlag(options::OPT_fmerge_all_constants,
  3704. options::OPT_fno_merge_all_constants))
  3705. CmdArgs.push_back("-fno-merge-all-constants");
  3706. // LLVM Code Generator Options.
  3707. if (Args.hasArg(options::OPT_frewrite_map_file) ||
  3708. Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
  3709. for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
  3710. options::OPT_frewrite_map_file_EQ)) {
  3711. StringRef Map = A->getValue();
  3712. if (!llvm::sys::fs::exists(Map)) {
  3713. D.Diag(diag::err_drv_no_such_file) << Map;
  3714. } else {
  3715. CmdArgs.push_back("-frewrite-map-file");
  3716. CmdArgs.push_back(A->getValue());
  3717. A->claim();
  3718. }
  3719. }
  3720. }
  3721. if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
  3722. StringRef v = A->getValue();
  3723. CmdArgs.push_back("-mllvm");
  3724. CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
  3725. A->claim();
  3726. }
  3727. if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
  3728. true))
  3729. CmdArgs.push_back("-fno-jump-tables");
  3730. if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
  3731. options::OPT_fno_preserve_as_comments, true))
  3732. CmdArgs.push_back("-fno-preserve-as-comments");
  3733. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  3734. CmdArgs.push_back("-mregparm");
  3735. CmdArgs.push_back(A->getValue());
  3736. }
  3737. if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
  3738. options::OPT_freg_struct_return)) {
  3739. if (getToolChain().getArch() != llvm::Triple::x86) {
  3740. D.Diag(diag::err_drv_unsupported_opt_for_target)
  3741. << A->getSpelling() << getToolChain().getTriple().str();
  3742. } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
  3743. CmdArgs.push_back("-fpcc-struct-return");
  3744. } else {
  3745. assert(A->getOption().matches(options::OPT_freg_struct_return));
  3746. CmdArgs.push_back("-freg-struct-return");
  3747. }
  3748. }
  3749. if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
  3750. CmdArgs.push_back("-fdefault-calling-conv=stdcall");
  3751. if (shouldUseFramePointer(Args, getToolChain().getTriple()))
  3752. CmdArgs.push_back("-mdisable-fp-elim");
  3753. if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
  3754. options::OPT_fno_zero_initialized_in_bss))
  3755. CmdArgs.push_back("-mno-zero-initialized-in-bss");
  3756. bool OFastEnabled = isOptimizationLevelFast(Args);
  3757. // If -Ofast is the optimization level, then -fstrict-aliasing should be
  3758. // enabled. This alias option is being used to simplify the hasFlag logic.
  3759. OptSpecifier StrictAliasingAliasOption =
  3760. OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
  3761. // We turn strict aliasing off by default if we're in CL mode, since MSVC
  3762. // doesn't do any TBAA.
  3763. bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
  3764. if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
  3765. options::OPT_fno_strict_aliasing, TBAAOnByDefault))
  3766. CmdArgs.push_back("-relaxed-aliasing");
  3767. if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
  3768. options::OPT_fno_struct_path_tbaa))
  3769. CmdArgs.push_back("-no-struct-path-tbaa");
  3770. if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
  3771. false))
  3772. CmdArgs.push_back("-fstrict-enums");
  3773. if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
  3774. options::OPT_fno_strict_vtable_pointers,
  3775. false))
  3776. CmdArgs.push_back("-fstrict-vtable-pointers");
  3777. if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
  3778. options::OPT_fno_optimize_sibling_calls))
  3779. CmdArgs.push_back("-mdisable-tail-calls");
  3780. // Handle segmented stacks.
  3781. if (Args.hasArg(options::OPT_fsplit_stack))
  3782. CmdArgs.push_back("-split-stacks");
  3783. // If -Ofast is the optimization level, then -ffast-math should be enabled.
  3784. // This alias option is being used to simplify the getLastArg logic.
  3785. OptSpecifier FastMathAliasOption =
  3786. OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
  3787. // Handle various floating point optimization flags, mapping them to the
  3788. // appropriate LLVM code generation flags. The pattern for all of these is to
  3789. // default off the codegen optimizations, and if any flag enables them and no
  3790. // flag disables them after the flag enabling them, enable the codegen
  3791. // optimization. This is complicated by several "umbrella" flags.
  3792. if (Arg *A = Args.getLastArg(
  3793. options::OPT_ffast_math, FastMathAliasOption,
  3794. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3795. options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
  3796. options::OPT_fno_honor_infinities))
  3797. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3798. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3799. A->getOption().getID() != options::OPT_fhonor_infinities)
  3800. CmdArgs.push_back("-menable-no-infs");
  3801. if (Arg *A = Args.getLastArg(
  3802. options::OPT_ffast_math, FastMathAliasOption,
  3803. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3804. options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
  3805. options::OPT_fno_honor_nans))
  3806. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3807. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3808. A->getOption().getID() != options::OPT_fhonor_nans)
  3809. CmdArgs.push_back("-menable-no-nans");
  3810. // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
  3811. bool MathErrno = getToolChain().IsMathErrnoDefault();
  3812. if (Arg *A =
  3813. Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3814. options::OPT_fno_fast_math, options::OPT_fmath_errno,
  3815. options::OPT_fno_math_errno)) {
  3816. // Turning on -ffast_math (with either flag) removes the need for MathErrno.
  3817. // However, turning *off* -ffast_math merely restores the toolchain default
  3818. // (which may be false).
  3819. if (A->getOption().getID() == options::OPT_fno_math_errno ||
  3820. A->getOption().getID() == options::OPT_ffast_math ||
  3821. A->getOption().getID() == options::OPT_Ofast)
  3822. MathErrno = false;
  3823. else if (A->getOption().getID() == options::OPT_fmath_errno)
  3824. MathErrno = true;
  3825. }
  3826. if (MathErrno)
  3827. CmdArgs.push_back("-fmath-errno");
  3828. // There are several flags which require disabling very specific
  3829. // optimizations. Any of these being disabled forces us to turn off the
  3830. // entire set of LLVM optimizations, so collect them through all the flag
  3831. // madness.
  3832. bool AssociativeMath = false;
  3833. if (Arg *A = Args.getLastArg(
  3834. options::OPT_ffast_math, FastMathAliasOption,
  3835. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3836. options::OPT_fno_unsafe_math_optimizations,
  3837. options::OPT_fassociative_math, options::OPT_fno_associative_math))
  3838. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3839. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3840. A->getOption().getID() != options::OPT_fno_associative_math)
  3841. AssociativeMath = true;
  3842. bool ReciprocalMath = false;
  3843. if (Arg *A = Args.getLastArg(
  3844. options::OPT_ffast_math, FastMathAliasOption,
  3845. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3846. options::OPT_fno_unsafe_math_optimizations,
  3847. options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
  3848. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3849. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3850. A->getOption().getID() != options::OPT_fno_reciprocal_math)
  3851. ReciprocalMath = true;
  3852. bool SignedZeros = true;
  3853. if (Arg *A = Args.getLastArg(
  3854. options::OPT_ffast_math, FastMathAliasOption,
  3855. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3856. options::OPT_fno_unsafe_math_optimizations,
  3857. options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
  3858. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3859. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3860. A->getOption().getID() != options::OPT_fsigned_zeros)
  3861. SignedZeros = false;
  3862. bool TrappingMath = true;
  3863. if (Arg *A = Args.getLastArg(
  3864. options::OPT_ffast_math, FastMathAliasOption,
  3865. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3866. options::OPT_fno_unsafe_math_optimizations,
  3867. options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
  3868. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3869. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3870. A->getOption().getID() != options::OPT_ftrapping_math)
  3871. TrappingMath = false;
  3872. if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
  3873. !TrappingMath)
  3874. CmdArgs.push_back("-menable-unsafe-fp-math");
  3875. if (!SignedZeros)
  3876. CmdArgs.push_back("-fno-signed-zeros");
  3877. if (ReciprocalMath)
  3878. CmdArgs.push_back("-freciprocal-math");
  3879. if (!TrappingMath)
  3880. CmdArgs.push_back("-fno-trapping-math");
  3881. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3882. options::OPT_fno_fast_math,
  3883. options::OPT_funsafe_math_optimizations,
  3884. options::OPT_fno_unsafe_math_optimizations,
  3885. options::OPT_fdenormal_fp_math_EQ))
  3886. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3887. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations)
  3888. Args.AddLastArg(CmdArgs, options::OPT_fdenormal_fp_math_EQ);
  3889. // Validate and pass through -fp-contract option.
  3890. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3891. options::OPT_fno_fast_math,
  3892. options::OPT_ffp_contract)) {
  3893. if (A->getOption().getID() == options::OPT_ffp_contract) {
  3894. StringRef Val = A->getValue();
  3895. if (Val == "fast" || Val == "on" || Val == "off") {
  3896. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
  3897. } else {
  3898. D.Diag(diag::err_drv_unsupported_option_argument)
  3899. << A->getOption().getName() << Val;
  3900. }
  3901. } else if (A->getOption().matches(options::OPT_ffast_math) ||
  3902. (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
  3903. // If fast-math is set then set the fp-contract mode to fast.
  3904. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
  3905. }
  3906. }
  3907. ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
  3908. // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
  3909. // and if we find them, tell the frontend to provide the appropriate
  3910. // preprocessor macros. This is distinct from enabling any optimizations as
  3911. // these options induce language changes which must survive serialization
  3912. // and deserialization, etc.
  3913. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3914. options::OPT_fno_fast_math))
  3915. if (!A->getOption().matches(options::OPT_fno_fast_math))
  3916. CmdArgs.push_back("-ffast-math");
  3917. if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
  3918. options::OPT_fno_fast_math))
  3919. if (A->getOption().matches(options::OPT_ffinite_math_only))
  3920. CmdArgs.push_back("-ffinite-math-only");
  3921. // Decide whether to use verbose asm. Verbose assembly is the default on
  3922. // toolchains which have the integrated assembler on by default.
  3923. bool IsIntegratedAssemblerDefault =
  3924. getToolChain().IsIntegratedAssemblerDefault();
  3925. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  3926. IsIntegratedAssemblerDefault) ||
  3927. Args.hasArg(options::OPT_dA))
  3928. CmdArgs.push_back("-masm-verbose");
  3929. if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
  3930. IsIntegratedAssemblerDefault))
  3931. CmdArgs.push_back("-no-integrated-as");
  3932. if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
  3933. CmdArgs.push_back("-mdebug-pass");
  3934. CmdArgs.push_back("Structure");
  3935. }
  3936. if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
  3937. CmdArgs.push_back("-mdebug-pass");
  3938. CmdArgs.push_back("Arguments");
  3939. }
  3940. // Enable -mconstructor-aliases except on darwin, where we have to work around
  3941. // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
  3942. // aliases aren't supported.
  3943. if (!getToolChain().getTriple().isOSDarwin() &&
  3944. !getToolChain().getTriple().isNVPTX())
  3945. CmdArgs.push_back("-mconstructor-aliases");
  3946. // Darwin's kernel doesn't support guard variables; just die if we
  3947. // try to use them.
  3948. if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
  3949. CmdArgs.push_back("-fforbid-guard-variables");
  3950. if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
  3951. false)) {
  3952. CmdArgs.push_back("-mms-bitfields");
  3953. }
  3954. if (Args.hasFlag(options::OPT_mpie_copy_relocations,
  3955. options::OPT_mno_pie_copy_relocations,
  3956. false)) {
  3957. CmdArgs.push_back("-mpie-copy-relocations");
  3958. }
  3959. // This is a coarse approximation of what llvm-gcc actually does, both
  3960. // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
  3961. // complicated ways.
  3962. bool AsynchronousUnwindTables =
  3963. Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
  3964. options::OPT_fno_asynchronous_unwind_tables,
  3965. (getToolChain().IsUnwindTablesDefault() ||
  3966. getToolChain().getSanitizerArgs().needsUnwindTables()) &&
  3967. !KernelOrKext);
  3968. if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
  3969. AsynchronousUnwindTables))
  3970. CmdArgs.push_back("-munwind-tables");
  3971. getToolChain().addClangTargetOptions(Args, CmdArgs);
  3972. if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
  3973. CmdArgs.push_back("-mlimit-float-precision");
  3974. CmdArgs.push_back(A->getValue());
  3975. }
  3976. // FIXME: Handle -mtune=.
  3977. (void)Args.hasArg(options::OPT_mtune_EQ);
  3978. if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
  3979. CmdArgs.push_back("-mcode-model");
  3980. CmdArgs.push_back(A->getValue());
  3981. }
  3982. // Add the target cpu
  3983. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
  3984. if (!CPU.empty()) {
  3985. CmdArgs.push_back("-target-cpu");
  3986. CmdArgs.push_back(Args.MakeArgString(CPU));
  3987. }
  3988. if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
  3989. CmdArgs.push_back("-mfpmath");
  3990. CmdArgs.push_back(A->getValue());
  3991. }
  3992. // Add the target features
  3993. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
  3994. // Add target specific flags.
  3995. switch (getToolChain().getArch()) {
  3996. default:
  3997. break;
  3998. case llvm::Triple::arm:
  3999. case llvm::Triple::armeb:
  4000. case llvm::Triple::thumb:
  4001. case llvm::Triple::thumbeb:
  4002. // Use the effective triple, which takes into account the deployment target.
  4003. AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
  4004. break;
  4005. case llvm::Triple::aarch64:
  4006. case llvm::Triple::aarch64_be:
  4007. AddAArch64TargetArgs(Args, CmdArgs);
  4008. break;
  4009. case llvm::Triple::mips:
  4010. case llvm::Triple::mipsel:
  4011. case llvm::Triple::mips64:
  4012. case llvm::Triple::mips64el:
  4013. AddMIPSTargetArgs(Args, CmdArgs);
  4014. break;
  4015. case llvm::Triple::ppc:
  4016. case llvm::Triple::ppc64:
  4017. case llvm::Triple::ppc64le:
  4018. AddPPCTargetArgs(Args, CmdArgs);
  4019. break;
  4020. case llvm::Triple::sparc:
  4021. case llvm::Triple::sparcel:
  4022. case llvm::Triple::sparcv9:
  4023. AddSparcTargetArgs(Args, CmdArgs);
  4024. break;
  4025. case llvm::Triple::systemz:
  4026. AddSystemZTargetArgs(Args, CmdArgs);
  4027. break;
  4028. case llvm::Triple::x86:
  4029. case llvm::Triple::x86_64:
  4030. AddX86TargetArgs(Args, CmdArgs);
  4031. break;
  4032. case llvm::Triple::lanai:
  4033. AddLanaiTargetArgs(Args, CmdArgs);
  4034. break;
  4035. case llvm::Triple::hexagon:
  4036. AddHexagonTargetArgs(Args, CmdArgs);
  4037. break;
  4038. case llvm::Triple::wasm32:
  4039. case llvm::Triple::wasm64:
  4040. AddWebAssemblyTargetArgs(Args, CmdArgs);
  4041. break;
  4042. }
  4043. // The 'g' groups options involve a somewhat intricate sequence of decisions
  4044. // about what to pass from the driver to the frontend, but by the time they
  4045. // reach cc1 they've been factored into three well-defined orthogonal choices:
  4046. // * what level of debug info to generate
  4047. // * what dwarf version to write
  4048. // * what debugger tuning to use
  4049. // This avoids having to monkey around further in cc1 other than to disable
  4050. // codeview if not running in a Windows environment. Perhaps even that
  4051. // decision should be made in the driver as well though.
  4052. unsigned DwarfVersion = 0;
  4053. llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
  4054. // These two are potentially updated by AddClangCLArgs.
  4055. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  4056. bool EmitCodeView = false;
  4057. // Add clang-cl arguments.
  4058. types::ID InputType = Input.getType();
  4059. if (getToolChain().getDriver().IsCLMode())
  4060. AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
  4061. // Pass the linker version in use.
  4062. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  4063. CmdArgs.push_back("-target-linker-version");
  4064. CmdArgs.push_back(A->getValue());
  4065. }
  4066. if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
  4067. CmdArgs.push_back("-momit-leaf-frame-pointer");
  4068. // Explicitly error on some things we know we don't support and can't just
  4069. // ignore.
  4070. if (!Args.hasArg(options::OPT_fallow_unsupported)) {
  4071. Arg *Unsupported;
  4072. if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
  4073. getToolChain().getArch() == llvm::Triple::x86) {
  4074. if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
  4075. (Unsupported = Args.getLastArg(options::OPT_mkernel)))
  4076. D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
  4077. << Unsupported->getOption().getName();
  4078. }
  4079. }
  4080. Args.AddAllArgs(CmdArgs, options::OPT_v);
  4081. Args.AddLastArg(CmdArgs, options::OPT_H);
  4082. if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
  4083. CmdArgs.push_back("-header-include-file");
  4084. CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
  4085. : "-");
  4086. }
  4087. Args.AddLastArg(CmdArgs, options::OPT_P);
  4088. Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
  4089. if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
  4090. CmdArgs.push_back("-diagnostic-log-file");
  4091. CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
  4092. : "-");
  4093. }
  4094. bool splitDwarfInlining =
  4095. Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
  4096. options::OPT_fno_split_dwarf_inlining, true);
  4097. Args.ClaimAllArgs(options::OPT_g_Group);
  4098. Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
  4099. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  4100. // If the last option explicitly specified a debug-info level, use it.
  4101. if (A->getOption().matches(options::OPT_gN_Group)) {
  4102. DebugInfoKind = DebugLevelToInfoKind(*A);
  4103. // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
  4104. // But -gsplit-dwarf is not a g_group option, hence we have to check the
  4105. // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
  4106. // This gets a bit more complicated if you've disabled inline info in the
  4107. // skeleton CUs (splitDwarfInlining) - then there's value in composing
  4108. // split-dwarf and line-tables-only, so let those compose naturally in
  4109. // that case.
  4110. // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
  4111. if (SplitDwarfArg) {
  4112. if (A->getIndex() > SplitDwarfArg->getIndex()) {
  4113. if (DebugInfoKind == codegenoptions::NoDebugInfo ||
  4114. (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
  4115. splitDwarfInlining))
  4116. SplitDwarfArg = nullptr;
  4117. } else if (splitDwarfInlining)
  4118. DebugInfoKind = codegenoptions::NoDebugInfo;
  4119. }
  4120. } else
  4121. // For any other 'g' option, use Limited.
  4122. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  4123. }
  4124. // If a debugger tuning argument appeared, remember it.
  4125. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  4126. options::OPT_ggdbN_Group)) {
  4127. if (A->getOption().matches(options::OPT_glldb))
  4128. DebuggerTuning = llvm::DebuggerKind::LLDB;
  4129. else if (A->getOption().matches(options::OPT_gsce))
  4130. DebuggerTuning = llvm::DebuggerKind::SCE;
  4131. else
  4132. DebuggerTuning = llvm::DebuggerKind::GDB;
  4133. }
  4134. // If a -gdwarf argument appeared, remember it.
  4135. if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
  4136. options::OPT_gdwarf_4, options::OPT_gdwarf_5))
  4137. DwarfVersion = DwarfVersionNum(A->getSpelling());
  4138. // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
  4139. // argument parsing.
  4140. if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
  4141. // DwarfVersion remains at 0 if no explicit choice was made.
  4142. CmdArgs.push_back("-gcodeview");
  4143. } else if (DwarfVersion == 0 &&
  4144. DebugInfoKind != codegenoptions::NoDebugInfo) {
  4145. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  4146. }
  4147. // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
  4148. Args.ClaimAllArgs(options::OPT_g_flags_Group);
  4149. // Column info is included by default for everything except PS4 and CodeView.
  4150. // Clang doesn't track end columns, just starting columns, which, in theory,
  4151. // is fine for CodeView (and PDB). In practice, however, the Microsoft
  4152. // debuggers don't handle missing end columns well, so it's better not to
  4153. // include any column info.
  4154. if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
  4155. /*Default=*/ !IsPS4CPU && !(IsWindowsMSVC && EmitCodeView)))
  4156. CmdArgs.push_back("-dwarf-column-info");
  4157. // FIXME: Move backend command line options to the module.
  4158. // If -gline-tables-only is the last option it wins.
  4159. if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
  4160. Args.hasArg(options::OPT_gmodules)) {
  4161. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  4162. CmdArgs.push_back("-dwarf-ext-refs");
  4163. CmdArgs.push_back("-fmodule-format=obj");
  4164. }
  4165. // -gsplit-dwarf should turn on -g and enable the backend dwarf
  4166. // splitting and extraction.
  4167. // FIXME: Currently only works on Linux.
  4168. if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
  4169. if (!splitDwarfInlining)
  4170. CmdArgs.push_back("-fno-split-dwarf-inlining");
  4171. if (DebugInfoKind == codegenoptions::NoDebugInfo)
  4172. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  4173. CmdArgs.push_back("-backend-option");
  4174. CmdArgs.push_back("-split-dwarf=Enable");
  4175. }
  4176. // After we've dealt with all combinations of things that could
  4177. // make DebugInfoKind be other than None or DebugLineTablesOnly,
  4178. // figure out if we need to "upgrade" it to standalone debug info.
  4179. // We parse these two '-f' options whether or not they will be used,
  4180. // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
  4181. bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
  4182. options::OPT_fno_standalone_debug,
  4183. getToolChain().GetDefaultStandaloneDebug());
  4184. if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
  4185. DebugInfoKind = codegenoptions::FullDebugInfo;
  4186. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
  4187. DebuggerTuning);
  4188. // -ggnu-pubnames turns on gnu style pubnames in the backend.
  4189. if (Args.hasArg(options::OPT_ggnu_pubnames)) {
  4190. CmdArgs.push_back("-backend-option");
  4191. CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
  4192. }
  4193. // -gdwarf-aranges turns on the emission of the aranges section in the
  4194. // backend.
  4195. // Always enabled on the PS4.
  4196. if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
  4197. CmdArgs.push_back("-backend-option");
  4198. CmdArgs.push_back("-generate-arange-section");
  4199. }
  4200. if (Args.hasFlag(options::OPT_fdebug_types_section,
  4201. options::OPT_fno_debug_types_section, false)) {
  4202. CmdArgs.push_back("-backend-option");
  4203. CmdArgs.push_back("-generate-type-units");
  4204. }
  4205. bool UseSeparateSections = isUseSeparateSections(Triple);
  4206. if (Args.hasFlag(options::OPT_ffunction_sections,
  4207. options::OPT_fno_function_sections, UseSeparateSections)) {
  4208. CmdArgs.push_back("-ffunction-sections");
  4209. }
  4210. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  4211. UseSeparateSections)) {
  4212. CmdArgs.push_back("-fdata-sections");
  4213. }
  4214. if (!Args.hasFlag(options::OPT_funique_section_names,
  4215. options::OPT_fno_unique_section_names, true))
  4216. CmdArgs.push_back("-fno-unique-section-names");
  4217. Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
  4218. if (Args.hasFlag(options::OPT_fxray_instrument,
  4219. options::OPT_fnoxray_instrument, false)) {
  4220. const char *const XRayInstrumentOption = "-fxray-instrument";
  4221. if (Triple.getOS() == llvm::Triple::Linux &&
  4222. (Triple.getArch() == llvm::Triple::arm ||
  4223. Triple.getArch() == llvm::Triple::x86_64)) {
  4224. // Supported.
  4225. } else {
  4226. D.Diag(diag::err_drv_clang_unsupported)
  4227. << (std::string(XRayInstrumentOption) + " on " + Triple.str());
  4228. }
  4229. CmdArgs.push_back(XRayInstrumentOption);
  4230. if (const Arg *A =
  4231. Args.getLastArg(options::OPT_fxray_instruction_threshold_,
  4232. options::OPT_fxray_instruction_threshold_EQ)) {
  4233. CmdArgs.push_back("-fxray-instruction-threshold");
  4234. CmdArgs.push_back(A->getValue());
  4235. }
  4236. }
  4237. addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
  4238. // Add runtime flag for PS4 when PGO or Coverage are enabled.
  4239. if (getToolChain().getTriple().isPS4CPU())
  4240. addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
  4241. // Pass options for controlling the default header search paths.
  4242. if (Args.hasArg(options::OPT_nostdinc)) {
  4243. CmdArgs.push_back("-nostdsysteminc");
  4244. CmdArgs.push_back("-nobuiltininc");
  4245. } else {
  4246. if (Args.hasArg(options::OPT_nostdlibinc))
  4247. CmdArgs.push_back("-nostdsysteminc");
  4248. Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
  4249. Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
  4250. }
  4251. // Pass the path to compiler resource files.
  4252. CmdArgs.push_back("-resource-dir");
  4253. CmdArgs.push_back(D.ResourceDir.c_str());
  4254. Args.AddLastArg(CmdArgs, options::OPT_working_directory);
  4255. bool ARCMTEnabled = false;
  4256. if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
  4257. if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
  4258. options::OPT_ccc_arcmt_modify,
  4259. options::OPT_ccc_arcmt_migrate)) {
  4260. ARCMTEnabled = true;
  4261. switch (A->getOption().getID()) {
  4262. default:
  4263. llvm_unreachable("missed a case");
  4264. case options::OPT_ccc_arcmt_check:
  4265. CmdArgs.push_back("-arcmt-check");
  4266. break;
  4267. case options::OPT_ccc_arcmt_modify:
  4268. CmdArgs.push_back("-arcmt-modify");
  4269. break;
  4270. case options::OPT_ccc_arcmt_migrate:
  4271. CmdArgs.push_back("-arcmt-migrate");
  4272. CmdArgs.push_back("-mt-migrate-directory");
  4273. CmdArgs.push_back(A->getValue());
  4274. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
  4275. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
  4276. break;
  4277. }
  4278. }
  4279. } else {
  4280. Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
  4281. Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
  4282. Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
  4283. }
  4284. if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
  4285. if (ARCMTEnabled) {
  4286. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  4287. << "-ccc-arcmt-migrate";
  4288. }
  4289. CmdArgs.push_back("-mt-migrate-directory");
  4290. CmdArgs.push_back(A->getValue());
  4291. if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
  4292. options::OPT_objcmt_migrate_subscripting,
  4293. options::OPT_objcmt_migrate_property)) {
  4294. // None specified, means enable them all.
  4295. CmdArgs.push_back("-objcmt-migrate-literals");
  4296. CmdArgs.push_back("-objcmt-migrate-subscripting");
  4297. CmdArgs.push_back("-objcmt-migrate-property");
  4298. } else {
  4299. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  4300. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  4301. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  4302. }
  4303. } else {
  4304. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  4305. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  4306. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  4307. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
  4308. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
  4309. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
  4310. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
  4311. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
  4312. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
  4313. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
  4314. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
  4315. Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
  4316. Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
  4317. Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
  4318. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
  4319. Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
  4320. }
  4321. // Add preprocessing options like -I, -D, etc. if we are using the
  4322. // preprocessor.
  4323. //
  4324. // FIXME: Support -fpreprocessed
  4325. if (types::getPreprocessedType(InputType) != types::TY_INVALID)
  4326. AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
  4327. // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
  4328. // that "The compiler can only warn and ignore the option if not recognized".
  4329. // When building with ccache, it will pass -D options to clang even on
  4330. // preprocessed inputs and configure concludes that -fPIC is not supported.
  4331. Args.ClaimAllArgs(options::OPT_D);
  4332. // Manually translate -O4 to -O3; let clang reject others.
  4333. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  4334. if (A->getOption().matches(options::OPT_O4)) {
  4335. CmdArgs.push_back("-O3");
  4336. D.Diag(diag::warn_O4_is_O3);
  4337. } else {
  4338. A->render(Args, CmdArgs);
  4339. }
  4340. }
  4341. // Warn about ignored options to clang.
  4342. for (const Arg *A :
  4343. Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
  4344. D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
  4345. A->claim();
  4346. }
  4347. claimNoWarnArgs(Args);
  4348. Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
  4349. Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
  4350. if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
  4351. CmdArgs.push_back("-pedantic");
  4352. Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
  4353. Args.AddLastArg(CmdArgs, options::OPT_w);
  4354. // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
  4355. // (-ansi is equivalent to -std=c89 or -std=c++98).
  4356. //
  4357. // If a std is supplied, only add -trigraphs if it follows the
  4358. // option.
  4359. bool ImplyVCPPCXXVer = false;
  4360. if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
  4361. if (Std->getOption().matches(options::OPT_ansi))
  4362. if (types::isCXX(InputType))
  4363. CmdArgs.push_back("-std=c++98");
  4364. else
  4365. CmdArgs.push_back("-std=c89");
  4366. else
  4367. Std->render(Args, CmdArgs);
  4368. // If -f(no-)trigraphs appears after the language standard flag, honor it.
  4369. if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
  4370. options::OPT_ftrigraphs,
  4371. options::OPT_fno_trigraphs))
  4372. if (A != Std)
  4373. A->render(Args, CmdArgs);
  4374. } else {
  4375. // Honor -std-default.
  4376. //
  4377. // FIXME: Clang doesn't correctly handle -std= when the input language
  4378. // doesn't match. For the time being just ignore this for C++ inputs;
  4379. // eventually we want to do all the standard defaulting here instead of
  4380. // splitting it between the driver and clang -cc1.
  4381. if (!types::isCXX(InputType))
  4382. Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
  4383. /*Joined=*/true);
  4384. else if (IsWindowsMSVC)
  4385. ImplyVCPPCXXVer = true;
  4386. Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
  4387. options::OPT_fno_trigraphs);
  4388. }
  4389. // GCC's behavior for -Wwrite-strings is a bit strange:
  4390. // * In C, this "warning flag" changes the types of string literals from
  4391. // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
  4392. // for the discarded qualifier.
  4393. // * In C++, this is just a normal warning flag.
  4394. //
  4395. // Implementing this warning correctly in C is hard, so we follow GCC's
  4396. // behavior for now. FIXME: Directly diagnose uses of a string literal as
  4397. // a non-const char* in C, rather than using this crude hack.
  4398. if (!types::isCXX(InputType)) {
  4399. // FIXME: This should behave just like a warning flag, and thus should also
  4400. // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
  4401. Arg *WriteStrings =
  4402. Args.getLastArg(options::OPT_Wwrite_strings,
  4403. options::OPT_Wno_write_strings, options::OPT_w);
  4404. if (WriteStrings &&
  4405. WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
  4406. CmdArgs.push_back("-fconst-strings");
  4407. }
  4408. // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
  4409. // during C++ compilation, which it is by default. GCC keeps this define even
  4410. // in the presence of '-w', match this behavior bug-for-bug.
  4411. if (types::isCXX(InputType) &&
  4412. Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
  4413. true)) {
  4414. CmdArgs.push_back("-fdeprecated-macro");
  4415. }
  4416. // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
  4417. if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
  4418. if (Asm->getOption().matches(options::OPT_fasm))
  4419. CmdArgs.push_back("-fgnu-keywords");
  4420. else
  4421. CmdArgs.push_back("-fno-gnu-keywords");
  4422. }
  4423. if (ShouldDisableDwarfDirectory(Args, getToolChain()))
  4424. CmdArgs.push_back("-fno-dwarf-directory-asm");
  4425. if (ShouldDisableAutolink(Args, getToolChain()))
  4426. CmdArgs.push_back("-fno-autolink");
  4427. // Add in -fdebug-compilation-dir if necessary.
  4428. addDebugCompDirArg(Args, CmdArgs);
  4429. for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
  4430. StringRef Map = A->getValue();
  4431. if (Map.find('=') == StringRef::npos)
  4432. D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
  4433. else
  4434. CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
  4435. A->claim();
  4436. }
  4437. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
  4438. options::OPT_ftemplate_depth_EQ)) {
  4439. CmdArgs.push_back("-ftemplate-depth");
  4440. CmdArgs.push_back(A->getValue());
  4441. }
  4442. if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
  4443. CmdArgs.push_back("-foperator-arrow-depth");
  4444. CmdArgs.push_back(A->getValue());
  4445. }
  4446. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
  4447. CmdArgs.push_back("-fconstexpr-depth");
  4448. CmdArgs.push_back(A->getValue());
  4449. }
  4450. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
  4451. CmdArgs.push_back("-fconstexpr-steps");
  4452. CmdArgs.push_back(A->getValue());
  4453. }
  4454. if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
  4455. CmdArgs.push_back("-fbracket-depth");
  4456. CmdArgs.push_back(A->getValue());
  4457. }
  4458. if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
  4459. options::OPT_Wlarge_by_value_copy_def)) {
  4460. if (A->getNumValues()) {
  4461. StringRef bytes = A->getValue();
  4462. CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
  4463. } else
  4464. CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
  4465. }
  4466. if (Args.hasArg(options::OPT_relocatable_pch))
  4467. CmdArgs.push_back("-relocatable-pch");
  4468. if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
  4469. CmdArgs.push_back("-fconstant-string-class");
  4470. CmdArgs.push_back(A->getValue());
  4471. }
  4472. if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
  4473. CmdArgs.push_back("-ftabstop");
  4474. CmdArgs.push_back(A->getValue());
  4475. }
  4476. CmdArgs.push_back("-ferror-limit");
  4477. if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
  4478. CmdArgs.push_back(A->getValue());
  4479. else
  4480. CmdArgs.push_back("19");
  4481. if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
  4482. CmdArgs.push_back("-fmacro-backtrace-limit");
  4483. CmdArgs.push_back(A->getValue());
  4484. }
  4485. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
  4486. CmdArgs.push_back("-ftemplate-backtrace-limit");
  4487. CmdArgs.push_back(A->getValue());
  4488. }
  4489. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
  4490. CmdArgs.push_back("-fconstexpr-backtrace-limit");
  4491. CmdArgs.push_back(A->getValue());
  4492. }
  4493. if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
  4494. CmdArgs.push_back("-fspell-checking-limit");
  4495. CmdArgs.push_back(A->getValue());
  4496. }
  4497. // Pass -fmessage-length=.
  4498. CmdArgs.push_back("-fmessage-length");
  4499. if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
  4500. CmdArgs.push_back(A->getValue());
  4501. } else {
  4502. // If -fmessage-length=N was not specified, determine whether this is a
  4503. // terminal and, if so, implicitly define -fmessage-length appropriately.
  4504. unsigned N = llvm::sys::Process::StandardErrColumns();
  4505. CmdArgs.push_back(Args.MakeArgString(Twine(N)));
  4506. }
  4507. // -fvisibility= and -fvisibility-ms-compat are of a piece.
  4508. if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
  4509. options::OPT_fvisibility_ms_compat)) {
  4510. if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
  4511. CmdArgs.push_back("-fvisibility");
  4512. CmdArgs.push_back(A->getValue());
  4513. } else {
  4514. assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
  4515. CmdArgs.push_back("-fvisibility");
  4516. CmdArgs.push_back("hidden");
  4517. CmdArgs.push_back("-ftype-visibility");
  4518. CmdArgs.push_back("default");
  4519. }
  4520. }
  4521. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
  4522. Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
  4523. // -fhosted is default.
  4524. if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
  4525. KernelOrKext)
  4526. CmdArgs.push_back("-ffreestanding");
  4527. // Forward -f (flag) options which we can pass directly.
  4528. Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
  4529. Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
  4530. Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
  4531. // Emulated TLS is enabled by default on Android, and can be enabled manually
  4532. // with -femulated-tls.
  4533. bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
  4534. if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
  4535. EmulatedTLSDefault))
  4536. CmdArgs.push_back("-femulated-tls");
  4537. // AltiVec-like language extensions aren't relevant for assembling.
  4538. if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
  4539. Args.AddLastArg(CmdArgs, options::OPT_faltivec);
  4540. Args.AddLastArg(CmdArgs, options::OPT_fzvector);
  4541. }
  4542. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
  4543. Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
  4544. // Forward flags for OpenMP. We don't do this if the current action is an
  4545. // device offloading action.
  4546. //
  4547. // TODO: Allow OpenMP offload actions when they become available.
  4548. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  4549. options::OPT_fno_openmp, false) &&
  4550. JA.isDeviceOffloading(Action::OFK_None)) {
  4551. switch (getToolChain().getDriver().getOpenMPRuntime(Args)) {
  4552. case Driver::OMPRT_OMP:
  4553. case Driver::OMPRT_IOMP5:
  4554. // Clang can generate useful OpenMP code for these two runtime libraries.
  4555. CmdArgs.push_back("-fopenmp");
  4556. // If no option regarding the use of TLS in OpenMP codegeneration is
  4557. // given, decide a default based on the target. Otherwise rely on the
  4558. // options and pass the right information to the frontend.
  4559. if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
  4560. options::OPT_fnoopenmp_use_tls, /*Default=*/true))
  4561. CmdArgs.push_back("-fnoopenmp-use-tls");
  4562. Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
  4563. break;
  4564. default:
  4565. // By default, if Clang doesn't know how to generate useful OpenMP code
  4566. // for a specific runtime library, we just don't pass the '-fopenmp' flag
  4567. // down to the actual compilation.
  4568. // FIXME: It would be better to have a mode which *only* omits IR
  4569. // generation based on the OpenMP support so that we get consistent
  4570. // semantic analysis, etc.
  4571. break;
  4572. }
  4573. }
  4574. const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
  4575. Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
  4576. // Report an error for -faltivec on anything other than PowerPC.
  4577. if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
  4578. const llvm::Triple::ArchType Arch = getToolChain().getArch();
  4579. if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  4580. Arch == llvm::Triple::ppc64le))
  4581. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  4582. << "ppc/ppc64/ppc64le";
  4583. }
  4584. // -fzvector is incompatible with -faltivec.
  4585. if (Arg *A = Args.getLastArg(options::OPT_fzvector))
  4586. if (Args.hasArg(options::OPT_faltivec))
  4587. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  4588. << "-faltivec";
  4589. if (getToolChain().SupportsProfiling())
  4590. Args.AddLastArg(CmdArgs, options::OPT_pg);
  4591. // -flax-vector-conversions is default.
  4592. if (!Args.hasFlag(options::OPT_flax_vector_conversions,
  4593. options::OPT_fno_lax_vector_conversions))
  4594. CmdArgs.push_back("-fno-lax-vector-conversions");
  4595. if (Args.getLastArg(options::OPT_fapple_kext) ||
  4596. (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
  4597. CmdArgs.push_back("-fapple-kext");
  4598. Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
  4599. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
  4600. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
  4601. Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
  4602. Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
  4603. if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
  4604. CmdArgs.push_back("-ftrapv-handler");
  4605. CmdArgs.push_back(A->getValue());
  4606. }
  4607. Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
  4608. // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
  4609. // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
  4610. if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
  4611. if (A->getOption().matches(options::OPT_fwrapv))
  4612. CmdArgs.push_back("-fwrapv");
  4613. } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
  4614. options::OPT_fno_strict_overflow)) {
  4615. if (A->getOption().matches(options::OPT_fno_strict_overflow))
  4616. CmdArgs.push_back("-fwrapv");
  4617. }
  4618. if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
  4619. options::OPT_fno_reroll_loops))
  4620. if (A->getOption().matches(options::OPT_freroll_loops))
  4621. CmdArgs.push_back("-freroll-loops");
  4622. Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
  4623. Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
  4624. options::OPT_fno_unroll_loops);
  4625. Args.AddLastArg(CmdArgs, options::OPT_pthread);
  4626. // -stack-protector=0 is default.
  4627. unsigned StackProtectorLevel = 0;
  4628. if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
  4629. options::OPT_fstack_protector_all,
  4630. options::OPT_fstack_protector_strong,
  4631. options::OPT_fstack_protector)) {
  4632. if (A->getOption().matches(options::OPT_fstack_protector)) {
  4633. StackProtectorLevel = std::max<unsigned>(
  4634. LangOptions::SSPOn,
  4635. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
  4636. } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
  4637. StackProtectorLevel = LangOptions::SSPStrong;
  4638. else if (A->getOption().matches(options::OPT_fstack_protector_all))
  4639. StackProtectorLevel = LangOptions::SSPReq;
  4640. } else {
  4641. StackProtectorLevel =
  4642. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
  4643. }
  4644. if (StackProtectorLevel) {
  4645. CmdArgs.push_back("-stack-protector");
  4646. CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
  4647. }
  4648. // --param ssp-buffer-size=
  4649. for (const Arg *A : Args.filtered(options::OPT__param)) {
  4650. StringRef Str(A->getValue());
  4651. if (Str.startswith("ssp-buffer-size=")) {
  4652. if (StackProtectorLevel) {
  4653. CmdArgs.push_back("-stack-protector-buffer-size");
  4654. // FIXME: Verify the argument is a valid integer.
  4655. CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
  4656. }
  4657. A->claim();
  4658. }
  4659. }
  4660. // Translate -mstackrealign
  4661. if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
  4662. false))
  4663. CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
  4664. if (Args.hasArg(options::OPT_mstack_alignment)) {
  4665. StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
  4666. CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
  4667. }
  4668. if (Args.hasArg(options::OPT_mstack_probe_size)) {
  4669. StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
  4670. if (!Size.empty())
  4671. CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
  4672. else
  4673. CmdArgs.push_back("-mstack-probe-size=0");
  4674. }
  4675. switch (getToolChain().getArch()) {
  4676. case llvm::Triple::aarch64:
  4677. case llvm::Triple::aarch64_be:
  4678. case llvm::Triple::arm:
  4679. case llvm::Triple::armeb:
  4680. case llvm::Triple::thumb:
  4681. case llvm::Triple::thumbeb:
  4682. CmdArgs.push_back("-fallow-half-arguments-and-returns");
  4683. break;
  4684. default:
  4685. break;
  4686. }
  4687. if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
  4688. options::OPT_mno_restrict_it)) {
  4689. if (A->getOption().matches(options::OPT_mrestrict_it)) {
  4690. CmdArgs.push_back("-backend-option");
  4691. CmdArgs.push_back("-arm-restrict-it");
  4692. } else {
  4693. CmdArgs.push_back("-backend-option");
  4694. CmdArgs.push_back("-arm-no-restrict-it");
  4695. }
  4696. } else if (Triple.isOSWindows() &&
  4697. (Triple.getArch() == llvm::Triple::arm ||
  4698. Triple.getArch() == llvm::Triple::thumb)) {
  4699. // Windows on ARM expects restricted IT blocks
  4700. CmdArgs.push_back("-backend-option");
  4701. CmdArgs.push_back("-arm-restrict-it");
  4702. }
  4703. // Forward -cl options to -cc1
  4704. if (Args.getLastArg(options::OPT_cl_opt_disable)) {
  4705. CmdArgs.push_back("-cl-opt-disable");
  4706. }
  4707. if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
  4708. CmdArgs.push_back("-cl-strict-aliasing");
  4709. }
  4710. if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
  4711. CmdArgs.push_back("-cl-single-precision-constant");
  4712. }
  4713. if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
  4714. CmdArgs.push_back("-cl-finite-math-only");
  4715. }
  4716. if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
  4717. CmdArgs.push_back("-cl-kernel-arg-info");
  4718. }
  4719. if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
  4720. CmdArgs.push_back("-cl-unsafe-math-optimizations");
  4721. }
  4722. if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
  4723. CmdArgs.push_back("-cl-fast-relaxed-math");
  4724. }
  4725. if (Args.getLastArg(options::OPT_cl_mad_enable)) {
  4726. CmdArgs.push_back("-cl-mad-enable");
  4727. }
  4728. if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
  4729. CmdArgs.push_back("-cl-no-signed-zeros");
  4730. }
  4731. if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
  4732. std::string CLStdStr = "-cl-std=";
  4733. CLStdStr += A->getValue();
  4734. CmdArgs.push_back(Args.MakeArgString(CLStdStr));
  4735. }
  4736. if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
  4737. CmdArgs.push_back("-cl-denorms-are-zero");
  4738. }
  4739. if (Args.getLastArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt)) {
  4740. CmdArgs.push_back("-cl-fp32-correctly-rounded-divide-sqrt");
  4741. }
  4742. // Forward -f options with positive and negative forms; we translate
  4743. // these by hand.
  4744. if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
  4745. StringRef fname = A->getValue();
  4746. if (!llvm::sys::fs::exists(fname))
  4747. D.Diag(diag::err_drv_no_such_file) << fname;
  4748. else
  4749. A->render(Args, CmdArgs);
  4750. }
  4751. // -fbuiltin is default unless -mkernel is used.
  4752. bool UseBuiltins =
  4753. Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
  4754. !Args.hasArg(options::OPT_mkernel));
  4755. if (!UseBuiltins)
  4756. CmdArgs.push_back("-fno-builtin");
  4757. // -ffreestanding implies -fno-builtin.
  4758. if (Args.hasArg(options::OPT_ffreestanding))
  4759. UseBuiltins = false;
  4760. // Process the -fno-builtin-* options.
  4761. for (const auto &Arg : Args) {
  4762. const Option &O = Arg->getOption();
  4763. if (!O.matches(options::OPT_fno_builtin_))
  4764. continue;
  4765. Arg->claim();
  4766. // If -fno-builtin is specified, then there's no need to pass the option to
  4767. // the frontend.
  4768. if (!UseBuiltins)
  4769. continue;
  4770. StringRef FuncName = Arg->getValue();
  4771. CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
  4772. }
  4773. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4774. options::OPT_fno_assume_sane_operator_new))
  4775. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4776. // -fblocks=0 is default.
  4777. if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
  4778. getToolChain().IsBlocksDefault()) ||
  4779. (Args.hasArg(options::OPT_fgnu_runtime) &&
  4780. Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
  4781. !Args.hasArg(options::OPT_fno_blocks))) {
  4782. CmdArgs.push_back("-fblocks");
  4783. if (!Args.hasArg(options::OPT_fgnu_runtime) &&
  4784. !getToolChain().hasBlocksRuntime())
  4785. CmdArgs.push_back("-fblocks-runtime-optional");
  4786. }
  4787. if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
  4788. false) &&
  4789. types::isCXX(InputType)) {
  4790. CmdArgs.push_back("-fcoroutines-ts");
  4791. }
  4792. // -fmodules enables the use of precompiled modules (off by default).
  4793. // Users can pass -fno-cxx-modules to turn off modules support for
  4794. // C++/Objective-C++ programs.
  4795. bool HaveClangModules = false;
  4796. if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
  4797. bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
  4798. options::OPT_fno_cxx_modules, true);
  4799. if (AllowedInCXX || !types::isCXX(InputType)) {
  4800. CmdArgs.push_back("-fmodules");
  4801. HaveClangModules = true;
  4802. }
  4803. }
  4804. bool HaveAnyModules = HaveClangModules;
  4805. if (Args.hasArg(options::OPT_fmodules_ts)) {
  4806. CmdArgs.push_back("-fmodules-ts");
  4807. HaveAnyModules = true;
  4808. }
  4809. // -fmodule-maps enables implicit reading of module map files. By default,
  4810. // this is enabled if we are using Clang's flavor of precompiled modules.
  4811. if (Args.hasFlag(options::OPT_fimplicit_module_maps,
  4812. options::OPT_fno_implicit_module_maps, HaveClangModules)) {
  4813. CmdArgs.push_back("-fimplicit-module-maps");
  4814. }
  4815. // -fmodules-decluse checks that modules used are declared so (off by
  4816. // default).
  4817. if (Args.hasFlag(options::OPT_fmodules_decluse,
  4818. options::OPT_fno_modules_decluse, false)) {
  4819. CmdArgs.push_back("-fmodules-decluse");
  4820. }
  4821. // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
  4822. // all #included headers are part of modules.
  4823. if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
  4824. options::OPT_fno_modules_strict_decluse, false)) {
  4825. CmdArgs.push_back("-fmodules-strict-decluse");
  4826. }
  4827. // -fno-implicit-modules turns off implicitly compiling modules on demand.
  4828. if (!Args.hasFlag(options::OPT_fimplicit_modules,
  4829. options::OPT_fno_implicit_modules, HaveClangModules)) {
  4830. if (HaveAnyModules)
  4831. CmdArgs.push_back("-fno-implicit-modules");
  4832. } else if (HaveAnyModules) {
  4833. // -fmodule-cache-path specifies where our implicitly-built module files
  4834. // should be written.
  4835. SmallString<128> Path;
  4836. if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
  4837. Path = A->getValue();
  4838. if (C.isForDiagnostics()) {
  4839. // When generating crash reports, we want to emit the modules along with
  4840. // the reproduction sources, so we ignore any provided module path.
  4841. Path = Output.getFilename();
  4842. llvm::sys::path::replace_extension(Path, ".cache");
  4843. llvm::sys::path::append(Path, "modules");
  4844. } else if (Path.empty()) {
  4845. // No module path was provided: use the default.
  4846. llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
  4847. llvm::sys::path::append(Path, "org.llvm.clang.");
  4848. appendUserToPath(Path);
  4849. llvm::sys::path::append(Path, "ModuleCache");
  4850. }
  4851. const char Arg[] = "-fmodules-cache-path=";
  4852. Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
  4853. CmdArgs.push_back(Args.MakeArgString(Path));
  4854. }
  4855. if (HaveAnyModules) {
  4856. // -fprebuilt-module-path specifies where to load the prebuilt module files.
  4857. for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path))
  4858. CmdArgs.push_back(Args.MakeArgString(
  4859. std::string("-fprebuilt-module-path=") + A->getValue()));
  4860. }
  4861. // -fmodule-name specifies the module that is currently being built (or
  4862. // used for header checking by -fmodule-maps).
  4863. Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
  4864. // -fmodule-map-file can be used to specify files containing module
  4865. // definitions.
  4866. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
  4867. // -fmodule-file can be used to specify files containing precompiled modules.
  4868. if (HaveAnyModules)
  4869. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
  4870. else
  4871. Args.ClaimAllArgs(options::OPT_fmodule_file);
  4872. // When building modules and generating crashdumps, we need to dump a module
  4873. // dependency VFS alongside the output.
  4874. if (HaveClangModules && C.isForDiagnostics()) {
  4875. SmallString<128> VFSDir(Output.getFilename());
  4876. llvm::sys::path::replace_extension(VFSDir, ".cache");
  4877. // Add the cache directory as a temp so the crash diagnostics pick it up.
  4878. C.addTempFile(Args.MakeArgString(VFSDir));
  4879. llvm::sys::path::append(VFSDir, "vfs");
  4880. CmdArgs.push_back("-module-dependency-dir");
  4881. CmdArgs.push_back(Args.MakeArgString(VFSDir));
  4882. }
  4883. if (HaveClangModules)
  4884. Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
  4885. // Pass through all -fmodules-ignore-macro arguments.
  4886. Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
  4887. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
  4888. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
  4889. Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
  4890. if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
  4891. if (Args.hasArg(options::OPT_fbuild_session_timestamp))
  4892. D.Diag(diag::err_drv_argument_not_allowed_with)
  4893. << A->getAsString(Args) << "-fbuild-session-timestamp";
  4894. llvm::sys::fs::file_status Status;
  4895. if (llvm::sys::fs::status(A->getValue(), Status))
  4896. D.Diag(diag::err_drv_no_such_file) << A->getValue();
  4897. CmdArgs.push_back(
  4898. Args.MakeArgString("-fbuild-session-timestamp=" +
  4899. Twine((uint64_t)Status.getLastModificationTime()
  4900. .time_since_epoch()
  4901. .count())));
  4902. }
  4903. if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
  4904. if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
  4905. options::OPT_fbuild_session_file))
  4906. D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
  4907. Args.AddLastArg(CmdArgs,
  4908. options::OPT_fmodules_validate_once_per_build_session);
  4909. }
  4910. Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
  4911. Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
  4912. // -faccess-control is default.
  4913. if (Args.hasFlag(options::OPT_fno_access_control,
  4914. options::OPT_faccess_control, false))
  4915. CmdArgs.push_back("-fno-access-control");
  4916. // -felide-constructors is the default.
  4917. if (Args.hasFlag(options::OPT_fno_elide_constructors,
  4918. options::OPT_felide_constructors, false))
  4919. CmdArgs.push_back("-fno-elide-constructors");
  4920. ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
  4921. if (KernelOrKext || (types::isCXX(InputType) &&
  4922. (RTTIMode == ToolChain::RM_DisabledExplicitly ||
  4923. RTTIMode == ToolChain::RM_DisabledImplicitly)))
  4924. CmdArgs.push_back("-fno-rtti");
  4925. // -fshort-enums=0 is default for all architectures except Hexagon.
  4926. if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
  4927. getToolChain().getArch() == llvm::Triple::hexagon))
  4928. CmdArgs.push_back("-fshort-enums");
  4929. // -fsigned-char is default.
  4930. if (Arg *A = Args.getLastArg(
  4931. options::OPT_fsigned_char, options::OPT_fno_signed_char,
  4932. options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
  4933. if (A->getOption().matches(options::OPT_funsigned_char) ||
  4934. A->getOption().matches(options::OPT_fno_signed_char)) {
  4935. CmdArgs.push_back("-fno-signed-char");
  4936. }
  4937. } else if (!isSignedCharDefault(getToolChain().getTriple())) {
  4938. CmdArgs.push_back("-fno-signed-char");
  4939. }
  4940. // -fuse-cxa-atexit is default.
  4941. if (!Args.hasFlag(
  4942. options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
  4943. !IsWindowsCygnus && !IsWindowsGNU &&
  4944. getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
  4945. getToolChain().getArch() != llvm::Triple::hexagon &&
  4946. getToolChain().getArch() != llvm::Triple::xcore &&
  4947. ((getToolChain().getTriple().getVendor() !=
  4948. llvm::Triple::MipsTechnologies) ||
  4949. getToolChain().getTriple().hasEnvironment())) ||
  4950. KernelOrKext)
  4951. CmdArgs.push_back("-fno-use-cxa-atexit");
  4952. // -fms-extensions=0 is default.
  4953. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  4954. IsWindowsMSVC))
  4955. CmdArgs.push_back("-fms-extensions");
  4956. // -fno-use-line-directives is default.
  4957. if (Args.hasFlag(options::OPT_fuse_line_directives,
  4958. options::OPT_fno_use_line_directives, false))
  4959. CmdArgs.push_back("-fuse-line-directives");
  4960. // -fms-compatibility=0 is default.
  4961. if (Args.hasFlag(options::OPT_fms_compatibility,
  4962. options::OPT_fno_ms_compatibility,
  4963. (IsWindowsMSVC &&
  4964. Args.hasFlag(options::OPT_fms_extensions,
  4965. options::OPT_fno_ms_extensions, true))))
  4966. CmdArgs.push_back("-fms-compatibility");
  4967. // -fms-compatibility-version=18.00 is default.
  4968. VersionTuple MSVT = visualstudio::getMSVCVersion(
  4969. &D, getToolChain(), getToolChain().getTriple(), Args, IsWindowsMSVC);
  4970. if (!MSVT.empty())
  4971. CmdArgs.push_back(
  4972. Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
  4973. bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
  4974. if (ImplyVCPPCXXVer) {
  4975. StringRef LanguageStandard;
  4976. if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
  4977. LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
  4978. .Case("c++14", "-std=c++14")
  4979. .Case("c++latest", "-std=c++1z")
  4980. .Default("");
  4981. if (LanguageStandard.empty())
  4982. D.Diag(clang::diag::warn_drv_unused_argument)
  4983. << StdArg->getAsString(Args);
  4984. }
  4985. if (LanguageStandard.empty()) {
  4986. if (IsMSVC2015Compatible)
  4987. LanguageStandard = "-std=c++14";
  4988. else
  4989. LanguageStandard = "-std=c++11";
  4990. }
  4991. CmdArgs.push_back(LanguageStandard.data());
  4992. }
  4993. // -fno-borland-extensions is default.
  4994. if (Args.hasFlag(options::OPT_fborland_extensions,
  4995. options::OPT_fno_borland_extensions, false))
  4996. CmdArgs.push_back("-fborland-extensions");
  4997. // -fno-declspec is default, except for PS4.
  4998. if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
  4999. getToolChain().getTriple().isPS4()))
  5000. CmdArgs.push_back("-fdeclspec");
  5001. else if (Args.hasArg(options::OPT_fno_declspec))
  5002. CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
  5003. // -fthreadsafe-static is default, except for MSVC compatibility versions less
  5004. // than 19.
  5005. if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
  5006. options::OPT_fno_threadsafe_statics,
  5007. !IsWindowsMSVC || IsMSVC2015Compatible))
  5008. CmdArgs.push_back("-fno-threadsafe-statics");
  5009. // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
  5010. // needs it.
  5011. if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
  5012. options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
  5013. CmdArgs.push_back("-fdelayed-template-parsing");
  5014. // -fgnu-keywords default varies depending on language; only pass if
  5015. // specified.
  5016. if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
  5017. options::OPT_fno_gnu_keywords))
  5018. A->render(Args, CmdArgs);
  5019. if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
  5020. false))
  5021. CmdArgs.push_back("-fgnu89-inline");
  5022. if (Args.hasArg(options::OPT_fno_inline))
  5023. CmdArgs.push_back("-fno-inline");
  5024. if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
  5025. options::OPT_finline_hint_functions,
  5026. options::OPT_fno_inline_functions))
  5027. InlineArg->render(Args, CmdArgs);
  5028. ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
  5029. // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
  5030. // legacy is the default. Except for deployment target of 10.5,
  5031. // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
  5032. // gets ignored silently.
  5033. if (objcRuntime.isNonFragile()) {
  5034. if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
  5035. options::OPT_fno_objc_legacy_dispatch,
  5036. objcRuntime.isLegacyDispatchDefaultForArch(
  5037. getToolChain().getArch()))) {
  5038. if (getToolChain().UseObjCMixedDispatch())
  5039. CmdArgs.push_back("-fobjc-dispatch-method=mixed");
  5040. else
  5041. CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
  5042. }
  5043. }
  5044. // When ObjectiveC legacy runtime is in effect on MacOSX,
  5045. // turn on the option to do Array/Dictionary subscripting
  5046. // by default.
  5047. if (getToolChain().getArch() == llvm::Triple::x86 &&
  5048. getToolChain().getTriple().isMacOSX() &&
  5049. !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
  5050. objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
  5051. objcRuntime.isNeXTFamily())
  5052. CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
  5053. // -fencode-extended-block-signature=1 is default.
  5054. if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
  5055. CmdArgs.push_back("-fencode-extended-block-signature");
  5056. }
  5057. // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
  5058. // NOTE: This logic is duplicated in ToolChains.cpp.
  5059. bool ARC = isObjCAutoRefCount(Args);
  5060. if (ARC) {
  5061. getToolChain().CheckObjCARC();
  5062. CmdArgs.push_back("-fobjc-arc");
  5063. // FIXME: It seems like this entire block, and several around it should be
  5064. // wrapped in isObjC, but for now we just use it here as this is where it
  5065. // was being used previously.
  5066. if (types::isCXX(InputType) && types::isObjC(InputType)) {
  5067. if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  5068. CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
  5069. else
  5070. CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
  5071. }
  5072. // Allow the user to enable full exceptions code emission.
  5073. // We define off for Objective-CC, on for Objective-C++.
  5074. if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
  5075. options::OPT_fno_objc_arc_exceptions,
  5076. /*default*/ types::isCXX(InputType)))
  5077. CmdArgs.push_back("-fobjc-arc-exceptions");
  5078. }
  5079. // -fobjc-infer-related-result-type is the default, except in the Objective-C
  5080. // rewriter.
  5081. if (rewriteKind != RK_None)
  5082. CmdArgs.push_back("-fno-objc-infer-related-result-type");
  5083. // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
  5084. // takes precedence.
  5085. const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
  5086. if (!GCArg)
  5087. GCArg = Args.getLastArg(options::OPT_fobjc_gc);
  5088. if (GCArg) {
  5089. if (ARC) {
  5090. D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
  5091. } else if (getToolChain().SupportsObjCGC()) {
  5092. GCArg->render(Args, CmdArgs);
  5093. } else {
  5094. // FIXME: We should move this to a hard error.
  5095. D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
  5096. }
  5097. }
  5098. // Pass down -fobjc-weak or -fno-objc-weak if present.
  5099. if (types::isObjC(InputType)) {
  5100. auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
  5101. options::OPT_fno_objc_weak);
  5102. if (!WeakArg) {
  5103. // nothing to do
  5104. } else if (GCArg) {
  5105. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  5106. D.Diag(diag::err_objc_weak_with_gc);
  5107. } else if (!objcRuntime.allowsWeak()) {
  5108. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  5109. D.Diag(diag::err_objc_weak_unsupported);
  5110. } else {
  5111. WeakArg->render(Args, CmdArgs);
  5112. }
  5113. }
  5114. if (Args.hasFlag(options::OPT_fapplication_extension,
  5115. options::OPT_fno_application_extension, false))
  5116. CmdArgs.push_back("-fapplication-extension");
  5117. // Handle GCC-style exception args.
  5118. if (!C.getDriver().IsCLMode())
  5119. addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
  5120. CmdArgs);
  5121. if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
  5122. getToolChain().UseSjLjExceptions(Args))
  5123. CmdArgs.push_back("-fsjlj-exceptions");
  5124. // C++ "sane" operator new.
  5125. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  5126. options::OPT_fno_assume_sane_operator_new))
  5127. CmdArgs.push_back("-fno-assume-sane-operator-new");
  5128. // -fsized-deallocation is off by default, as it is an ABI-breaking change for
  5129. // most platforms.
  5130. if (Args.hasFlag(options::OPT_fsized_deallocation,
  5131. options::OPT_fno_sized_deallocation, false))
  5132. CmdArgs.push_back("-fsized-deallocation");
  5133. // -faligned-allocation is on by default in C++17 onwards and otherwise off
  5134. // by default.
  5135. if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
  5136. options::OPT_fno_aligned_allocation,
  5137. options::OPT_faligned_new_EQ)) {
  5138. if (A->getOption().matches(options::OPT_fno_aligned_allocation))
  5139. CmdArgs.push_back("-fno-aligned-allocation");
  5140. else
  5141. CmdArgs.push_back("-faligned-allocation");
  5142. }
  5143. // The default new alignment can be specified using a dedicated option or via
  5144. // a GCC-compatible option that also turns on aligned allocation.
  5145. if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
  5146. options::OPT_faligned_new_EQ))
  5147. CmdArgs.push_back(
  5148. Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
  5149. // -fconstant-cfstrings is default, and may be subject to argument translation
  5150. // on Darwin.
  5151. if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
  5152. options::OPT_fno_constant_cfstrings) ||
  5153. !Args.hasFlag(options::OPT_mconstant_cfstrings,
  5154. options::OPT_mno_constant_cfstrings))
  5155. CmdArgs.push_back("-fno-constant-cfstrings");
  5156. // -fshort-wchar default varies depending on platform; only
  5157. // pass if specified.
  5158. if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
  5159. options::OPT_fno_short_wchar))
  5160. A->render(Args, CmdArgs);
  5161. // -fno-pascal-strings is default, only pass non-default.
  5162. if (Args.hasFlag(options::OPT_fpascal_strings,
  5163. options::OPT_fno_pascal_strings, false))
  5164. CmdArgs.push_back("-fpascal-strings");
  5165. // Honor -fpack-struct= and -fpack-struct, if given. Note that
  5166. // -fno-pack-struct doesn't apply to -fpack-struct=.
  5167. if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
  5168. std::string PackStructStr = "-fpack-struct=";
  5169. PackStructStr += A->getValue();
  5170. CmdArgs.push_back(Args.MakeArgString(PackStructStr));
  5171. } else if (Args.hasFlag(options::OPT_fpack_struct,
  5172. options::OPT_fno_pack_struct, false)) {
  5173. CmdArgs.push_back("-fpack-struct=1");
  5174. }
  5175. // Handle -fmax-type-align=N and -fno-type-align
  5176. bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
  5177. if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
  5178. if (!SkipMaxTypeAlign) {
  5179. std::string MaxTypeAlignStr = "-fmax-type-align=";
  5180. MaxTypeAlignStr += A->getValue();
  5181. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  5182. }
  5183. } else if (getToolChain().getTriple().isOSDarwin()) {
  5184. if (!SkipMaxTypeAlign) {
  5185. std::string MaxTypeAlignStr = "-fmax-type-align=16";
  5186. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  5187. }
  5188. }
  5189. // -fcommon is the default unless compiling kernel code or the target says so
  5190. bool NoCommonDefault =
  5191. KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
  5192. if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
  5193. !NoCommonDefault))
  5194. CmdArgs.push_back("-fno-common");
  5195. // -fsigned-bitfields is default, and clang doesn't yet support
  5196. // -funsigned-bitfields.
  5197. if (!Args.hasFlag(options::OPT_fsigned_bitfields,
  5198. options::OPT_funsigned_bitfields))
  5199. D.Diag(diag::warn_drv_clang_unsupported)
  5200. << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
  5201. // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
  5202. if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
  5203. D.Diag(diag::err_drv_clang_unsupported)
  5204. << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
  5205. // -finput_charset=UTF-8 is default. Reject others
  5206. if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
  5207. StringRef value = inputCharset->getValue();
  5208. if (!value.equals_lower("utf-8"))
  5209. D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
  5210. << value;
  5211. }
  5212. // -fexec_charset=UTF-8 is default. Reject others
  5213. if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
  5214. StringRef value = execCharset->getValue();
  5215. if (!value.equals_lower("utf-8"))
  5216. D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
  5217. << value;
  5218. }
  5219. // -fcaret-diagnostics is default.
  5220. if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
  5221. options::OPT_fno_caret_diagnostics, true))
  5222. CmdArgs.push_back("-fno-caret-diagnostics");
  5223. // -fdiagnostics-fixit-info is default, only pass non-default.
  5224. if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
  5225. options::OPT_fno_diagnostics_fixit_info))
  5226. CmdArgs.push_back("-fno-diagnostics-fixit-info");
  5227. // Enable -fdiagnostics-show-option by default.
  5228. if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
  5229. options::OPT_fno_diagnostics_show_option))
  5230. CmdArgs.push_back("-fdiagnostics-show-option");
  5231. if (const Arg *A =
  5232. Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
  5233. CmdArgs.push_back("-fdiagnostics-show-category");
  5234. CmdArgs.push_back(A->getValue());
  5235. }
  5236. if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
  5237. options::OPT_fno_diagnostics_show_hotness, false))
  5238. CmdArgs.push_back("-fdiagnostics-show-hotness");
  5239. if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
  5240. CmdArgs.push_back("-fdiagnostics-format");
  5241. CmdArgs.push_back(A->getValue());
  5242. }
  5243. if (Arg *A = Args.getLastArg(
  5244. options::OPT_fdiagnostics_show_note_include_stack,
  5245. options::OPT_fno_diagnostics_show_note_include_stack)) {
  5246. if (A->getOption().matches(
  5247. options::OPT_fdiagnostics_show_note_include_stack))
  5248. CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
  5249. else
  5250. CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
  5251. }
  5252. // Color diagnostics are parsed by the driver directly from argv
  5253. // and later re-parsed to construct this job; claim any possible
  5254. // color diagnostic here to avoid warn_drv_unused_argument and
  5255. // diagnose bad OPT_fdiagnostics_color_EQ values.
  5256. for (Arg *A : Args) {
  5257. const Option &O = A->getOption();
  5258. if (!O.matches(options::OPT_fcolor_diagnostics) &&
  5259. !O.matches(options::OPT_fdiagnostics_color) &&
  5260. !O.matches(options::OPT_fno_color_diagnostics) &&
  5261. !O.matches(options::OPT_fno_diagnostics_color) &&
  5262. !O.matches(options::OPT_fdiagnostics_color_EQ))
  5263. continue;
  5264. if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
  5265. StringRef Value(A->getValue());
  5266. if (Value != "always" && Value != "never" && Value != "auto")
  5267. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  5268. << ("-fdiagnostics-color=" + Value).str();
  5269. }
  5270. A->claim();
  5271. }
  5272. if (D.getDiags().getDiagnosticOptions().ShowColors)
  5273. CmdArgs.push_back("-fcolor-diagnostics");
  5274. if (Args.hasArg(options::OPT_fansi_escape_codes))
  5275. CmdArgs.push_back("-fansi-escape-codes");
  5276. if (!Args.hasFlag(options::OPT_fshow_source_location,
  5277. options::OPT_fno_show_source_location))
  5278. CmdArgs.push_back("-fno-show-source-location");
  5279. if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
  5280. CmdArgs.push_back("-fdiagnostics-absolute-paths");
  5281. if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
  5282. true))
  5283. CmdArgs.push_back("-fno-show-column");
  5284. if (!Args.hasFlag(options::OPT_fspell_checking,
  5285. options::OPT_fno_spell_checking))
  5286. CmdArgs.push_back("-fno-spell-checking");
  5287. // -fno-asm-blocks is default.
  5288. if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
  5289. false))
  5290. CmdArgs.push_back("-fasm-blocks");
  5291. // -fgnu-inline-asm is default.
  5292. if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
  5293. options::OPT_fno_gnu_inline_asm, true))
  5294. CmdArgs.push_back("-fno-gnu-inline-asm");
  5295. // Enable vectorization per default according to the optimization level
  5296. // selected. For optimization levels that want vectorization we use the alias
  5297. // option to simplify the hasFlag logic.
  5298. bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
  5299. OptSpecifier VectorizeAliasOption =
  5300. EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
  5301. if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
  5302. options::OPT_fno_vectorize, EnableVec))
  5303. CmdArgs.push_back("-vectorize-loops");
  5304. // -fslp-vectorize is enabled based on the optimization level selected.
  5305. bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
  5306. OptSpecifier SLPVectAliasOption =
  5307. EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
  5308. if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
  5309. options::OPT_fno_slp_vectorize, EnableSLPVec))
  5310. CmdArgs.push_back("-vectorize-slp");
  5311. // -fno-slp-vectorize-aggressive is default.
  5312. if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
  5313. options::OPT_fno_slp_vectorize_aggressive, false))
  5314. CmdArgs.push_back("-vectorize-slp-aggressive");
  5315. if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
  5316. A->render(Args, CmdArgs);
  5317. if (Arg *A = Args.getLastArg(
  5318. options::OPT_fsanitize_undefined_strip_path_components_EQ))
  5319. A->render(Args, CmdArgs);
  5320. // -fdollars-in-identifiers default varies depending on platform and
  5321. // language; only pass if specified.
  5322. if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
  5323. options::OPT_fno_dollars_in_identifiers)) {
  5324. if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
  5325. CmdArgs.push_back("-fdollars-in-identifiers");
  5326. else
  5327. CmdArgs.push_back("-fno-dollars-in-identifiers");
  5328. }
  5329. // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
  5330. // practical purposes.
  5331. if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
  5332. options::OPT_fno_unit_at_a_time)) {
  5333. if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
  5334. D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
  5335. }
  5336. if (Args.hasFlag(options::OPT_fapple_pragma_pack,
  5337. options::OPT_fno_apple_pragma_pack, false))
  5338. CmdArgs.push_back("-fapple-pragma-pack");
  5339. // le32-specific flags:
  5340. // -fno-math-builtin: clang should not convert math builtins to intrinsics
  5341. // by default.
  5342. if (getToolChain().getArch() == llvm::Triple::le32) {
  5343. CmdArgs.push_back("-fno-math-builtin");
  5344. }
  5345. if (Args.hasFlag(options::OPT_fsave_optimization_record,
  5346. options::OPT_fno_save_optimization_record, false)) {
  5347. CmdArgs.push_back("-opt-record-file");
  5348. const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
  5349. if (A) {
  5350. CmdArgs.push_back(A->getValue());
  5351. } else {
  5352. SmallString<128> F;
  5353. if (Output.isFilename() && (Args.hasArg(options::OPT_c) ||
  5354. Args.hasArg(options::OPT_S))) {
  5355. F = Output.getFilename();
  5356. } else {
  5357. // Use the compilation directory.
  5358. F = llvm::sys::path::stem(Input.getBaseInput());
  5359. // If we're compiling for an offload architecture (i.e. a CUDA device),
  5360. // we need to make the file name for the device compilation different
  5361. // from the host compilation.
  5362. if (!JA.isDeviceOffloading(Action::OFK_None) &&
  5363. !JA.isDeviceOffloading(Action::OFK_Host)) {
  5364. llvm::sys::path::replace_extension(F, "");
  5365. F += JA.getOffloadingFileNamePrefix(Triple.normalize());
  5366. F += "-";
  5367. F += JA.getOffloadingArch();
  5368. }
  5369. }
  5370. llvm::sys::path::replace_extension(F, "opt.yaml");
  5371. CmdArgs.push_back(Args.MakeArgString(F));
  5372. }
  5373. }
  5374. // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
  5375. //
  5376. // FIXME: Now that PR4941 has been fixed this can be enabled.
  5377. #if 0
  5378. if (getToolChain().getTriple().isOSDarwin() &&
  5379. (getToolChain().getArch() == llvm::Triple::arm ||
  5380. getToolChain().getArch() == llvm::Triple::thumb)) {
  5381. if (!Args.hasArg(options::OPT_fbuiltin_strcat))
  5382. CmdArgs.push_back("-fno-builtin-strcat");
  5383. if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
  5384. CmdArgs.push_back("-fno-builtin-strcpy");
  5385. }
  5386. #endif
  5387. // Enable rewrite includes if the user's asked for it or if we're generating
  5388. // diagnostics.
  5389. // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
  5390. // nice to enable this when doing a crashdump for modules as well.
  5391. if (Args.hasFlag(options::OPT_frewrite_includes,
  5392. options::OPT_fno_rewrite_includes, false) ||
  5393. (C.isForDiagnostics() && !HaveAnyModules))
  5394. CmdArgs.push_back("-frewrite-includes");
  5395. // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
  5396. if (Arg *A = Args.getLastArg(options::OPT_traditional,
  5397. options::OPT_traditional_cpp)) {
  5398. if (isa<PreprocessJobAction>(JA))
  5399. CmdArgs.push_back("-traditional-cpp");
  5400. else
  5401. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  5402. }
  5403. Args.AddLastArg(CmdArgs, options::OPT_dM);
  5404. Args.AddLastArg(CmdArgs, options::OPT_dD);
  5405. // Handle serialized diagnostics.
  5406. if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
  5407. CmdArgs.push_back("-serialize-diagnostic-file");
  5408. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  5409. }
  5410. if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
  5411. CmdArgs.push_back("-fretain-comments-from-system-headers");
  5412. // Forward -fcomment-block-commands to -cc1.
  5413. Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
  5414. // Forward -fparse-all-comments to -cc1.
  5415. Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
  5416. // Turn -fplugin=name.so into -load name.so
  5417. for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
  5418. CmdArgs.push_back("-load");
  5419. CmdArgs.push_back(A->getValue());
  5420. A->claim();
  5421. }
  5422. // Setup statistics file output.
  5423. if (const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ)) {
  5424. StringRef SaveStats = A->getValue();
  5425. SmallString<128> StatsFile;
  5426. bool DoSaveStats = false;
  5427. if (SaveStats == "obj") {
  5428. if (Output.isFilename()) {
  5429. StatsFile.assign(Output.getFilename());
  5430. llvm::sys::path::remove_filename(StatsFile);
  5431. }
  5432. DoSaveStats = true;
  5433. } else if (SaveStats == "cwd") {
  5434. DoSaveStats = true;
  5435. } else {
  5436. D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
  5437. }
  5438. if (DoSaveStats) {
  5439. StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
  5440. llvm::sys::path::append(StatsFile, BaseName);
  5441. llvm::sys::path::replace_extension(StatsFile, "stats");
  5442. CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") +
  5443. StatsFile));
  5444. }
  5445. }
  5446. // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
  5447. // parser.
  5448. Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
  5449. for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
  5450. A->claim();
  5451. // We translate this by hand to the -cc1 argument, since nightly test uses
  5452. // it and developers have been trained to spell it with -mllvm.
  5453. if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
  5454. CmdArgs.push_back("-disable-llvm-optzns");
  5455. } else
  5456. A->render(Args, CmdArgs);
  5457. }
  5458. // With -save-temps, we want to save the unoptimized bitcode output from the
  5459. // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
  5460. // by the frontend.
  5461. // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
  5462. // has slightly different breakdown between stages.
  5463. // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
  5464. // pristine IR generated by the frontend. Ideally, a new compile action should
  5465. // be added so both IR can be captured.
  5466. if (C.getDriver().isSaveTempsEnabled() &&
  5467. !C.getDriver().embedBitcodeEnabled() && isa<CompileJobAction>(JA))
  5468. CmdArgs.push_back("-disable-llvm-passes");
  5469. if (Output.getType() == types::TY_Dependencies) {
  5470. // Handled with other dependency code.
  5471. } else if (Output.isFilename()) {
  5472. CmdArgs.push_back("-o");
  5473. CmdArgs.push_back(Output.getFilename());
  5474. } else {
  5475. assert(Output.isNothing() && "Invalid output.");
  5476. }
  5477. addDashXForInput(Args, Input, CmdArgs);
  5478. if (Input.isFilename())
  5479. CmdArgs.push_back(Input.getFilename());
  5480. else
  5481. Input.getInputArg().renderAsInput(Args, CmdArgs);
  5482. Args.AddAllArgs(CmdArgs, options::OPT_undef);
  5483. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5484. // Optionally embed the -cc1 level arguments into the debug info, for build
  5485. // analysis.
  5486. if (getToolChain().UseDwarfDebugFlags()) {
  5487. ArgStringList OriginalArgs;
  5488. for (const auto &Arg : Args)
  5489. Arg->render(Args, OriginalArgs);
  5490. SmallString<256> Flags;
  5491. Flags += Exec;
  5492. for (const char *OriginalArg : OriginalArgs) {
  5493. SmallString<128> EscapedArg;
  5494. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  5495. Flags += " ";
  5496. Flags += EscapedArg;
  5497. }
  5498. CmdArgs.push_back("-dwarf-debug-flags");
  5499. CmdArgs.push_back(Args.MakeArgString(Flags));
  5500. }
  5501. // Add the split debug info name to the command lines here so we
  5502. // can propagate it to the backend.
  5503. bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
  5504. (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
  5505. isa<BackendJobAction>(JA));
  5506. const char *SplitDwarfOut;
  5507. if (SplitDwarf) {
  5508. CmdArgs.push_back("-split-dwarf-file");
  5509. SplitDwarfOut = SplitDebugName(Args, Input);
  5510. CmdArgs.push_back(SplitDwarfOut);
  5511. }
  5512. // Host-side cuda compilation receives device-side outputs as Inputs[1...].
  5513. // Include them with -fcuda-include-gpubinary.
  5514. if (IsCuda && Inputs.size() > 1)
  5515. for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
  5516. CmdArgs.push_back("-fcuda-include-gpubinary");
  5517. CmdArgs.push_back(I->getFilename());
  5518. }
  5519. bool WholeProgramVTables =
  5520. Args.hasFlag(options::OPT_fwhole_program_vtables,
  5521. options::OPT_fno_whole_program_vtables, false);
  5522. if (WholeProgramVTables) {
  5523. if (!D.isUsingLTO())
  5524. D.Diag(diag::err_drv_argument_only_allowed_with)
  5525. << "-fwhole-program-vtables"
  5526. << "-flto";
  5527. CmdArgs.push_back("-fwhole-program-vtables");
  5528. }
  5529. // Finally add the compile command to the compilation.
  5530. if (Args.hasArg(options::OPT__SLASH_fallback) &&
  5531. Output.getType() == types::TY_Object &&
  5532. (InputType == types::TY_C || InputType == types::TY_CXX)) {
  5533. auto CLCommand =
  5534. getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
  5535. C.addCommand(llvm::make_unique<FallbackCommand>(
  5536. JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
  5537. } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
  5538. isa<PrecompileJobAction>(JA)) {
  5539. // In /fallback builds, run the main compilation even if the pch generation
  5540. // fails, so that the main compilation's fallback to cl.exe runs.
  5541. C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
  5542. CmdArgs, Inputs));
  5543. } else {
  5544. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5545. }
  5546. // Handle the debug info splitting at object creation time if we're
  5547. // creating an object.
  5548. // TODO: Currently only works on linux with newer objcopy.
  5549. if (SplitDwarf && Output.getType() == types::TY_Object)
  5550. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
  5551. if (Arg *A = Args.getLastArg(options::OPT_pg))
  5552. if (Args.hasArg(options::OPT_fomit_frame_pointer))
  5553. D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
  5554. << A->getAsString(Args);
  5555. // Claim some arguments which clang supports automatically.
  5556. // -fpch-preprocess is used with gcc to add a special marker in the output to
  5557. // include the PCH file. Clang's PTH solution is completely transparent, so we
  5558. // do not need to deal with it at all.
  5559. Args.ClaimAllArgs(options::OPT_fpch_preprocess);
  5560. // Claim some arguments which clang doesn't support, but we don't
  5561. // care to warn the user about.
  5562. Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
  5563. Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
  5564. // Disable warnings for clang -E -emit-llvm foo.c
  5565. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5566. }
  5567. /// Add options related to the Objective-C runtime/ABI.
  5568. ///
  5569. /// Returns true if the runtime is non-fragile.
  5570. ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
  5571. ArgStringList &cmdArgs,
  5572. RewriteKind rewriteKind) const {
  5573. // Look for the controlling runtime option.
  5574. Arg *runtimeArg =
  5575. args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
  5576. options::OPT_fobjc_runtime_EQ);
  5577. // Just forward -fobjc-runtime= to the frontend. This supercedes
  5578. // options about fragility.
  5579. if (runtimeArg &&
  5580. runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
  5581. ObjCRuntime runtime;
  5582. StringRef value = runtimeArg->getValue();
  5583. if (runtime.tryParse(value)) {
  5584. getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
  5585. << value;
  5586. }
  5587. runtimeArg->render(args, cmdArgs);
  5588. return runtime;
  5589. }
  5590. // Otherwise, we'll need the ABI "version". Version numbers are
  5591. // slightly confusing for historical reasons:
  5592. // 1 - Traditional "fragile" ABI
  5593. // 2 - Non-fragile ABI, version 1
  5594. // 3 - Non-fragile ABI, version 2
  5595. unsigned objcABIVersion = 1;
  5596. // If -fobjc-abi-version= is present, use that to set the version.
  5597. if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
  5598. StringRef value = abiArg->getValue();
  5599. if (value == "1")
  5600. objcABIVersion = 1;
  5601. else if (value == "2")
  5602. objcABIVersion = 2;
  5603. else if (value == "3")
  5604. objcABIVersion = 3;
  5605. else
  5606. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
  5607. } else {
  5608. // Otherwise, determine if we are using the non-fragile ABI.
  5609. bool nonFragileABIIsDefault =
  5610. (rewriteKind == RK_NonFragile ||
  5611. (rewriteKind == RK_None &&
  5612. getToolChain().IsObjCNonFragileABIDefault()));
  5613. if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
  5614. options::OPT_fno_objc_nonfragile_abi,
  5615. nonFragileABIIsDefault)) {
  5616. // Determine the non-fragile ABI version to use.
  5617. #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
  5618. unsigned nonFragileABIVersion = 1;
  5619. #else
  5620. unsigned nonFragileABIVersion = 2;
  5621. #endif
  5622. if (Arg *abiArg =
  5623. args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
  5624. StringRef value = abiArg->getValue();
  5625. if (value == "1")
  5626. nonFragileABIVersion = 1;
  5627. else if (value == "2")
  5628. nonFragileABIVersion = 2;
  5629. else
  5630. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  5631. << value;
  5632. }
  5633. objcABIVersion = 1 + nonFragileABIVersion;
  5634. } else {
  5635. objcABIVersion = 1;
  5636. }
  5637. }
  5638. // We don't actually care about the ABI version other than whether
  5639. // it's non-fragile.
  5640. bool isNonFragile = objcABIVersion != 1;
  5641. // If we have no runtime argument, ask the toolchain for its default runtime.
  5642. // However, the rewriter only really supports the Mac runtime, so assume that.
  5643. ObjCRuntime runtime;
  5644. if (!runtimeArg) {
  5645. switch (rewriteKind) {
  5646. case RK_None:
  5647. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  5648. break;
  5649. case RK_Fragile:
  5650. runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
  5651. break;
  5652. case RK_NonFragile:
  5653. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  5654. break;
  5655. }
  5656. // -fnext-runtime
  5657. } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
  5658. // On Darwin, make this use the default behavior for the toolchain.
  5659. if (getToolChain().getTriple().isOSDarwin()) {
  5660. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  5661. // Otherwise, build for a generic macosx port.
  5662. } else {
  5663. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  5664. }
  5665. // -fgnu-runtime
  5666. } else {
  5667. assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
  5668. // Legacy behaviour is to target the gnustep runtime if we are in
  5669. // non-fragile mode or the GCC runtime in fragile mode.
  5670. if (isNonFragile)
  5671. runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
  5672. else
  5673. runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
  5674. }
  5675. cmdArgs.push_back(
  5676. args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
  5677. return runtime;
  5678. }
  5679. static bool maybeConsumeDash(const std::string &EH, size_t &I) {
  5680. bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
  5681. I += HaveDash;
  5682. return !HaveDash;
  5683. }
  5684. namespace {
  5685. struct EHFlags {
  5686. bool Synch = false;
  5687. bool Asynch = false;
  5688. bool NoUnwindC = false;
  5689. };
  5690. } // end anonymous namespace
  5691. /// /EH controls whether to run destructor cleanups when exceptions are
  5692. /// thrown. There are three modifiers:
  5693. /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
  5694. /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
  5695. /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
  5696. /// - c: Assume that extern "C" functions are implicitly nounwind.
  5697. /// The default is /EHs-c-, meaning cleanups are disabled.
  5698. static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
  5699. EHFlags EH;
  5700. std::vector<std::string> EHArgs =
  5701. Args.getAllArgValues(options::OPT__SLASH_EH);
  5702. for (auto EHVal : EHArgs) {
  5703. for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
  5704. switch (EHVal[I]) {
  5705. case 'a':
  5706. EH.Asynch = maybeConsumeDash(EHVal, I);
  5707. if (EH.Asynch)
  5708. EH.Synch = false;
  5709. continue;
  5710. case 'c':
  5711. EH.NoUnwindC = maybeConsumeDash(EHVal, I);
  5712. continue;
  5713. case 's':
  5714. EH.Synch = maybeConsumeDash(EHVal, I);
  5715. if (EH.Synch)
  5716. EH.Asynch = false;
  5717. continue;
  5718. default:
  5719. break;
  5720. }
  5721. D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
  5722. break;
  5723. }
  5724. }
  5725. // The /GX, /GX- flags are only processed if there are not /EH flags.
  5726. // The default is that /GX is not specified.
  5727. if (EHArgs.empty() &&
  5728. Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
  5729. /*default=*/false)) {
  5730. EH.Synch = true;
  5731. EH.NoUnwindC = true;
  5732. }
  5733. return EH;
  5734. }
  5735. void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
  5736. ArgStringList &CmdArgs,
  5737. codegenoptions::DebugInfoKind *DebugInfoKind,
  5738. bool *EmitCodeView) const {
  5739. unsigned RTOptionID = options::OPT__SLASH_MT;
  5740. if (Args.hasArg(options::OPT__SLASH_LDd))
  5741. // The /LDd option implies /MTd. The dependent lib part can be overridden,
  5742. // but defining _DEBUG is sticky.
  5743. RTOptionID = options::OPT__SLASH_MTd;
  5744. if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
  5745. RTOptionID = A->getOption().getID();
  5746. StringRef FlagForCRT;
  5747. switch (RTOptionID) {
  5748. case options::OPT__SLASH_MD:
  5749. if (Args.hasArg(options::OPT__SLASH_LDd))
  5750. CmdArgs.push_back("-D_DEBUG");
  5751. CmdArgs.push_back("-D_MT");
  5752. CmdArgs.push_back("-D_DLL");
  5753. FlagForCRT = "--dependent-lib=msvcrt";
  5754. break;
  5755. case options::OPT__SLASH_MDd:
  5756. CmdArgs.push_back("-D_DEBUG");
  5757. CmdArgs.push_back("-D_MT");
  5758. CmdArgs.push_back("-D_DLL");
  5759. FlagForCRT = "--dependent-lib=msvcrtd";
  5760. break;
  5761. case options::OPT__SLASH_MT:
  5762. if (Args.hasArg(options::OPT__SLASH_LDd))
  5763. CmdArgs.push_back("-D_DEBUG");
  5764. CmdArgs.push_back("-D_MT");
  5765. CmdArgs.push_back("-flto-visibility-public-std");
  5766. FlagForCRT = "--dependent-lib=libcmt";
  5767. break;
  5768. case options::OPT__SLASH_MTd:
  5769. CmdArgs.push_back("-D_DEBUG");
  5770. CmdArgs.push_back("-D_MT");
  5771. CmdArgs.push_back("-flto-visibility-public-std");
  5772. FlagForCRT = "--dependent-lib=libcmtd";
  5773. break;
  5774. default:
  5775. llvm_unreachable("Unexpected option ID.");
  5776. }
  5777. if (Args.hasArg(options::OPT__SLASH_Zl)) {
  5778. CmdArgs.push_back("-D_VC_NODEFAULTLIB");
  5779. } else {
  5780. CmdArgs.push_back(FlagForCRT.data());
  5781. // This provides POSIX compatibility (maps 'open' to '_open'), which most
  5782. // users want. The /Za flag to cl.exe turns this off, but it's not
  5783. // implemented in clang.
  5784. CmdArgs.push_back("--dependent-lib=oldnames");
  5785. }
  5786. // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
  5787. // would produce interleaved output, so ignore /showIncludes in such cases.
  5788. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
  5789. if (Arg *A = Args.getLastArg(options::OPT_show_includes))
  5790. A->render(Args, CmdArgs);
  5791. // This controls whether or not we emit RTTI data for polymorphic types.
  5792. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  5793. /*default=*/false))
  5794. CmdArgs.push_back("-fno-rtti-data");
  5795. // This controls whether or not we emit stack-protector instrumentation.
  5796. // In MSVC, Buffer Security Check (/GS) is on by default.
  5797. if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
  5798. /*default=*/true)) {
  5799. CmdArgs.push_back("-stack-protector");
  5800. CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
  5801. }
  5802. // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
  5803. if (Arg *DebugInfoArg =
  5804. Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
  5805. options::OPT_gline_tables_only)) {
  5806. *EmitCodeView = true;
  5807. if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
  5808. *DebugInfoKind = codegenoptions::LimitedDebugInfo;
  5809. else
  5810. *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
  5811. CmdArgs.push_back("-gcodeview");
  5812. } else {
  5813. *EmitCodeView = false;
  5814. }
  5815. const Driver &D = getToolChain().getDriver();
  5816. EHFlags EH = parseClangCLEHFlags(D, Args);
  5817. if (EH.Synch || EH.Asynch) {
  5818. if (types::isCXX(InputType))
  5819. CmdArgs.push_back("-fcxx-exceptions");
  5820. CmdArgs.push_back("-fexceptions");
  5821. }
  5822. if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
  5823. CmdArgs.push_back("-fexternc-nounwind");
  5824. // /EP should expand to -E -P.
  5825. if (Args.hasArg(options::OPT__SLASH_EP)) {
  5826. CmdArgs.push_back("-E");
  5827. CmdArgs.push_back("-P");
  5828. }
  5829. unsigned VolatileOptionID;
  5830. if (getToolChain().getArch() == llvm::Triple::x86_64 ||
  5831. getToolChain().getArch() == llvm::Triple::x86)
  5832. VolatileOptionID = options::OPT__SLASH_volatile_ms;
  5833. else
  5834. VolatileOptionID = options::OPT__SLASH_volatile_iso;
  5835. if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
  5836. VolatileOptionID = A->getOption().getID();
  5837. if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
  5838. CmdArgs.push_back("-fms-volatile");
  5839. Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
  5840. Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
  5841. if (MostGeneralArg && BestCaseArg)
  5842. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5843. << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
  5844. if (MostGeneralArg) {
  5845. Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
  5846. Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
  5847. Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
  5848. Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
  5849. Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
  5850. if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
  5851. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5852. << FirstConflict->getAsString(Args)
  5853. << SecondConflict->getAsString(Args);
  5854. if (SingleArg)
  5855. CmdArgs.push_back("-fms-memptr-rep=single");
  5856. else if (MultipleArg)
  5857. CmdArgs.push_back("-fms-memptr-rep=multiple");
  5858. else
  5859. CmdArgs.push_back("-fms-memptr-rep=virtual");
  5860. }
  5861. if (Args.getLastArg(options::OPT__SLASH_Gd))
  5862. CmdArgs.push_back("-fdefault-calling-conv=cdecl");
  5863. else if (Args.getLastArg(options::OPT__SLASH_Gr))
  5864. CmdArgs.push_back("-fdefault-calling-conv=fastcall");
  5865. else if (Args.getLastArg(options::OPT__SLASH_Gz))
  5866. CmdArgs.push_back("-fdefault-calling-conv=stdcall");
  5867. else if (Args.getLastArg(options::OPT__SLASH_Gv))
  5868. CmdArgs.push_back("-fdefault-calling-conv=vectorcall");
  5869. if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
  5870. A->render(Args, CmdArgs);
  5871. if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
  5872. CmdArgs.push_back("-fdiagnostics-format");
  5873. if (Args.hasArg(options::OPT__SLASH_fallback))
  5874. CmdArgs.push_back("msvc-fallback");
  5875. else
  5876. CmdArgs.push_back("msvc");
  5877. }
  5878. }
  5879. visualstudio::Compiler *Clang::getCLFallback() const {
  5880. if (!CLFallback)
  5881. CLFallback.reset(new visualstudio::Compiler(getToolChain()));
  5882. return CLFallback.get();
  5883. }
  5884. void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
  5885. ArgStringList &CmdArgs) const {
  5886. StringRef CPUName;
  5887. StringRef ABIName;
  5888. const llvm::Triple &Triple = getToolChain().getTriple();
  5889. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  5890. CmdArgs.push_back("-target-abi");
  5891. CmdArgs.push_back(ABIName.data());
  5892. }
  5893. void ClangAs::AddX86TargetArgs(const ArgList &Args,
  5894. ArgStringList &CmdArgs) const {
  5895. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  5896. StringRef Value = A->getValue();
  5897. if (Value == "intel" || Value == "att") {
  5898. CmdArgs.push_back("-mllvm");
  5899. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  5900. } else {
  5901. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  5902. << A->getOption().getName() << Value;
  5903. }
  5904. }
  5905. }
  5906. void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
  5907. const InputInfo &Output, const InputInfoList &Inputs,
  5908. const ArgList &Args,
  5909. const char *LinkingOutput) const {
  5910. ArgStringList CmdArgs;
  5911. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  5912. const InputInfo &Input = Inputs[0];
  5913. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  5914. const std::string &TripleStr = Triple.getTriple();
  5915. // Don't warn about "clang -w -c foo.s"
  5916. Args.ClaimAllArgs(options::OPT_w);
  5917. // and "clang -emit-llvm -c foo.s"
  5918. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5919. claimNoWarnArgs(Args);
  5920. // Invoke ourselves in -cc1as mode.
  5921. //
  5922. // FIXME: Implement custom jobs for internal actions.
  5923. CmdArgs.push_back("-cc1as");
  5924. // Add the "effective" target triple.
  5925. CmdArgs.push_back("-triple");
  5926. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  5927. // Set the output mode, we currently only expect to be used as a real
  5928. // assembler.
  5929. CmdArgs.push_back("-filetype");
  5930. CmdArgs.push_back("obj");
  5931. // Set the main file name, so that debug info works even with
  5932. // -save-temps or preprocessed assembly.
  5933. CmdArgs.push_back("-main-file-name");
  5934. CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
  5935. // Add the target cpu
  5936. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
  5937. if (!CPU.empty()) {
  5938. CmdArgs.push_back("-target-cpu");
  5939. CmdArgs.push_back(Args.MakeArgString(CPU));
  5940. }
  5941. // Add the target features
  5942. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
  5943. // Ignore explicit -force_cpusubtype_ALL option.
  5944. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  5945. // Pass along any -I options so we get proper .include search paths.
  5946. Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
  5947. // Determine the original source input.
  5948. const Action *SourceAction = &JA;
  5949. while (SourceAction->getKind() != Action::InputClass) {
  5950. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  5951. SourceAction = SourceAction->getInputs()[0];
  5952. }
  5953. // Forward -g and handle debug info related flags, assuming we are dealing
  5954. // with an actual assembly file.
  5955. bool WantDebug = false;
  5956. unsigned DwarfVersion = 0;
  5957. Args.ClaimAllArgs(options::OPT_g_Group);
  5958. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  5959. WantDebug = !A->getOption().matches(options::OPT_g0) &&
  5960. !A->getOption().matches(options::OPT_ggdb0);
  5961. if (WantDebug)
  5962. DwarfVersion = DwarfVersionNum(A->getSpelling());
  5963. }
  5964. if (DwarfVersion == 0)
  5965. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  5966. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  5967. if (SourceAction->getType() == types::TY_Asm ||
  5968. SourceAction->getType() == types::TY_PP_Asm) {
  5969. // You might think that it would be ok to set DebugInfoKind outside of
  5970. // the guard for source type, however there is a test which asserts
  5971. // that some assembler invocation receives no -debug-info-kind,
  5972. // and it's not clear whether that test is just overly restrictive.
  5973. DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
  5974. : codegenoptions::NoDebugInfo);
  5975. // Add the -fdebug-compilation-dir flag if needed.
  5976. addDebugCompDirArg(Args, CmdArgs);
  5977. // Set the AT_producer to the clang version when using the integrated
  5978. // assembler on assembly source files.
  5979. CmdArgs.push_back("-dwarf-debug-producer");
  5980. CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
  5981. // And pass along -I options
  5982. Args.AddAllArgs(CmdArgs, options::OPT_I);
  5983. }
  5984. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
  5985. llvm::DebuggerKind::Default);
  5986. // Handle -fPIC et al -- the relocation-model affects the assembler
  5987. // for some targets.
  5988. llvm::Reloc::Model RelocationModel;
  5989. unsigned PICLevel;
  5990. bool IsPIE;
  5991. std::tie(RelocationModel, PICLevel, IsPIE) =
  5992. ParsePICArgs(getToolChain(), Triple, Args);
  5993. const char *RMName = RelocationModelName(RelocationModel);
  5994. if (RMName) {
  5995. CmdArgs.push_back("-mrelocation-model");
  5996. CmdArgs.push_back(RMName);
  5997. }
  5998. // Optionally embed the -cc1as level arguments into the debug info, for build
  5999. // analysis.
  6000. if (getToolChain().UseDwarfDebugFlags()) {
  6001. ArgStringList OriginalArgs;
  6002. for (const auto &Arg : Args)
  6003. Arg->render(Args, OriginalArgs);
  6004. SmallString<256> Flags;
  6005. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  6006. Flags += Exec;
  6007. for (const char *OriginalArg : OriginalArgs) {
  6008. SmallString<128> EscapedArg;
  6009. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  6010. Flags += " ";
  6011. Flags += EscapedArg;
  6012. }
  6013. CmdArgs.push_back("-dwarf-debug-flags");
  6014. CmdArgs.push_back(Args.MakeArgString(Flags));
  6015. }
  6016. // FIXME: Add -static support, once we have it.
  6017. // Add target specific flags.
  6018. switch (getToolChain().getArch()) {
  6019. default:
  6020. break;
  6021. case llvm::Triple::mips:
  6022. case llvm::Triple::mipsel:
  6023. case llvm::Triple::mips64:
  6024. case llvm::Triple::mips64el:
  6025. AddMIPSTargetArgs(Args, CmdArgs);
  6026. break;
  6027. case llvm::Triple::x86:
  6028. case llvm::Triple::x86_64:
  6029. AddX86TargetArgs(Args, CmdArgs);
  6030. break;
  6031. }
  6032. // Consume all the warning flags. Usually this would be handled more
  6033. // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
  6034. // doesn't handle that so rather than warning about unused flags that are
  6035. // actually used, we'll lie by omission instead.
  6036. // FIXME: Stop lying and consume only the appropriate driver flags
  6037. Args.ClaimAllArgs(options::OPT_W_Group);
  6038. CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
  6039. getToolChain().getDriver());
  6040. Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
  6041. assert(Output.isFilename() && "Unexpected lipo output.");
  6042. CmdArgs.push_back("-o");
  6043. CmdArgs.push_back(Output.getFilename());
  6044. assert(Input.isFilename() && "Invalid input.");
  6045. CmdArgs.push_back(Input.getFilename());
  6046. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  6047. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6048. // Handle the debug info splitting at object creation time if we're
  6049. // creating an object.
  6050. // TODO: Currently only works on linux with newer objcopy.
  6051. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  6052. getToolChain().getTriple().isOSLinux())
  6053. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  6054. SplitDebugName(Args, Input));
  6055. }
  6056. void GnuTool::anchor() {}
  6057. void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
  6058. const InputInfo &Output,
  6059. const InputInfoList &Inputs, const ArgList &Args,
  6060. const char *LinkingOutput) const {
  6061. const Driver &D = getToolChain().getDriver();
  6062. ArgStringList CmdArgs;
  6063. for (const auto &A : Args) {
  6064. if (forwardToGCC(A->getOption())) {
  6065. // It is unfortunate that we have to claim here, as this means
  6066. // we will basically never report anything interesting for
  6067. // platforms using a generic gcc, even if we are just using gcc
  6068. // to get to the assembler.
  6069. A->claim();
  6070. // Don't forward any -g arguments to assembly steps.
  6071. if (isa<AssembleJobAction>(JA) &&
  6072. A->getOption().matches(options::OPT_g_Group))
  6073. continue;
  6074. // Don't forward any -W arguments to assembly and link steps.
  6075. if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
  6076. A->getOption().matches(options::OPT_W_Group))
  6077. continue;
  6078. A->render(Args, CmdArgs);
  6079. }
  6080. }
  6081. RenderExtraToolArgs(JA, CmdArgs);
  6082. // If using a driver driver, force the arch.
  6083. if (getToolChain().getTriple().isOSDarwin()) {
  6084. CmdArgs.push_back("-arch");
  6085. CmdArgs.push_back(
  6086. Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
  6087. }
  6088. // Try to force gcc to match the tool chain we want, if we recognize
  6089. // the arch.
  6090. //
  6091. // FIXME: The triple class should directly provide the information we want
  6092. // here.
  6093. switch (getToolChain().getArch()) {
  6094. default:
  6095. break;
  6096. case llvm::Triple::x86:
  6097. case llvm::Triple::ppc:
  6098. CmdArgs.push_back("-m32");
  6099. break;
  6100. case llvm::Triple::x86_64:
  6101. case llvm::Triple::ppc64:
  6102. case llvm::Triple::ppc64le:
  6103. CmdArgs.push_back("-m64");
  6104. break;
  6105. case llvm::Triple::sparcel:
  6106. CmdArgs.push_back("-EL");
  6107. break;
  6108. }
  6109. if (Output.isFilename()) {
  6110. CmdArgs.push_back("-o");
  6111. CmdArgs.push_back(Output.getFilename());
  6112. } else {
  6113. assert(Output.isNothing() && "Unexpected output");
  6114. CmdArgs.push_back("-fsyntax-only");
  6115. }
  6116. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6117. // Only pass -x if gcc will understand it; otherwise hope gcc
  6118. // understands the suffix correctly. The main use case this would go
  6119. // wrong in is for linker inputs if they happened to have an odd
  6120. // suffix; really the only way to get this to happen is a command
  6121. // like '-x foobar a.c' which will treat a.c like a linker input.
  6122. //
  6123. // FIXME: For the linker case specifically, can we safely convert
  6124. // inputs into '-Wl,' options?
  6125. for (const auto &II : Inputs) {
  6126. // Don't try to pass LLVM or AST inputs to a generic gcc.
  6127. if (types::isLLVMIR(II.getType()))
  6128. D.Diag(diag::err_drv_no_linker_llvm_support)
  6129. << getToolChain().getTripleString();
  6130. else if (II.getType() == types::TY_AST)
  6131. D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
  6132. else if (II.getType() == types::TY_ModuleFile)
  6133. D.Diag(diag::err_drv_no_module_support)
  6134. << getToolChain().getTripleString();
  6135. if (types::canTypeBeUserSpecified(II.getType())) {
  6136. CmdArgs.push_back("-x");
  6137. CmdArgs.push_back(types::getTypeName(II.getType()));
  6138. }
  6139. if (II.isFilename())
  6140. CmdArgs.push_back(II.getFilename());
  6141. else {
  6142. const Arg &A = II.getInputArg();
  6143. // Reverse translate some rewritten options.
  6144. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
  6145. CmdArgs.push_back("-lstdc++");
  6146. continue;
  6147. }
  6148. // Don't render as input, we need gcc to do the translations.
  6149. A.render(Args, CmdArgs);
  6150. }
  6151. }
  6152. const std::string &customGCCName = D.getCCCGenericGCCName();
  6153. const char *GCCName;
  6154. if (!customGCCName.empty())
  6155. GCCName = customGCCName.c_str();
  6156. else if (D.CCCIsCXX()) {
  6157. GCCName = "g++";
  6158. } else
  6159. GCCName = "gcc";
  6160. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
  6161. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6162. }
  6163. void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
  6164. ArgStringList &CmdArgs) const {
  6165. CmdArgs.push_back("-E");
  6166. }
  6167. void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
  6168. ArgStringList &CmdArgs) const {
  6169. const Driver &D = getToolChain().getDriver();
  6170. switch (JA.getType()) {
  6171. // If -flto, etc. are present then make sure not to force assembly output.
  6172. case types::TY_LLVM_IR:
  6173. case types::TY_LTO_IR:
  6174. case types::TY_LLVM_BC:
  6175. case types::TY_LTO_BC:
  6176. CmdArgs.push_back("-c");
  6177. break;
  6178. // We assume we've got an "integrated" assembler in that gcc will produce an
  6179. // object file itself.
  6180. case types::TY_Object:
  6181. CmdArgs.push_back("-c");
  6182. break;
  6183. case types::TY_PP_Asm:
  6184. CmdArgs.push_back("-S");
  6185. break;
  6186. case types::TY_Nothing:
  6187. CmdArgs.push_back("-fsyntax-only");
  6188. break;
  6189. default:
  6190. D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
  6191. }
  6192. }
  6193. void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
  6194. ArgStringList &CmdArgs) const {
  6195. // The types are (hopefully) good enough.
  6196. }
  6197. // Hexagon tools start.
  6198. void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
  6199. ArgStringList &CmdArgs) const {
  6200. }
  6201. void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6202. const InputInfo &Output,
  6203. const InputInfoList &Inputs,
  6204. const ArgList &Args,
  6205. const char *LinkingOutput) const {
  6206. claimNoWarnArgs(Args);
  6207. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  6208. const Driver &D = HTC.getDriver();
  6209. ArgStringList CmdArgs;
  6210. std::string MArchString = "-march=hexagon";
  6211. CmdArgs.push_back(Args.MakeArgString(MArchString));
  6212. RenderExtraToolArgs(JA, CmdArgs);
  6213. std::string AsName = "hexagon-llvm-mc";
  6214. std::string MCpuString = "-mcpu=hexagon" +
  6215. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  6216. CmdArgs.push_back("-filetype=obj");
  6217. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  6218. if (Output.isFilename()) {
  6219. CmdArgs.push_back("-o");
  6220. CmdArgs.push_back(Output.getFilename());
  6221. } else {
  6222. assert(Output.isNothing() && "Unexpected output");
  6223. CmdArgs.push_back("-fsyntax-only");
  6224. }
  6225. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  6226. std::string N = llvm::utostr(G.getValue());
  6227. CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
  6228. }
  6229. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6230. // Only pass -x if gcc will understand it; otherwise hope gcc
  6231. // understands the suffix correctly. The main use case this would go
  6232. // wrong in is for linker inputs if they happened to have an odd
  6233. // suffix; really the only way to get this to happen is a command
  6234. // like '-x foobar a.c' which will treat a.c like a linker input.
  6235. //
  6236. // FIXME: For the linker case specifically, can we safely convert
  6237. // inputs into '-Wl,' options?
  6238. for (const auto &II : Inputs) {
  6239. // Don't try to pass LLVM or AST inputs to a generic gcc.
  6240. if (types::isLLVMIR(II.getType()))
  6241. D.Diag(clang::diag::err_drv_no_linker_llvm_support)
  6242. << HTC.getTripleString();
  6243. else if (II.getType() == types::TY_AST)
  6244. D.Diag(clang::diag::err_drv_no_ast_support)
  6245. << HTC.getTripleString();
  6246. else if (II.getType() == types::TY_ModuleFile)
  6247. D.Diag(diag::err_drv_no_module_support)
  6248. << HTC.getTripleString();
  6249. if (II.isFilename())
  6250. CmdArgs.push_back(II.getFilename());
  6251. else
  6252. // Don't render as input, we need gcc to do the translations.
  6253. // FIXME: What is this?
  6254. II.getInputArg().render(Args, CmdArgs);
  6255. }
  6256. auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
  6257. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6258. }
  6259. void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
  6260. ArgStringList &CmdArgs) const {
  6261. }
  6262. static void
  6263. constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
  6264. const toolchains::HexagonToolChain &HTC,
  6265. const InputInfo &Output, const InputInfoList &Inputs,
  6266. const ArgList &Args, ArgStringList &CmdArgs,
  6267. const char *LinkingOutput) {
  6268. const Driver &D = HTC.getDriver();
  6269. //----------------------------------------------------------------------------
  6270. //
  6271. //----------------------------------------------------------------------------
  6272. bool IsStatic = Args.hasArg(options::OPT_static);
  6273. bool IsShared = Args.hasArg(options::OPT_shared);
  6274. bool IsPIE = Args.hasArg(options::OPT_pie);
  6275. bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
  6276. bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
  6277. bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
  6278. bool UseG0 = false;
  6279. bool UseShared = IsShared && !IsStatic;
  6280. //----------------------------------------------------------------------------
  6281. // Silence warnings for various options
  6282. //----------------------------------------------------------------------------
  6283. Args.ClaimAllArgs(options::OPT_g_Group);
  6284. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6285. Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
  6286. // handled somewhere else.
  6287. Args.ClaimAllArgs(options::OPT_static_libgcc);
  6288. //----------------------------------------------------------------------------
  6289. //
  6290. //----------------------------------------------------------------------------
  6291. if (Args.hasArg(options::OPT_s))
  6292. CmdArgs.push_back("-s");
  6293. if (Args.hasArg(options::OPT_r))
  6294. CmdArgs.push_back("-r");
  6295. for (const auto &Opt : HTC.ExtraOpts)
  6296. CmdArgs.push_back(Opt.c_str());
  6297. CmdArgs.push_back("-march=hexagon");
  6298. std::string CpuVer =
  6299. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  6300. std::string MCpuString = "-mcpu=hexagon" + CpuVer;
  6301. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  6302. if (IsShared) {
  6303. CmdArgs.push_back("-shared");
  6304. // The following should be the default, but doing as hexagon-gcc does.
  6305. CmdArgs.push_back("-call_shared");
  6306. }
  6307. if (IsStatic)
  6308. CmdArgs.push_back("-static");
  6309. if (IsPIE && !IsShared)
  6310. CmdArgs.push_back("-pie");
  6311. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  6312. std::string N = llvm::utostr(G.getValue());
  6313. CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
  6314. UseG0 = G.getValue() == 0;
  6315. }
  6316. //----------------------------------------------------------------------------
  6317. //
  6318. //----------------------------------------------------------------------------
  6319. CmdArgs.push_back("-o");
  6320. CmdArgs.push_back(Output.getFilename());
  6321. //----------------------------------------------------------------------------
  6322. // moslib
  6323. //----------------------------------------------------------------------------
  6324. std::vector<std::string> OsLibs;
  6325. bool HasStandalone = false;
  6326. for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
  6327. A->claim();
  6328. OsLibs.emplace_back(A->getValue());
  6329. HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
  6330. }
  6331. if (OsLibs.empty()) {
  6332. OsLibs.push_back("standalone");
  6333. HasStandalone = true;
  6334. }
  6335. //----------------------------------------------------------------------------
  6336. // Start Files
  6337. //----------------------------------------------------------------------------
  6338. const std::string MCpuSuffix = "/" + CpuVer;
  6339. const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
  6340. const std::string RootDir =
  6341. HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
  6342. const std::string StartSubDir =
  6343. "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
  6344. auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
  6345. const char *Name) -> std::string {
  6346. std::string RelName = SubDir + Name;
  6347. std::string P = HTC.GetFilePath(RelName.c_str());
  6348. if (llvm::sys::fs::exists(P))
  6349. return P;
  6350. return RootDir + RelName;
  6351. };
  6352. if (IncStdLib && IncStartFiles) {
  6353. if (!IsShared) {
  6354. if (HasStandalone) {
  6355. std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
  6356. CmdArgs.push_back(Args.MakeArgString(Crt0SA));
  6357. }
  6358. std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
  6359. CmdArgs.push_back(Args.MakeArgString(Crt0));
  6360. }
  6361. std::string Init = UseShared
  6362. ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
  6363. : Find(RootDir, StartSubDir, "/init.o");
  6364. CmdArgs.push_back(Args.MakeArgString(Init));
  6365. }
  6366. //----------------------------------------------------------------------------
  6367. // Library Search Paths
  6368. //----------------------------------------------------------------------------
  6369. const ToolChain::path_list &LibPaths = HTC.getFilePaths();
  6370. for (const auto &LibPath : LibPaths)
  6371. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
  6372. //----------------------------------------------------------------------------
  6373. //
  6374. //----------------------------------------------------------------------------
  6375. Args.AddAllArgs(CmdArgs,
  6376. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  6377. options::OPT_t, options::OPT_u_Group});
  6378. AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
  6379. //----------------------------------------------------------------------------
  6380. // Libraries
  6381. //----------------------------------------------------------------------------
  6382. if (IncStdLib && IncDefLibs) {
  6383. if (D.CCCIsCXX()) {
  6384. HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
  6385. CmdArgs.push_back("-lm");
  6386. }
  6387. CmdArgs.push_back("--start-group");
  6388. if (!IsShared) {
  6389. for (const std::string &Lib : OsLibs)
  6390. CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
  6391. CmdArgs.push_back("-lc");
  6392. }
  6393. CmdArgs.push_back("-lgcc");
  6394. CmdArgs.push_back("--end-group");
  6395. }
  6396. //----------------------------------------------------------------------------
  6397. // End files
  6398. //----------------------------------------------------------------------------
  6399. if (IncStdLib && IncStartFiles) {
  6400. std::string Fini = UseShared
  6401. ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
  6402. : Find(RootDir, StartSubDir, "/fini.o");
  6403. CmdArgs.push_back(Args.MakeArgString(Fini));
  6404. }
  6405. }
  6406. void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6407. const InputInfo &Output,
  6408. const InputInfoList &Inputs,
  6409. const ArgList &Args,
  6410. const char *LinkingOutput) const {
  6411. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  6412. ArgStringList CmdArgs;
  6413. constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
  6414. LinkingOutput);
  6415. std::string Linker = HTC.GetProgramPath("hexagon-link");
  6416. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  6417. CmdArgs, Inputs));
  6418. }
  6419. // Hexagon tools end.
  6420. void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6421. const InputInfo &Output,
  6422. const InputInfoList &Inputs,
  6423. const ArgList &Args,
  6424. const char *LinkingOutput) const {
  6425. std::string Linker = getToolChain().GetProgramPath(getShortName());
  6426. ArgStringList CmdArgs;
  6427. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6428. CmdArgs.push_back("-shared");
  6429. CmdArgs.push_back("-o");
  6430. CmdArgs.push_back(Output.getFilename());
  6431. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  6432. CmdArgs, Inputs));
  6433. }
  6434. // AMDGPU tools end.
  6435. wasm::Linker::Linker(const ToolChain &TC)
  6436. : GnuTool("wasm::Linker", "lld", TC) {}
  6437. bool wasm::Linker::isLinkJob() const {
  6438. return true;
  6439. }
  6440. bool wasm::Linker::hasIntegratedCPP() const {
  6441. return false;
  6442. }
  6443. void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6444. const InputInfo &Output,
  6445. const InputInfoList &Inputs,
  6446. const ArgList &Args,
  6447. const char *LinkingOutput) const {
  6448. const ToolChain &ToolChain = getToolChain();
  6449. const Driver &D = ToolChain.getDriver();
  6450. const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
  6451. ArgStringList CmdArgs;
  6452. CmdArgs.push_back("-flavor");
  6453. CmdArgs.push_back("ld");
  6454. // Enable garbage collection of unused input sections by default, since code
  6455. // size is of particular importance. This is significantly facilitated by
  6456. // the enabling of -ffunction-sections and -fdata-sections in
  6457. // Clang::ConstructJob.
  6458. if (areOptimizationsEnabled(Args))
  6459. CmdArgs.push_back("--gc-sections");
  6460. if (Args.hasArg(options::OPT_rdynamic))
  6461. CmdArgs.push_back("-export-dynamic");
  6462. if (Args.hasArg(options::OPT_s))
  6463. CmdArgs.push_back("--strip-all");
  6464. if (Args.hasArg(options::OPT_shared))
  6465. CmdArgs.push_back("-shared");
  6466. if (Args.hasArg(options::OPT_static))
  6467. CmdArgs.push_back("-Bstatic");
  6468. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6469. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  6470. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6471. if (Args.hasArg(options::OPT_shared))
  6472. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("rcrt1.o")));
  6473. else if (Args.hasArg(options::OPT_pie))
  6474. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
  6475. else
  6476. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  6477. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  6478. }
  6479. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  6480. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6481. if (D.CCCIsCXX())
  6482. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  6483. if (Args.hasArg(options::OPT_pthread))
  6484. CmdArgs.push_back("-lpthread");
  6485. CmdArgs.push_back("-lc");
  6486. CmdArgs.push_back("-lcompiler_rt");
  6487. }
  6488. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6489. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  6490. CmdArgs.push_back("-o");
  6491. CmdArgs.push_back(Output.getFilename());
  6492. C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
  6493. }
  6494. const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
  6495. std::string MArch;
  6496. if (!Arch.empty())
  6497. MArch = Arch;
  6498. else
  6499. MArch = Triple.getArchName();
  6500. MArch = StringRef(MArch).split("+").first.lower();
  6501. // Handle -march=native.
  6502. if (MArch == "native") {
  6503. std::string CPU = llvm::sys::getHostCPUName();
  6504. if (CPU != "generic") {
  6505. // Translate the native cpu into the architecture suffix for that CPU.
  6506. StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
  6507. // If there is no valid architecture suffix for this CPU we don't know how
  6508. // to handle it, so return no architecture.
  6509. if (Suffix.empty())
  6510. MArch = "";
  6511. else
  6512. MArch = std::string("arm") + Suffix.str();
  6513. }
  6514. }
  6515. return MArch;
  6516. }
  6517. /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
  6518. StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
  6519. std::string MArch = getARMArch(Arch, Triple);
  6520. // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
  6521. // here means an -march=native that we can't handle, so instead return no CPU.
  6522. if (MArch.empty())
  6523. return StringRef();
  6524. // We need to return an empty string here on invalid MArch values as the
  6525. // various places that call this function can't cope with a null result.
  6526. return Triple.getARMCPUForArch(MArch);
  6527. }
  6528. /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
  6529. std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
  6530. const llvm::Triple &Triple) {
  6531. // FIXME: Warn on inconsistent use of -mcpu and -march.
  6532. // If we have -mcpu=, use that.
  6533. if (!CPU.empty()) {
  6534. std::string MCPU = StringRef(CPU).split("+").first.lower();
  6535. // Handle -mcpu=native.
  6536. if (MCPU == "native")
  6537. return llvm::sys::getHostCPUName();
  6538. else
  6539. return MCPU;
  6540. }
  6541. return getARMCPUForMArch(Arch, Triple);
  6542. }
  6543. /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
  6544. /// CPU (or Arch, if CPU is generic).
  6545. // FIXME: This is redundant with -mcpu, why does LLVM use this.
  6546. StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
  6547. const llvm::Triple &Triple) {
  6548. unsigned ArchKind;
  6549. if (CPU == "generic") {
  6550. std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
  6551. ArchKind = llvm::ARM::parseArch(ARMArch);
  6552. if (ArchKind == llvm::ARM::AK_INVALID)
  6553. // In case of generic Arch, i.e. "arm",
  6554. // extract arch from default cpu of the Triple
  6555. ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
  6556. } else {
  6557. // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
  6558. // armv7k triple if it's actually been specified via "-arch armv7k".
  6559. ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
  6560. ? (unsigned)llvm::ARM::AK_ARMV7K
  6561. : llvm::ARM::parseCPUArch(CPU);
  6562. }
  6563. if (ArchKind == llvm::ARM::AK_INVALID)
  6564. return "";
  6565. return llvm::ARM::getSubArch(ArchKind);
  6566. }
  6567. void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
  6568. const llvm::Triple &Triple) {
  6569. if (Args.hasArg(options::OPT_r))
  6570. return;
  6571. // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
  6572. // to generate BE-8 executables.
  6573. if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
  6574. CmdArgs.push_back("--be8");
  6575. }
  6576. mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
  6577. // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
  6578. // was first introduced in Release 3. However, other compilers have
  6579. // traditionally allowed it for Release 2 so we should do the same.
  6580. return (NanEncoding)llvm::StringSwitch<int>(CPU)
  6581. .Case("mips1", NanLegacy)
  6582. .Case("mips2", NanLegacy)
  6583. .Case("mips3", NanLegacy)
  6584. .Case("mips4", NanLegacy)
  6585. .Case("mips5", NanLegacy)
  6586. .Case("mips32", NanLegacy)
  6587. .Case("mips32r2", NanLegacy | Nan2008)
  6588. .Case("mips32r3", NanLegacy | Nan2008)
  6589. .Case("mips32r5", NanLegacy | Nan2008)
  6590. .Case("mips32r6", Nan2008)
  6591. .Case("mips64", NanLegacy)
  6592. .Case("mips64r2", NanLegacy | Nan2008)
  6593. .Case("mips64r3", NanLegacy | Nan2008)
  6594. .Case("mips64r5", NanLegacy | Nan2008)
  6595. .Case("mips64r6", Nan2008)
  6596. .Default(NanLegacy);
  6597. }
  6598. bool mips::hasCompactBranches(StringRef &CPU) {
  6599. // mips32r6 and mips64r6 have compact branches.
  6600. return llvm::StringSwitch<bool>(CPU)
  6601. .Case("mips32r6", true)
  6602. .Case("mips64r6", true)
  6603. .Default(false);
  6604. }
  6605. bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
  6606. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  6607. return A && (A->getValue() == StringRef(Value));
  6608. }
  6609. bool mips::isUCLibc(const ArgList &Args) {
  6610. Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
  6611. return A && A->getOption().matches(options::OPT_muclibc);
  6612. }
  6613. bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
  6614. if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
  6615. return llvm::StringSwitch<bool>(NaNArg->getValue())
  6616. .Case("2008", true)
  6617. .Case("legacy", false)
  6618. .Default(false);
  6619. // NaN2008 is the default for MIPS32r6/MIPS64r6.
  6620. return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
  6621. .Cases("mips32r6", "mips64r6", true)
  6622. .Default(false);
  6623. return false;
  6624. }
  6625. bool mips::isFP64ADefault(const llvm::Triple &Triple, StringRef CPUName) {
  6626. if (!Triple.isAndroid())
  6627. return false;
  6628. // Android MIPS32R6 defaults to FP64A.
  6629. return llvm::StringSwitch<bool>(CPUName)
  6630. .Case("mips32r6", true)
  6631. .Default(false);
  6632. }
  6633. bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
  6634. StringRef ABIName, mips::FloatABI FloatABI) {
  6635. if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
  6636. Triple.getVendor() != llvm::Triple::MipsTechnologies &&
  6637. !Triple.isAndroid())
  6638. return false;
  6639. if (ABIName != "32")
  6640. return false;
  6641. // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
  6642. // present.
  6643. if (FloatABI == mips::FloatABI::Soft)
  6644. return false;
  6645. return llvm::StringSwitch<bool>(CPUName)
  6646. .Cases("mips2", "mips3", "mips4", "mips5", true)
  6647. .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
  6648. .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
  6649. .Default(false);
  6650. }
  6651. bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
  6652. StringRef CPUName, StringRef ABIName,
  6653. mips::FloatABI FloatABI) {
  6654. bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
  6655. // FPXX shouldn't be used if -msingle-float is present.
  6656. if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
  6657. options::OPT_mdouble_float))
  6658. if (A->getOption().matches(options::OPT_msingle_float))
  6659. UseFPXX = false;
  6660. return UseFPXX;
  6661. }
  6662. llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
  6663. // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
  6664. // archs which Darwin doesn't use.
  6665. // The matching this routine does is fairly pointless, since it is neither the
  6666. // complete architecture list, nor a reasonable subset. The problem is that
  6667. // historically the driver driver accepts this and also ties its -march=
  6668. // handling to the architecture name, so we need to be careful before removing
  6669. // support for it.
  6670. // This code must be kept in sync with Clang's Darwin specific argument
  6671. // translation.
  6672. return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
  6673. .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
  6674. .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
  6675. .Case("ppc64", llvm::Triple::ppc64)
  6676. .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
  6677. .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
  6678. llvm::Triple::x86)
  6679. .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
  6680. // This is derived from the driver driver.
  6681. .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
  6682. .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
  6683. .Cases("armv7s", "xscale", llvm::Triple::arm)
  6684. .Case("arm64", llvm::Triple::aarch64)
  6685. .Case("r600", llvm::Triple::r600)
  6686. .Case("amdgcn", llvm::Triple::amdgcn)
  6687. .Case("nvptx", llvm::Triple::nvptx)
  6688. .Case("nvptx64", llvm::Triple::nvptx64)
  6689. .Case("amdil", llvm::Triple::amdil)
  6690. .Case("spir", llvm::Triple::spir)
  6691. .Default(llvm::Triple::UnknownArch);
  6692. }
  6693. void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
  6694. const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
  6695. unsigned ArchKind = llvm::ARM::parseArch(Str);
  6696. T.setArch(Arch);
  6697. if (Str == "x86_64h")
  6698. T.setArchName(Str);
  6699. else if (ArchKind == llvm::ARM::AK_ARMV6M ||
  6700. ArchKind == llvm::ARM::AK_ARMV7M ||
  6701. ArchKind == llvm::ARM::AK_ARMV7EM) {
  6702. T.setOS(llvm::Triple::UnknownOS);
  6703. T.setObjectFormat(llvm::Triple::MachO);
  6704. }
  6705. }
  6706. const char *Clang::getBaseInputName(const ArgList &Args,
  6707. const InputInfo &Input) {
  6708. return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
  6709. }
  6710. const char *Clang::getBaseInputStem(const ArgList &Args,
  6711. const InputInfoList &Inputs) {
  6712. const char *Str = getBaseInputName(Args, Inputs[0]);
  6713. if (const char *End = strrchr(Str, '.'))
  6714. return Args.MakeArgString(std::string(Str, End));
  6715. return Str;
  6716. }
  6717. const char *Clang::getDependencyFileName(const ArgList &Args,
  6718. const InputInfoList &Inputs) {
  6719. // FIXME: Think about this more.
  6720. std::string Res;
  6721. if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
  6722. std::string Str(OutputOpt->getValue());
  6723. Res = Str.substr(0, Str.rfind('.'));
  6724. } else {
  6725. Res = getBaseInputStem(Args, Inputs);
  6726. }
  6727. return Args.MakeArgString(Res + ".d");
  6728. }
  6729. void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6730. const InputInfo &Output,
  6731. const InputInfoList &Inputs,
  6732. const ArgList &Args,
  6733. const char *LinkingOutput) const {
  6734. const ToolChain &ToolChain = getToolChain();
  6735. const Driver &D = ToolChain.getDriver();
  6736. ArgStringList CmdArgs;
  6737. // Silence warning for "clang -g foo.o -o foo"
  6738. Args.ClaimAllArgs(options::OPT_g_Group);
  6739. // and "clang -emit-llvm foo.o -o foo"
  6740. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6741. // and for "clang -w foo.o -o foo". Other warning options are already
  6742. // handled somewhere else.
  6743. Args.ClaimAllArgs(options::OPT_w);
  6744. if (!D.SysRoot.empty())
  6745. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  6746. // CloudABI only supports static linkage.
  6747. CmdArgs.push_back("-Bstatic");
  6748. CmdArgs.push_back("--no-dynamic-linker");
  6749. // Provide PIE linker flags in case PIE is default for the architecture.
  6750. if (ToolChain.isPIEDefault()) {
  6751. CmdArgs.push_back("-pie");
  6752. CmdArgs.push_back("-zrelro");
  6753. }
  6754. CmdArgs.push_back("--eh-frame-hdr");
  6755. CmdArgs.push_back("--gc-sections");
  6756. if (Output.isFilename()) {
  6757. CmdArgs.push_back("-o");
  6758. CmdArgs.push_back(Output.getFilename());
  6759. } else {
  6760. assert(Output.isNothing() && "Invalid output.");
  6761. }
  6762. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6763. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
  6764. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
  6765. }
  6766. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6767. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  6768. Args.AddAllArgs(CmdArgs,
  6769. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  6770. options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
  6771. if (D.isUsingLTO())
  6772. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin, D);
  6773. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  6774. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6775. if (D.CCCIsCXX())
  6776. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  6777. CmdArgs.push_back("-lc");
  6778. CmdArgs.push_back("-lcompiler_rt");
  6779. }
  6780. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6781. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  6782. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  6783. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6784. }
  6785. void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6786. const InputInfo &Output,
  6787. const InputInfoList &Inputs,
  6788. const ArgList &Args,
  6789. const char *LinkingOutput) const {
  6790. ArgStringList CmdArgs;
  6791. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  6792. const InputInfo &Input = Inputs[0];
  6793. // Determine the original source input.
  6794. const Action *SourceAction = &JA;
  6795. while (SourceAction->getKind() != Action::InputClass) {
  6796. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  6797. SourceAction = SourceAction->getInputs()[0];
  6798. }
  6799. // If -fno-integrated-as is used add -Q to the darwin assember driver to make
  6800. // sure it runs its system assembler not clang's integrated assembler.
  6801. // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
  6802. // FIXME: at run-time detect assembler capabilities or rely on version
  6803. // information forwarded by -target-assembler-version.
  6804. if (Args.hasArg(options::OPT_fno_integrated_as)) {
  6805. const llvm::Triple &T(getToolChain().getTriple());
  6806. if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
  6807. CmdArgs.push_back("-Q");
  6808. }
  6809. // Forward -g, assuming we are dealing with an actual assembly file.
  6810. if (SourceAction->getType() == types::TY_Asm ||
  6811. SourceAction->getType() == types::TY_PP_Asm) {
  6812. if (Args.hasArg(options::OPT_gstabs))
  6813. CmdArgs.push_back("--gstabs");
  6814. else if (Args.hasArg(options::OPT_g_Group))
  6815. CmdArgs.push_back("-g");
  6816. }
  6817. // Derived from asm spec.
  6818. AddMachOArch(Args, CmdArgs);
  6819. // Use -force_cpusubtype_ALL on x86 by default.
  6820. if (getToolChain().getArch() == llvm::Triple::x86 ||
  6821. getToolChain().getArch() == llvm::Triple::x86_64 ||
  6822. Args.hasArg(options::OPT_force__cpusubtype__ALL))
  6823. CmdArgs.push_back("-force_cpusubtype_ALL");
  6824. if (getToolChain().getArch() != llvm::Triple::x86_64 &&
  6825. (((Args.hasArg(options::OPT_mkernel) ||
  6826. Args.hasArg(options::OPT_fapple_kext)) &&
  6827. getMachOToolChain().isKernelStatic()) ||
  6828. Args.hasArg(options::OPT_static)))
  6829. CmdArgs.push_back("-static");
  6830. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6831. assert(Output.isFilename() && "Unexpected lipo output.");
  6832. CmdArgs.push_back("-o");
  6833. CmdArgs.push_back(Output.getFilename());
  6834. assert(Input.isFilename() && "Invalid input.");
  6835. CmdArgs.push_back(Input.getFilename());
  6836. // asm_final spec is empty.
  6837. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6838. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6839. }
  6840. void darwin::MachOTool::anchor() {}
  6841. void darwin::MachOTool::AddMachOArch(const ArgList &Args,
  6842. ArgStringList &CmdArgs) const {
  6843. StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
  6844. // Derived from darwin_arch spec.
  6845. CmdArgs.push_back("-arch");
  6846. CmdArgs.push_back(Args.MakeArgString(ArchName));
  6847. // FIXME: Is this needed anymore?
  6848. if (ArchName == "arm")
  6849. CmdArgs.push_back("-force_cpusubtype_ALL");
  6850. }
  6851. bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
  6852. // We only need to generate a temp path for LTO if we aren't compiling object
  6853. // files. When compiling source files, we run 'dsymutil' after linking. We
  6854. // don't run 'dsymutil' when compiling object files.
  6855. for (const auto &Input : Inputs)
  6856. if (Input.getType() != types::TY_Object)
  6857. return true;
  6858. return false;
  6859. }
  6860. /// \brief Pass -no_deduplicate to ld64 under certain conditions:
  6861. ///
  6862. /// - Either -O0 or -O1 is explicitly specified
  6863. /// - No -O option is specified *and* this is a compile+link (implicit -O0)
  6864. ///
  6865. /// Also do *not* add -no_deduplicate when no -O option is specified and this
  6866. /// is just a link (we can't imply -O0)
  6867. static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args) {
  6868. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  6869. if (A->getOption().matches(options::OPT_O0))
  6870. return true;
  6871. if (A->getOption().matches(options::OPT_O))
  6872. return llvm::StringSwitch<bool>(A->getValue())
  6873. .Case("1", true)
  6874. .Default(false);
  6875. return false; // OPT_Ofast & OPT_O4
  6876. }
  6877. if (!IsLinkerOnlyAction) // Implicit -O0 for compile+linker only.
  6878. return true;
  6879. return false;
  6880. }
  6881. void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
  6882. ArgStringList &CmdArgs,
  6883. const InputInfoList &Inputs) const {
  6884. const Driver &D = getToolChain().getDriver();
  6885. const toolchains::MachO &MachOTC = getMachOToolChain();
  6886. unsigned Version[5] = {0, 0, 0, 0, 0};
  6887. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  6888. if (!Driver::GetReleaseVersion(A->getValue(), Version))
  6889. D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
  6890. }
  6891. // Newer linkers support -demangle. Pass it if supported and not disabled by
  6892. // the user.
  6893. if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  6894. CmdArgs.push_back("-demangle");
  6895. if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
  6896. CmdArgs.push_back("-export_dynamic");
  6897. // If we are using App Extension restrictions, pass a flag to the linker
  6898. // telling it that the compiled code has been audited.
  6899. if (Args.hasFlag(options::OPT_fapplication_extension,
  6900. options::OPT_fno_application_extension, false))
  6901. CmdArgs.push_back("-application_extension");
  6902. if (D.isUsingLTO()) {
  6903. // If we are using LTO, then automatically create a temporary file path for
  6904. // the linker to use, so that it's lifetime will extend past a possible
  6905. // dsymutil step.
  6906. if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
  6907. const char *TmpPath = C.getArgs().MakeArgString(
  6908. D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
  6909. C.addTempFile(TmpPath);
  6910. CmdArgs.push_back("-object_path_lto");
  6911. CmdArgs.push_back(TmpPath);
  6912. }
  6913. }
  6914. // Use -lto_library option to specify the libLTO.dylib path. Try to find
  6915. // it in clang installed libraries. If not found, the option is not used
  6916. // and 'ld' will use its default mechanism to search for libLTO.dylib.
  6917. if (Version[0] >= 133) {
  6918. // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
  6919. StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
  6920. SmallString<128> LibLTOPath(P);
  6921. llvm::sys::path::append(LibLTOPath, "lib");
  6922. llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
  6923. if (llvm::sys::fs::exists(LibLTOPath)) {
  6924. CmdArgs.push_back("-lto_library");
  6925. CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
  6926. } else {
  6927. D.Diag(diag::warn_drv_lto_libpath);
  6928. }
  6929. }
  6930. // ld64 version 262 and above run the deduplicate pass by default.
  6931. if (Version[0] >= 262 && shouldLinkerNotDedup(C.getJobs().empty(), Args))
  6932. CmdArgs.push_back("-no_deduplicate");
  6933. // Derived from the "link" spec.
  6934. Args.AddAllArgs(CmdArgs, options::OPT_static);
  6935. if (!Args.hasArg(options::OPT_static))
  6936. CmdArgs.push_back("-dynamic");
  6937. if (Args.hasArg(options::OPT_fgnu_runtime)) {
  6938. // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
  6939. // here. How do we wish to handle such things?
  6940. }
  6941. if (!Args.hasArg(options::OPT_dynamiclib)) {
  6942. AddMachOArch(Args, CmdArgs);
  6943. // FIXME: Why do this only on this path?
  6944. Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
  6945. Args.AddLastArg(CmdArgs, options::OPT_bundle);
  6946. Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
  6947. Args.AddAllArgs(CmdArgs, options::OPT_client__name);
  6948. Arg *A;
  6949. if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
  6950. (A = Args.getLastArg(options::OPT_current__version)) ||
  6951. (A = Args.getLastArg(options::OPT_install__name)))
  6952. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  6953. << "-dynamiclib";
  6954. Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
  6955. Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
  6956. Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
  6957. } else {
  6958. CmdArgs.push_back("-dylib");
  6959. Arg *A;
  6960. if ((A = Args.getLastArg(options::OPT_bundle)) ||
  6961. (A = Args.getLastArg(options::OPT_bundle__loader)) ||
  6962. (A = Args.getLastArg(options::OPT_client__name)) ||
  6963. (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
  6964. (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
  6965. (A = Args.getLastArg(options::OPT_private__bundle)))
  6966. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  6967. << "-dynamiclib";
  6968. Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
  6969. "-dylib_compatibility_version");
  6970. Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
  6971. "-dylib_current_version");
  6972. AddMachOArch(Args, CmdArgs);
  6973. Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
  6974. "-dylib_install_name");
  6975. }
  6976. Args.AddLastArg(CmdArgs, options::OPT_all__load);
  6977. Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
  6978. Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
  6979. if (MachOTC.isTargetIOSBased())
  6980. Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
  6981. Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
  6982. Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
  6983. Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
  6984. Args.AddLastArg(CmdArgs, options::OPT_dynamic);
  6985. Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
  6986. Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
  6987. Args.AddAllArgs(CmdArgs, options::OPT_force__load);
  6988. Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
  6989. Args.AddAllArgs(CmdArgs, options::OPT_image__base);
  6990. Args.AddAllArgs(CmdArgs, options::OPT_init);
  6991. // Add the deployment target.
  6992. MachOTC.addMinVersionArgs(Args, CmdArgs);
  6993. Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
  6994. Args.AddLastArg(CmdArgs, options::OPT_multi__module);
  6995. Args.AddLastArg(CmdArgs, options::OPT_single__module);
  6996. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
  6997. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
  6998. if (const Arg *A =
  6999. Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
  7000. options::OPT_fno_pie, options::OPT_fno_PIE)) {
  7001. if (A->getOption().matches(options::OPT_fpie) ||
  7002. A->getOption().matches(options::OPT_fPIE))
  7003. CmdArgs.push_back("-pie");
  7004. else
  7005. CmdArgs.push_back("-no_pie");
  7006. }
  7007. // for embed-bitcode, use -bitcode_bundle in linker command
  7008. if (C.getDriver().embedBitcodeEnabled() ||
  7009. C.getDriver().embedBitcodeMarkerOnly()) {
  7010. // Check if the toolchain supports bitcode build flow.
  7011. if (MachOTC.SupportsEmbeddedBitcode())
  7012. CmdArgs.push_back("-bitcode_bundle");
  7013. else
  7014. D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
  7015. }
  7016. Args.AddLastArg(CmdArgs, options::OPT_prebind);
  7017. Args.AddLastArg(CmdArgs, options::OPT_noprebind);
  7018. Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
  7019. Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
  7020. Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
  7021. Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
  7022. Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
  7023. Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
  7024. Args.AddAllArgs(CmdArgs, options::OPT_segprot);
  7025. Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
  7026. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
  7027. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
  7028. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
  7029. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
  7030. Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
  7031. Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
  7032. // Give --sysroot= preference, over the Apple specific behavior to also use
  7033. // --isysroot as the syslibroot.
  7034. StringRef sysroot = C.getSysRoot();
  7035. if (sysroot != "") {
  7036. CmdArgs.push_back("-syslibroot");
  7037. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  7038. } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  7039. CmdArgs.push_back("-syslibroot");
  7040. CmdArgs.push_back(A->getValue());
  7041. }
  7042. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
  7043. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
  7044. Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
  7045. Args.AddAllArgs(CmdArgs, options::OPT_undefined);
  7046. Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
  7047. Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
  7048. Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
  7049. Args.AddAllArgs(CmdArgs, options::OPT_y);
  7050. Args.AddLastArg(CmdArgs, options::OPT_w);
  7051. Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
  7052. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
  7053. Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
  7054. Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
  7055. Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
  7056. Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
  7057. Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
  7058. Args.AddLastArg(CmdArgs, options::OPT_whyload);
  7059. Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
  7060. Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
  7061. Args.AddLastArg(CmdArgs, options::OPT_dylinker);
  7062. Args.AddLastArg(CmdArgs, options::OPT_Mach);
  7063. }
  7064. void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7065. const InputInfo &Output,
  7066. const InputInfoList &Inputs,
  7067. const ArgList &Args,
  7068. const char *LinkingOutput) const {
  7069. assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
  7070. // If the number of arguments surpasses the system limits, we will encode the
  7071. // input files in a separate file, shortening the command line. To this end,
  7072. // build a list of input file names that can be passed via a file with the
  7073. // -filelist linker option.
  7074. llvm::opt::ArgStringList InputFileList;
  7075. // The logic here is derived from gcc's behavior; most of which
  7076. // comes from specs (starting with link_command). Consult gcc for
  7077. // more information.
  7078. ArgStringList CmdArgs;
  7079. /// Hack(tm) to ignore linking errors when we are doing ARC migration.
  7080. if (Args.hasArg(options::OPT_ccc_arcmt_check,
  7081. options::OPT_ccc_arcmt_migrate)) {
  7082. for (const auto &Arg : Args)
  7083. Arg->claim();
  7084. const char *Exec =
  7085. Args.MakeArgString(getToolChain().GetProgramPath("touch"));
  7086. CmdArgs.push_back(Output.getFilename());
  7087. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
  7088. return;
  7089. }
  7090. // I'm not sure why this particular decomposition exists in gcc, but
  7091. // we follow suite for ease of comparison.
  7092. AddLinkArgs(C, Args, CmdArgs, Inputs);
  7093. // It seems that the 'e' option is completely ignored for dynamic executables
  7094. // (the default), and with static executables, the last one wins, as expected.
  7095. Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
  7096. options::OPT_Z_Flag, options::OPT_u_Group,
  7097. options::OPT_e, options::OPT_r});
  7098. // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
  7099. // members of static archive libraries which implement Objective-C classes or
  7100. // categories.
  7101. if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
  7102. CmdArgs.push_back("-ObjC");
  7103. CmdArgs.push_back("-o");
  7104. CmdArgs.push_back(Output.getFilename());
  7105. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  7106. getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
  7107. // SafeStack requires its own runtime libraries
  7108. // These libraries should be linked first, to make sure the
  7109. // __safestack_init constructor executes before everything else
  7110. if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
  7111. getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
  7112. "libclang_rt.safestack_osx.a",
  7113. /*AlwaysLink=*/true);
  7114. }
  7115. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7116. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7117. // Build the input file for -filelist (list of linker input files) in case we
  7118. // need it later
  7119. for (const auto &II : Inputs) {
  7120. if (!II.isFilename()) {
  7121. // This is a linker input argument.
  7122. // We cannot mix input arguments and file names in a -filelist input, thus
  7123. // we prematurely stop our list (remaining files shall be passed as
  7124. // arguments).
  7125. if (InputFileList.size() > 0)
  7126. break;
  7127. continue;
  7128. }
  7129. InputFileList.push_back(II.getFilename());
  7130. }
  7131. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
  7132. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  7133. if (isObjCRuntimeLinked(Args) &&
  7134. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7135. // We use arclite library for both ARC and subscripting support.
  7136. getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
  7137. CmdArgs.push_back("-framework");
  7138. CmdArgs.push_back("Foundation");
  7139. // Link libobj.
  7140. CmdArgs.push_back("-lobjc");
  7141. }
  7142. if (LinkingOutput) {
  7143. CmdArgs.push_back("-arch_multiple");
  7144. CmdArgs.push_back("-final_output");
  7145. CmdArgs.push_back(LinkingOutput);
  7146. }
  7147. if (Args.hasArg(options::OPT_fnested_functions))
  7148. CmdArgs.push_back("-allow_stack_execute");
  7149. getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
  7150. if (unsigned Parallelism =
  7151. getLTOParallelism(Args, getToolChain().getDriver())) {
  7152. CmdArgs.push_back("-mllvm");
  7153. CmdArgs.push_back(
  7154. Args.MakeArgString(Twine("-threads=") + llvm::to_string(Parallelism)));
  7155. }
  7156. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7157. if (getToolChain().getDriver().CCCIsCXX())
  7158. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7159. // link_ssp spec is empty.
  7160. // Let the tool chain choose which runtime library to link.
  7161. getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
  7162. }
  7163. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7164. // endfile_spec is empty.
  7165. }
  7166. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  7167. Args.AddAllArgs(CmdArgs, options::OPT_F);
  7168. // -iframework should be forwarded as -F.
  7169. for (const Arg *A : Args.filtered(options::OPT_iframework))
  7170. CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
  7171. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7172. if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
  7173. if (A->getValue() == StringRef("Accelerate")) {
  7174. CmdArgs.push_back("-framework");
  7175. CmdArgs.push_back("Accelerate");
  7176. }
  7177. }
  7178. }
  7179. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7180. std::unique_ptr<Command> Cmd =
  7181. llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
  7182. Cmd->setInputFileList(std::move(InputFileList));
  7183. C.addCommand(std::move(Cmd));
  7184. }
  7185. void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
  7186. const InputInfo &Output,
  7187. const InputInfoList &Inputs,
  7188. const ArgList &Args,
  7189. const char *LinkingOutput) const {
  7190. ArgStringList CmdArgs;
  7191. CmdArgs.push_back("-create");
  7192. assert(Output.isFilename() && "Unexpected lipo output.");
  7193. CmdArgs.push_back("-output");
  7194. CmdArgs.push_back(Output.getFilename());
  7195. for (const auto &II : Inputs) {
  7196. assert(II.isFilename() && "Unexpected lipo input.");
  7197. CmdArgs.push_back(II.getFilename());
  7198. }
  7199. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
  7200. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7201. }
  7202. void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
  7203. const InputInfo &Output,
  7204. const InputInfoList &Inputs,
  7205. const ArgList &Args,
  7206. const char *LinkingOutput) const {
  7207. ArgStringList CmdArgs;
  7208. CmdArgs.push_back("-o");
  7209. CmdArgs.push_back(Output.getFilename());
  7210. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  7211. const InputInfo &Input = Inputs[0];
  7212. assert(Input.isFilename() && "Unexpected dsymutil input.");
  7213. CmdArgs.push_back(Input.getFilename());
  7214. const char *Exec =
  7215. Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
  7216. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7217. }
  7218. void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
  7219. const InputInfo &Output,
  7220. const InputInfoList &Inputs,
  7221. const ArgList &Args,
  7222. const char *LinkingOutput) const {
  7223. ArgStringList CmdArgs;
  7224. CmdArgs.push_back("--verify");
  7225. CmdArgs.push_back("--debug-info");
  7226. CmdArgs.push_back("--eh-frame");
  7227. CmdArgs.push_back("--quiet");
  7228. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  7229. const InputInfo &Input = Inputs[0];
  7230. assert(Input.isFilename() && "Unexpected verify input");
  7231. // Grabbing the output of the earlier dsymutil run.
  7232. CmdArgs.push_back(Input.getFilename());
  7233. const char *Exec =
  7234. Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
  7235. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7236. }
  7237. void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7238. const InputInfo &Output,
  7239. const InputInfoList &Inputs,
  7240. const ArgList &Args,
  7241. const char *LinkingOutput) const {
  7242. claimNoWarnArgs(Args);
  7243. ArgStringList CmdArgs;
  7244. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7245. CmdArgs.push_back("-o");
  7246. CmdArgs.push_back(Output.getFilename());
  7247. for (const auto &II : Inputs)
  7248. CmdArgs.push_back(II.getFilename());
  7249. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7250. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7251. }
  7252. void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7253. const InputInfo &Output,
  7254. const InputInfoList &Inputs,
  7255. const ArgList &Args,
  7256. const char *LinkingOutput) const {
  7257. ArgStringList CmdArgs;
  7258. // Demangle C++ names in errors
  7259. CmdArgs.push_back("-C");
  7260. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  7261. CmdArgs.push_back("-e");
  7262. CmdArgs.push_back("_start");
  7263. }
  7264. if (Args.hasArg(options::OPT_static)) {
  7265. CmdArgs.push_back("-Bstatic");
  7266. CmdArgs.push_back("-dn");
  7267. } else {
  7268. CmdArgs.push_back("-Bdynamic");
  7269. if (Args.hasArg(options::OPT_shared)) {
  7270. CmdArgs.push_back("-shared");
  7271. } else {
  7272. CmdArgs.push_back("--dynamic-linker");
  7273. CmdArgs.push_back(
  7274. Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
  7275. }
  7276. }
  7277. if (Output.isFilename()) {
  7278. CmdArgs.push_back("-o");
  7279. CmdArgs.push_back(Output.getFilename());
  7280. } else {
  7281. assert(Output.isNothing() && "Invalid output.");
  7282. }
  7283. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7284. if (!Args.hasArg(options::OPT_shared))
  7285. CmdArgs.push_back(
  7286. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  7287. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7288. CmdArgs.push_back(
  7289. Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
  7290. CmdArgs.push_back(
  7291. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7292. }
  7293. getToolChain().AddFilePathLibArgs(Args, CmdArgs);
  7294. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  7295. options::OPT_e, options::OPT_r});
  7296. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7297. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7298. if (getToolChain().getDriver().CCCIsCXX())
  7299. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7300. CmdArgs.push_back("-lgcc_s");
  7301. CmdArgs.push_back("-lc");
  7302. if (!Args.hasArg(options::OPT_shared)) {
  7303. CmdArgs.push_back("-lgcc");
  7304. CmdArgs.push_back("-lm");
  7305. }
  7306. }
  7307. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7308. CmdArgs.push_back(
  7309. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7310. }
  7311. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  7312. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7313. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7314. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7315. }
  7316. void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7317. const InputInfo &Output,
  7318. const InputInfoList &Inputs,
  7319. const ArgList &Args,
  7320. const char *LinkingOutput) const {
  7321. claimNoWarnArgs(Args);
  7322. ArgStringList CmdArgs;
  7323. switch (getToolChain().getArch()) {
  7324. case llvm::Triple::x86:
  7325. // When building 32-bit code on OpenBSD/amd64, we have to explicitly
  7326. // instruct as in the base system to assemble 32-bit code.
  7327. CmdArgs.push_back("--32");
  7328. break;
  7329. case llvm::Triple::ppc:
  7330. CmdArgs.push_back("-mppc");
  7331. CmdArgs.push_back("-many");
  7332. break;
  7333. case llvm::Triple::sparc:
  7334. case llvm::Triple::sparcel: {
  7335. CmdArgs.push_back("-32");
  7336. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7337. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7338. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7339. break;
  7340. }
  7341. case llvm::Triple::sparcv9: {
  7342. CmdArgs.push_back("-64");
  7343. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7344. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7345. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7346. break;
  7347. }
  7348. case llvm::Triple::mips64:
  7349. case llvm::Triple::mips64el: {
  7350. StringRef CPUName;
  7351. StringRef ABIName;
  7352. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7353. CmdArgs.push_back("-mabi");
  7354. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  7355. if (getToolChain().getArch() == llvm::Triple::mips64)
  7356. CmdArgs.push_back("-EB");
  7357. else
  7358. CmdArgs.push_back("-EL");
  7359. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7360. break;
  7361. }
  7362. default:
  7363. break;
  7364. }
  7365. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7366. CmdArgs.push_back("-o");
  7367. CmdArgs.push_back(Output.getFilename());
  7368. for (const auto &II : Inputs)
  7369. CmdArgs.push_back(II.getFilename());
  7370. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7371. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7372. }
  7373. void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7374. const InputInfo &Output,
  7375. const InputInfoList &Inputs,
  7376. const ArgList &Args,
  7377. const char *LinkingOutput) const {
  7378. const Driver &D = getToolChain().getDriver();
  7379. ArgStringList CmdArgs;
  7380. // Silence warning for "clang -g foo.o -o foo"
  7381. Args.ClaimAllArgs(options::OPT_g_Group);
  7382. // and "clang -emit-llvm foo.o -o foo"
  7383. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7384. // and for "clang -w foo.o -o foo". Other warning options are already
  7385. // handled somewhere else.
  7386. Args.ClaimAllArgs(options::OPT_w);
  7387. if (getToolChain().getArch() == llvm::Triple::mips64)
  7388. CmdArgs.push_back("-EB");
  7389. else if (getToolChain().getArch() == llvm::Triple::mips64el)
  7390. CmdArgs.push_back("-EL");
  7391. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  7392. CmdArgs.push_back("-e");
  7393. CmdArgs.push_back("__start");
  7394. }
  7395. if (Args.hasArg(options::OPT_static)) {
  7396. CmdArgs.push_back("-Bstatic");
  7397. } else {
  7398. if (Args.hasArg(options::OPT_rdynamic))
  7399. CmdArgs.push_back("-export-dynamic");
  7400. CmdArgs.push_back("--eh-frame-hdr");
  7401. CmdArgs.push_back("-Bdynamic");
  7402. if (Args.hasArg(options::OPT_shared)) {
  7403. CmdArgs.push_back("-shared");
  7404. } else {
  7405. CmdArgs.push_back("-dynamic-linker");
  7406. CmdArgs.push_back("/usr/libexec/ld.so");
  7407. }
  7408. }
  7409. if (Args.hasArg(options::OPT_nopie))
  7410. CmdArgs.push_back("-nopie");
  7411. if (Output.isFilename()) {
  7412. CmdArgs.push_back("-o");
  7413. CmdArgs.push_back(Output.getFilename());
  7414. } else {
  7415. assert(Output.isNothing() && "Invalid output.");
  7416. }
  7417. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7418. if (!Args.hasArg(options::OPT_shared)) {
  7419. if (Args.hasArg(options::OPT_pg))
  7420. CmdArgs.push_back(
  7421. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  7422. else
  7423. CmdArgs.push_back(
  7424. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  7425. CmdArgs.push_back(
  7426. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7427. } else {
  7428. CmdArgs.push_back(
  7429. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7430. }
  7431. }
  7432. std::string Triple = getToolChain().getTripleString();
  7433. if (Triple.substr(0, 6) == "x86_64")
  7434. Triple.replace(0, 6, "amd64");
  7435. CmdArgs.push_back(
  7436. Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
  7437. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  7438. options::OPT_e, options::OPT_s, options::OPT_t,
  7439. options::OPT_Z_Flag, options::OPT_r});
  7440. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7441. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7442. if (D.CCCIsCXX()) {
  7443. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7444. if (Args.hasArg(options::OPT_pg))
  7445. CmdArgs.push_back("-lm_p");
  7446. else
  7447. CmdArgs.push_back("-lm");
  7448. }
  7449. // FIXME: For some reason GCC passes -lgcc before adding
  7450. // the default system libraries. Just mimic this for now.
  7451. CmdArgs.push_back("-lgcc");
  7452. if (Args.hasArg(options::OPT_pthread)) {
  7453. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  7454. CmdArgs.push_back("-lpthread_p");
  7455. else
  7456. CmdArgs.push_back("-lpthread");
  7457. }
  7458. if (!Args.hasArg(options::OPT_shared)) {
  7459. if (Args.hasArg(options::OPT_pg))
  7460. CmdArgs.push_back("-lc_p");
  7461. else
  7462. CmdArgs.push_back("-lc");
  7463. }
  7464. CmdArgs.push_back("-lgcc");
  7465. }
  7466. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7467. if (!Args.hasArg(options::OPT_shared))
  7468. CmdArgs.push_back(
  7469. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7470. else
  7471. CmdArgs.push_back(
  7472. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7473. }
  7474. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7475. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7476. }
  7477. void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7478. const InputInfo &Output,
  7479. const InputInfoList &Inputs,
  7480. const ArgList &Args,
  7481. const char *LinkingOutput) const {
  7482. claimNoWarnArgs(Args);
  7483. ArgStringList CmdArgs;
  7484. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7485. CmdArgs.push_back("-o");
  7486. CmdArgs.push_back(Output.getFilename());
  7487. for (const auto &II : Inputs)
  7488. CmdArgs.push_back(II.getFilename());
  7489. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7490. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7491. }
  7492. void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7493. const InputInfo &Output,
  7494. const InputInfoList &Inputs,
  7495. const ArgList &Args,
  7496. const char *LinkingOutput) const {
  7497. const Driver &D = getToolChain().getDriver();
  7498. ArgStringList CmdArgs;
  7499. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  7500. CmdArgs.push_back("-e");
  7501. CmdArgs.push_back("__start");
  7502. }
  7503. if (Args.hasArg(options::OPT_static)) {
  7504. CmdArgs.push_back("-Bstatic");
  7505. } else {
  7506. if (Args.hasArg(options::OPT_rdynamic))
  7507. CmdArgs.push_back("-export-dynamic");
  7508. CmdArgs.push_back("--eh-frame-hdr");
  7509. CmdArgs.push_back("-Bdynamic");
  7510. if (Args.hasArg(options::OPT_shared)) {
  7511. CmdArgs.push_back("-shared");
  7512. } else {
  7513. CmdArgs.push_back("-dynamic-linker");
  7514. CmdArgs.push_back("/usr/libexec/ld.so");
  7515. }
  7516. }
  7517. if (Output.isFilename()) {
  7518. CmdArgs.push_back("-o");
  7519. CmdArgs.push_back(Output.getFilename());
  7520. } else {
  7521. assert(Output.isNothing() && "Invalid output.");
  7522. }
  7523. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7524. if (!Args.hasArg(options::OPT_shared)) {
  7525. if (Args.hasArg(options::OPT_pg))
  7526. CmdArgs.push_back(
  7527. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  7528. else
  7529. CmdArgs.push_back(
  7530. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  7531. CmdArgs.push_back(
  7532. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7533. } else {
  7534. CmdArgs.push_back(
  7535. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7536. }
  7537. }
  7538. Args.AddAllArgs(CmdArgs,
  7539. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  7540. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7541. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7542. if (D.CCCIsCXX()) {
  7543. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7544. if (Args.hasArg(options::OPT_pg))
  7545. CmdArgs.push_back("-lm_p");
  7546. else
  7547. CmdArgs.push_back("-lm");
  7548. }
  7549. if (Args.hasArg(options::OPT_pthread)) {
  7550. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  7551. CmdArgs.push_back("-lpthread_p");
  7552. else
  7553. CmdArgs.push_back("-lpthread");
  7554. }
  7555. if (!Args.hasArg(options::OPT_shared)) {
  7556. if (Args.hasArg(options::OPT_pg))
  7557. CmdArgs.push_back("-lc_p");
  7558. else
  7559. CmdArgs.push_back("-lc");
  7560. }
  7561. StringRef MyArch;
  7562. switch (getToolChain().getArch()) {
  7563. case llvm::Triple::arm:
  7564. MyArch = "arm";
  7565. break;
  7566. case llvm::Triple::x86:
  7567. MyArch = "i386";
  7568. break;
  7569. case llvm::Triple::x86_64:
  7570. MyArch = "amd64";
  7571. break;
  7572. default:
  7573. llvm_unreachable("Unsupported architecture");
  7574. }
  7575. CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
  7576. }
  7577. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7578. if (!Args.hasArg(options::OPT_shared))
  7579. CmdArgs.push_back(
  7580. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7581. else
  7582. CmdArgs.push_back(
  7583. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7584. }
  7585. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7586. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7587. }
  7588. void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7589. const InputInfo &Output,
  7590. const InputInfoList &Inputs,
  7591. const ArgList &Args,
  7592. const char *LinkingOutput) const {
  7593. claimNoWarnArgs(Args);
  7594. ArgStringList CmdArgs;
  7595. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  7596. // instruct as in the base system to assemble 32-bit code.
  7597. switch (getToolChain().getArch()) {
  7598. default:
  7599. break;
  7600. case llvm::Triple::x86:
  7601. CmdArgs.push_back("--32");
  7602. break;
  7603. case llvm::Triple::ppc:
  7604. CmdArgs.push_back("-a32");
  7605. break;
  7606. case llvm::Triple::mips:
  7607. case llvm::Triple::mipsel:
  7608. case llvm::Triple::mips64:
  7609. case llvm::Triple::mips64el: {
  7610. StringRef CPUName;
  7611. StringRef ABIName;
  7612. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7613. CmdArgs.push_back("-march");
  7614. CmdArgs.push_back(CPUName.data());
  7615. CmdArgs.push_back("-mabi");
  7616. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  7617. if (getToolChain().getArch() == llvm::Triple::mips ||
  7618. getToolChain().getArch() == llvm::Triple::mips64)
  7619. CmdArgs.push_back("-EB");
  7620. else
  7621. CmdArgs.push_back("-EL");
  7622. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  7623. StringRef v = A->getValue();
  7624. CmdArgs.push_back(Args.MakeArgString("-G" + v));
  7625. A->claim();
  7626. }
  7627. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7628. break;
  7629. }
  7630. case llvm::Triple::arm:
  7631. case llvm::Triple::armeb:
  7632. case llvm::Triple::thumb:
  7633. case llvm::Triple::thumbeb: {
  7634. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  7635. if (ABI == arm::FloatABI::Hard)
  7636. CmdArgs.push_back("-mfpu=vfp");
  7637. else
  7638. CmdArgs.push_back("-mfpu=softvfp");
  7639. switch (getToolChain().getTriple().getEnvironment()) {
  7640. case llvm::Triple::GNUEABIHF:
  7641. case llvm::Triple::GNUEABI:
  7642. case llvm::Triple::EABI:
  7643. CmdArgs.push_back("-meabi=5");
  7644. break;
  7645. default:
  7646. CmdArgs.push_back("-matpcs");
  7647. }
  7648. break;
  7649. }
  7650. case llvm::Triple::sparc:
  7651. case llvm::Triple::sparcel:
  7652. case llvm::Triple::sparcv9: {
  7653. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7654. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7655. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7656. break;
  7657. }
  7658. }
  7659. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7660. CmdArgs.push_back("-o");
  7661. CmdArgs.push_back(Output.getFilename());
  7662. for (const auto &II : Inputs)
  7663. CmdArgs.push_back(II.getFilename());
  7664. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7665. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7666. }
  7667. void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7668. const InputInfo &Output,
  7669. const InputInfoList &Inputs,
  7670. const ArgList &Args,
  7671. const char *LinkingOutput) const {
  7672. const toolchains::FreeBSD &ToolChain =
  7673. static_cast<const toolchains::FreeBSD &>(getToolChain());
  7674. const Driver &D = ToolChain.getDriver();
  7675. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7676. const bool IsPIE =
  7677. !Args.hasArg(options::OPT_shared) &&
  7678. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  7679. ArgStringList CmdArgs;
  7680. // Silence warning for "clang -g foo.o -o foo"
  7681. Args.ClaimAllArgs(options::OPT_g_Group);
  7682. // and "clang -emit-llvm foo.o -o foo"
  7683. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7684. // and for "clang -w foo.o -o foo". Other warning options are already
  7685. // handled somewhere else.
  7686. Args.ClaimAllArgs(options::OPT_w);
  7687. if (!D.SysRoot.empty())
  7688. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7689. if (IsPIE)
  7690. CmdArgs.push_back("-pie");
  7691. CmdArgs.push_back("--eh-frame-hdr");
  7692. if (Args.hasArg(options::OPT_static)) {
  7693. CmdArgs.push_back("-Bstatic");
  7694. } else {
  7695. if (Args.hasArg(options::OPT_rdynamic))
  7696. CmdArgs.push_back("-export-dynamic");
  7697. if (Args.hasArg(options::OPT_shared)) {
  7698. CmdArgs.push_back("-Bshareable");
  7699. } else {
  7700. CmdArgs.push_back("-dynamic-linker");
  7701. CmdArgs.push_back("/libexec/ld-elf.so.1");
  7702. }
  7703. if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
  7704. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
  7705. Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
  7706. CmdArgs.push_back("--hash-style=both");
  7707. }
  7708. }
  7709. CmdArgs.push_back("--enable-new-dtags");
  7710. }
  7711. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  7712. // instruct ld in the base system to link 32-bit code.
  7713. if (Arch == llvm::Triple::x86) {
  7714. CmdArgs.push_back("-m");
  7715. CmdArgs.push_back("elf_i386_fbsd");
  7716. }
  7717. if (Arch == llvm::Triple::ppc) {
  7718. CmdArgs.push_back("-m");
  7719. CmdArgs.push_back("elf32ppc_fbsd");
  7720. }
  7721. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  7722. if (ToolChain.getArch() == llvm::Triple::mips ||
  7723. ToolChain.getArch() == llvm::Triple::mipsel ||
  7724. ToolChain.getArch() == llvm::Triple::mips64 ||
  7725. ToolChain.getArch() == llvm::Triple::mips64el) {
  7726. StringRef v = A->getValue();
  7727. CmdArgs.push_back(Args.MakeArgString("-G" + v));
  7728. A->claim();
  7729. }
  7730. }
  7731. if (Output.isFilename()) {
  7732. CmdArgs.push_back("-o");
  7733. CmdArgs.push_back(Output.getFilename());
  7734. } else {
  7735. assert(Output.isNothing() && "Invalid output.");
  7736. }
  7737. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7738. const char *crt1 = nullptr;
  7739. if (!Args.hasArg(options::OPT_shared)) {
  7740. if (Args.hasArg(options::OPT_pg))
  7741. crt1 = "gcrt1.o";
  7742. else if (IsPIE)
  7743. crt1 = "Scrt1.o";
  7744. else
  7745. crt1 = "crt1.o";
  7746. }
  7747. if (crt1)
  7748. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  7749. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  7750. const char *crtbegin = nullptr;
  7751. if (Args.hasArg(options::OPT_static))
  7752. crtbegin = "crtbeginT.o";
  7753. else if (Args.hasArg(options::OPT_shared) || IsPIE)
  7754. crtbegin = "crtbeginS.o";
  7755. else
  7756. crtbegin = "crtbegin.o";
  7757. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  7758. }
  7759. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7760. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  7761. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  7762. Args.AddAllArgs(CmdArgs, options::OPT_e);
  7763. Args.AddAllArgs(CmdArgs, options::OPT_s);
  7764. Args.AddAllArgs(CmdArgs, options::OPT_t);
  7765. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  7766. Args.AddAllArgs(CmdArgs, options::OPT_r);
  7767. if (D.isUsingLTO())
  7768. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin, D);
  7769. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  7770. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  7771. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7772. addOpenMPRuntime(CmdArgs, ToolChain, Args);
  7773. if (D.CCCIsCXX()) {
  7774. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7775. if (Args.hasArg(options::OPT_pg))
  7776. CmdArgs.push_back("-lm_p");
  7777. else
  7778. CmdArgs.push_back("-lm");
  7779. }
  7780. if (NeedsSanitizerDeps)
  7781. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  7782. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  7783. // the default system libraries. Just mimic this for now.
  7784. if (Args.hasArg(options::OPT_pg))
  7785. CmdArgs.push_back("-lgcc_p");
  7786. else
  7787. CmdArgs.push_back("-lgcc");
  7788. if (Args.hasArg(options::OPT_static)) {
  7789. CmdArgs.push_back("-lgcc_eh");
  7790. } else if (Args.hasArg(options::OPT_pg)) {
  7791. CmdArgs.push_back("-lgcc_eh_p");
  7792. } else {
  7793. CmdArgs.push_back("--as-needed");
  7794. CmdArgs.push_back("-lgcc_s");
  7795. CmdArgs.push_back("--no-as-needed");
  7796. }
  7797. if (Args.hasArg(options::OPT_pthread)) {
  7798. if (Args.hasArg(options::OPT_pg))
  7799. CmdArgs.push_back("-lpthread_p");
  7800. else
  7801. CmdArgs.push_back("-lpthread");
  7802. }
  7803. if (Args.hasArg(options::OPT_pg)) {
  7804. if (Args.hasArg(options::OPT_shared))
  7805. CmdArgs.push_back("-lc");
  7806. else
  7807. CmdArgs.push_back("-lc_p");
  7808. CmdArgs.push_back("-lgcc_p");
  7809. } else {
  7810. CmdArgs.push_back("-lc");
  7811. CmdArgs.push_back("-lgcc");
  7812. }
  7813. if (Args.hasArg(options::OPT_static)) {
  7814. CmdArgs.push_back("-lgcc_eh");
  7815. } else if (Args.hasArg(options::OPT_pg)) {
  7816. CmdArgs.push_back("-lgcc_eh_p");
  7817. } else {
  7818. CmdArgs.push_back("--as-needed");
  7819. CmdArgs.push_back("-lgcc_s");
  7820. CmdArgs.push_back("--no-as-needed");
  7821. }
  7822. }
  7823. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7824. if (Args.hasArg(options::OPT_shared) || IsPIE)
  7825. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  7826. else
  7827. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  7828. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  7829. }
  7830. ToolChain.addProfileRTLibs(Args, CmdArgs);
  7831. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7832. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7833. }
  7834. void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7835. const InputInfo &Output,
  7836. const InputInfoList &Inputs,
  7837. const ArgList &Args,
  7838. const char *LinkingOutput) const {
  7839. claimNoWarnArgs(Args);
  7840. ArgStringList CmdArgs;
  7841. // GNU as needs different flags for creating the correct output format
  7842. // on architectures with different ABIs or optional feature sets.
  7843. switch (getToolChain().getArch()) {
  7844. case llvm::Triple::x86:
  7845. CmdArgs.push_back("--32");
  7846. break;
  7847. case llvm::Triple::arm:
  7848. case llvm::Triple::armeb:
  7849. case llvm::Triple::thumb:
  7850. case llvm::Triple::thumbeb: {
  7851. StringRef MArch, MCPU;
  7852. getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
  7853. std::string Arch =
  7854. arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
  7855. CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
  7856. break;
  7857. }
  7858. case llvm::Triple::mips:
  7859. case llvm::Triple::mipsel:
  7860. case llvm::Triple::mips64:
  7861. case llvm::Triple::mips64el: {
  7862. StringRef CPUName;
  7863. StringRef ABIName;
  7864. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7865. CmdArgs.push_back("-march");
  7866. CmdArgs.push_back(CPUName.data());
  7867. CmdArgs.push_back("-mabi");
  7868. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  7869. if (getToolChain().getArch() == llvm::Triple::mips ||
  7870. getToolChain().getArch() == llvm::Triple::mips64)
  7871. CmdArgs.push_back("-EB");
  7872. else
  7873. CmdArgs.push_back("-EL");
  7874. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7875. break;
  7876. }
  7877. case llvm::Triple::sparc:
  7878. case llvm::Triple::sparcel: {
  7879. CmdArgs.push_back("-32");
  7880. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7881. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7882. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7883. break;
  7884. }
  7885. case llvm::Triple::sparcv9: {
  7886. CmdArgs.push_back("-64");
  7887. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7888. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7889. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7890. break;
  7891. }
  7892. default:
  7893. break;
  7894. }
  7895. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7896. CmdArgs.push_back("-o");
  7897. CmdArgs.push_back(Output.getFilename());
  7898. for (const auto &II : Inputs)
  7899. CmdArgs.push_back(II.getFilename());
  7900. const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
  7901. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7902. }
  7903. void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7904. const InputInfo &Output,
  7905. const InputInfoList &Inputs,
  7906. const ArgList &Args,
  7907. const char *LinkingOutput) const {
  7908. const Driver &D = getToolChain().getDriver();
  7909. ArgStringList CmdArgs;
  7910. if (!D.SysRoot.empty())
  7911. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7912. CmdArgs.push_back("--eh-frame-hdr");
  7913. if (Args.hasArg(options::OPT_static)) {
  7914. CmdArgs.push_back("-Bstatic");
  7915. } else {
  7916. if (Args.hasArg(options::OPT_rdynamic))
  7917. CmdArgs.push_back("-export-dynamic");
  7918. if (Args.hasArg(options::OPT_shared)) {
  7919. CmdArgs.push_back("-Bshareable");
  7920. } else {
  7921. Args.AddAllArgs(CmdArgs, options::OPT_pie);
  7922. CmdArgs.push_back("-dynamic-linker");
  7923. CmdArgs.push_back("/libexec/ld.elf_so");
  7924. }
  7925. }
  7926. // Many NetBSD architectures support more than one ABI.
  7927. // Determine the correct emulation for ld.
  7928. switch (getToolChain().getArch()) {
  7929. case llvm::Triple::x86:
  7930. CmdArgs.push_back("-m");
  7931. CmdArgs.push_back("elf_i386");
  7932. break;
  7933. case llvm::Triple::arm:
  7934. case llvm::Triple::thumb:
  7935. CmdArgs.push_back("-m");
  7936. switch (getToolChain().getTriple().getEnvironment()) {
  7937. case llvm::Triple::EABI:
  7938. case llvm::Triple::GNUEABI:
  7939. CmdArgs.push_back("armelf_nbsd_eabi");
  7940. break;
  7941. case llvm::Triple::EABIHF:
  7942. case llvm::Triple::GNUEABIHF:
  7943. CmdArgs.push_back("armelf_nbsd_eabihf");
  7944. break;
  7945. default:
  7946. CmdArgs.push_back("armelf_nbsd");
  7947. break;
  7948. }
  7949. break;
  7950. case llvm::Triple::armeb:
  7951. case llvm::Triple::thumbeb:
  7952. arm::appendEBLinkFlags(Args, CmdArgs, getToolChain().getEffectiveTriple());
  7953. CmdArgs.push_back("-m");
  7954. switch (getToolChain().getTriple().getEnvironment()) {
  7955. case llvm::Triple::EABI:
  7956. case llvm::Triple::GNUEABI:
  7957. CmdArgs.push_back("armelfb_nbsd_eabi");
  7958. break;
  7959. case llvm::Triple::EABIHF:
  7960. case llvm::Triple::GNUEABIHF:
  7961. CmdArgs.push_back("armelfb_nbsd_eabihf");
  7962. break;
  7963. default:
  7964. CmdArgs.push_back("armelfb_nbsd");
  7965. break;
  7966. }
  7967. break;
  7968. case llvm::Triple::mips64:
  7969. case llvm::Triple::mips64el:
  7970. if (mips::hasMipsAbiArg(Args, "32")) {
  7971. CmdArgs.push_back("-m");
  7972. if (getToolChain().getArch() == llvm::Triple::mips64)
  7973. CmdArgs.push_back("elf32btsmip");
  7974. else
  7975. CmdArgs.push_back("elf32ltsmip");
  7976. } else if (mips::hasMipsAbiArg(Args, "64")) {
  7977. CmdArgs.push_back("-m");
  7978. if (getToolChain().getArch() == llvm::Triple::mips64)
  7979. CmdArgs.push_back("elf64btsmip");
  7980. else
  7981. CmdArgs.push_back("elf64ltsmip");
  7982. }
  7983. break;
  7984. case llvm::Triple::ppc:
  7985. CmdArgs.push_back("-m");
  7986. CmdArgs.push_back("elf32ppc_nbsd");
  7987. break;
  7988. case llvm::Triple::ppc64:
  7989. case llvm::Triple::ppc64le:
  7990. CmdArgs.push_back("-m");
  7991. CmdArgs.push_back("elf64ppc");
  7992. break;
  7993. case llvm::Triple::sparc:
  7994. CmdArgs.push_back("-m");
  7995. CmdArgs.push_back("elf32_sparc");
  7996. break;
  7997. case llvm::Triple::sparcv9:
  7998. CmdArgs.push_back("-m");
  7999. CmdArgs.push_back("elf64_sparc");
  8000. break;
  8001. default:
  8002. break;
  8003. }
  8004. if (Output.isFilename()) {
  8005. CmdArgs.push_back("-o");
  8006. CmdArgs.push_back(Output.getFilename());
  8007. } else {
  8008. assert(Output.isNothing() && "Invalid output.");
  8009. }
  8010. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8011. if (!Args.hasArg(options::OPT_shared)) {
  8012. CmdArgs.push_back(
  8013. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  8014. }
  8015. CmdArgs.push_back(
  8016. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  8017. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie)) {
  8018. CmdArgs.push_back(
  8019. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  8020. } else {
  8021. CmdArgs.push_back(
  8022. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  8023. }
  8024. }
  8025. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8026. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  8027. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8028. Args.AddAllArgs(CmdArgs, options::OPT_s);
  8029. Args.AddAllArgs(CmdArgs, options::OPT_t);
  8030. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  8031. Args.AddAllArgs(CmdArgs, options::OPT_r);
  8032. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8033. unsigned Major, Minor, Micro;
  8034. getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
  8035. bool useLibgcc = true;
  8036. if (Major >= 7 || Major == 0) {
  8037. switch (getToolChain().getArch()) {
  8038. case llvm::Triple::aarch64:
  8039. case llvm::Triple::arm:
  8040. case llvm::Triple::armeb:
  8041. case llvm::Triple::thumb:
  8042. case llvm::Triple::thumbeb:
  8043. case llvm::Triple::ppc:
  8044. case llvm::Triple::ppc64:
  8045. case llvm::Triple::ppc64le:
  8046. case llvm::Triple::sparc:
  8047. case llvm::Triple::sparcv9:
  8048. case llvm::Triple::x86:
  8049. case llvm::Triple::x86_64:
  8050. useLibgcc = false;
  8051. break;
  8052. default:
  8053. break;
  8054. }
  8055. }
  8056. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8057. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  8058. if (D.CCCIsCXX()) {
  8059. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  8060. CmdArgs.push_back("-lm");
  8061. }
  8062. if (Args.hasArg(options::OPT_pthread))
  8063. CmdArgs.push_back("-lpthread");
  8064. CmdArgs.push_back("-lc");
  8065. if (useLibgcc) {
  8066. if (Args.hasArg(options::OPT_static)) {
  8067. // libgcc_eh depends on libc, so resolve as much as possible,
  8068. // pull in any new requirements from libc and then get the rest
  8069. // of libgcc.
  8070. CmdArgs.push_back("-lgcc_eh");
  8071. CmdArgs.push_back("-lc");
  8072. CmdArgs.push_back("-lgcc");
  8073. } else {
  8074. CmdArgs.push_back("-lgcc");
  8075. CmdArgs.push_back("--as-needed");
  8076. CmdArgs.push_back("-lgcc_s");
  8077. CmdArgs.push_back("--no-as-needed");
  8078. }
  8079. }
  8080. }
  8081. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8082. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8083. CmdArgs.push_back(
  8084. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  8085. else
  8086. CmdArgs.push_back(
  8087. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  8088. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  8089. }
  8090. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8091. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8092. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8093. }
  8094. void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8095. const InputInfo &Output,
  8096. const InputInfoList &Inputs,
  8097. const ArgList &Args,
  8098. const char *LinkingOutput) const {
  8099. claimNoWarnArgs(Args);
  8100. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  8101. ArgStringList CmdArgs;
  8102. llvm::Reloc::Model RelocationModel;
  8103. unsigned PICLevel;
  8104. bool IsPIE;
  8105. std::tie(RelocationModel, PICLevel, IsPIE) =
  8106. ParsePICArgs(getToolChain(), Triple, Args);
  8107. switch (getToolChain().getArch()) {
  8108. default:
  8109. break;
  8110. // Add --32/--64 to make sure we get the format we want.
  8111. // This is incomplete
  8112. case llvm::Triple::x86:
  8113. CmdArgs.push_back("--32");
  8114. break;
  8115. case llvm::Triple::x86_64:
  8116. if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
  8117. CmdArgs.push_back("--x32");
  8118. else
  8119. CmdArgs.push_back("--64");
  8120. break;
  8121. case llvm::Triple::ppc:
  8122. CmdArgs.push_back("-a32");
  8123. CmdArgs.push_back("-mppc");
  8124. CmdArgs.push_back("-many");
  8125. break;
  8126. case llvm::Triple::ppc64:
  8127. CmdArgs.push_back("-a64");
  8128. CmdArgs.push_back("-mppc64");
  8129. CmdArgs.push_back("-many");
  8130. break;
  8131. case llvm::Triple::ppc64le:
  8132. CmdArgs.push_back("-a64");
  8133. CmdArgs.push_back("-mppc64");
  8134. CmdArgs.push_back("-many");
  8135. CmdArgs.push_back("-mlittle-endian");
  8136. break;
  8137. case llvm::Triple::sparc:
  8138. case llvm::Triple::sparcel: {
  8139. CmdArgs.push_back("-32");
  8140. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  8141. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  8142. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  8143. break;
  8144. }
  8145. case llvm::Triple::sparcv9: {
  8146. CmdArgs.push_back("-64");
  8147. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  8148. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  8149. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  8150. break;
  8151. }
  8152. case llvm::Triple::arm:
  8153. case llvm::Triple::armeb:
  8154. case llvm::Triple::thumb:
  8155. case llvm::Triple::thumbeb: {
  8156. const llvm::Triple &Triple2 = getToolChain().getTriple();
  8157. switch (Triple2.getSubArch()) {
  8158. case llvm::Triple::ARMSubArch_v7:
  8159. CmdArgs.push_back("-mfpu=neon");
  8160. break;
  8161. case llvm::Triple::ARMSubArch_v8:
  8162. CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
  8163. break;
  8164. default:
  8165. break;
  8166. }
  8167. switch (arm::getARMFloatABI(getToolChain(), Args)) {
  8168. case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
  8169. case arm::FloatABI::Soft:
  8170. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
  8171. break;
  8172. case arm::FloatABI::SoftFP:
  8173. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
  8174. break;
  8175. case arm::FloatABI::Hard:
  8176. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
  8177. break;
  8178. }
  8179. Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
  8180. // FIXME: remove krait check when GNU tools support krait cpu
  8181. // for now replace it with -mcpu=cortex-a15 to avoid a lower
  8182. // march from being picked in the absence of a cpu flag.
  8183. Arg *A;
  8184. if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
  8185. StringRef(A->getValue()).equals_lower("krait"))
  8186. CmdArgs.push_back("-mcpu=cortex-a15");
  8187. else
  8188. Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
  8189. Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
  8190. break;
  8191. }
  8192. case llvm::Triple::mips:
  8193. case llvm::Triple::mipsel:
  8194. case llvm::Triple::mips64:
  8195. case llvm::Triple::mips64el: {
  8196. StringRef CPUName;
  8197. StringRef ABIName;
  8198. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  8199. ABIName = getGnuCompatibleMipsABIName(ABIName);
  8200. CmdArgs.push_back("-march");
  8201. CmdArgs.push_back(CPUName.data());
  8202. CmdArgs.push_back("-mabi");
  8203. CmdArgs.push_back(ABIName.data());
  8204. // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
  8205. // or -mshared (not implemented) is in effect.
  8206. if (RelocationModel == llvm::Reloc::Static)
  8207. CmdArgs.push_back("-mno-shared");
  8208. // LLVM doesn't support -mplt yet and acts as if it is always given.
  8209. // However, -mplt has no effect with the N64 ABI.
  8210. CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
  8211. if (getToolChain().getArch() == llvm::Triple::mips ||
  8212. getToolChain().getArch() == llvm::Triple::mips64)
  8213. CmdArgs.push_back("-EB");
  8214. else
  8215. CmdArgs.push_back("-EL");
  8216. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  8217. if (StringRef(A->getValue()) == "2008")
  8218. CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
  8219. }
  8220. // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
  8221. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  8222. options::OPT_mfp64)) {
  8223. A->claim();
  8224. A->render(Args, CmdArgs);
  8225. } else if (mips::shouldUseFPXX(
  8226. Args, getToolChain().getTriple(), CPUName, ABIName,
  8227. getMipsFloatABI(getToolChain().getDriver(), Args)))
  8228. CmdArgs.push_back("-mfpxx");
  8229. // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
  8230. // -mno-mips16 is actually -no-mips16.
  8231. if (Arg *A =
  8232. Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
  8233. if (A->getOption().matches(options::OPT_mips16)) {
  8234. A->claim();
  8235. A->render(Args, CmdArgs);
  8236. } else {
  8237. A->claim();
  8238. CmdArgs.push_back("-no-mips16");
  8239. }
  8240. }
  8241. Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
  8242. options::OPT_mno_micromips);
  8243. Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
  8244. Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
  8245. if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
  8246. // Do not use AddLastArg because not all versions of MIPS assembler
  8247. // support -mmsa / -mno-msa options.
  8248. if (A->getOption().matches(options::OPT_mmsa))
  8249. CmdArgs.push_back(Args.MakeArgString("-mmsa"));
  8250. }
  8251. Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
  8252. options::OPT_msoft_float);
  8253. Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
  8254. options::OPT_msingle_float);
  8255. Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
  8256. options::OPT_mno_odd_spreg);
  8257. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  8258. break;
  8259. }
  8260. case llvm::Triple::systemz: {
  8261. // Always pass an -march option, since our default of z10 is later
  8262. // than the GNU assembler's default.
  8263. StringRef CPUName = getSystemZTargetCPU(Args);
  8264. CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
  8265. break;
  8266. }
  8267. }
  8268. Args.AddAllArgs(CmdArgs, options::OPT_I);
  8269. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8270. CmdArgs.push_back("-o");
  8271. CmdArgs.push_back(Output.getFilename());
  8272. for (const auto &II : Inputs)
  8273. CmdArgs.push_back(II.getFilename());
  8274. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8275. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8276. // Handle the debug info splitting at object creation time if we're
  8277. // creating an object.
  8278. // TODO: Currently only works on linux with newer objcopy.
  8279. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  8280. getToolChain().getTriple().isOSLinux())
  8281. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  8282. SplitDebugName(Args, Inputs[0]));
  8283. }
  8284. static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
  8285. ArgStringList &CmdArgs, const ArgList &Args) {
  8286. bool isAndroid = Triple.isAndroid();
  8287. bool isCygMing = Triple.isOSCygMing();
  8288. bool IsIAMCU = Triple.isOSIAMCU();
  8289. bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
  8290. Args.hasArg(options::OPT_static);
  8291. if (!D.CCCIsCXX())
  8292. CmdArgs.push_back("-lgcc");
  8293. if (StaticLibgcc || isAndroid) {
  8294. if (D.CCCIsCXX())
  8295. CmdArgs.push_back("-lgcc");
  8296. } else {
  8297. if (!D.CCCIsCXX() && !isCygMing)
  8298. CmdArgs.push_back("--as-needed");
  8299. CmdArgs.push_back("-lgcc_s");
  8300. if (!D.CCCIsCXX() && !isCygMing)
  8301. CmdArgs.push_back("--no-as-needed");
  8302. }
  8303. if (StaticLibgcc && !isAndroid && !IsIAMCU)
  8304. CmdArgs.push_back("-lgcc_eh");
  8305. else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
  8306. CmdArgs.push_back("-lgcc");
  8307. // According to Android ABI, we have to link with libdl if we are
  8308. // linking with non-static libgcc.
  8309. //
  8310. // NOTE: This fixes a link error on Android MIPS as well. The non-static
  8311. // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
  8312. if (isAndroid && !StaticLibgcc)
  8313. CmdArgs.push_back("-ldl");
  8314. }
  8315. static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
  8316. ArgStringList &CmdArgs, const ArgList &Args) {
  8317. // Make use of compiler-rt if --rtlib option is used
  8318. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
  8319. switch (RLT) {
  8320. case ToolChain::RLT_CompilerRT:
  8321. switch (TC.getTriple().getOS()) {
  8322. default:
  8323. llvm_unreachable("unsupported OS");
  8324. case llvm::Triple::Win32:
  8325. case llvm::Triple::Linux:
  8326. case llvm::Triple::Fuchsia:
  8327. addClangRT(TC, Args, CmdArgs);
  8328. break;
  8329. }
  8330. break;
  8331. case ToolChain::RLT_Libgcc:
  8332. // Make sure libgcc is not used under MSVC environment by default
  8333. if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
  8334. // Issue error diagnostic if libgcc is explicitly specified
  8335. // through command line as --rtlib option argument.
  8336. if (Args.hasArg(options::OPT_rtlib_EQ)) {
  8337. TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
  8338. << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
  8339. }
  8340. } else
  8341. AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
  8342. break;
  8343. }
  8344. }
  8345. static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
  8346. switch (T.getArch()) {
  8347. case llvm::Triple::x86:
  8348. if (T.isOSIAMCU())
  8349. return "elf_iamcu";
  8350. return "elf_i386";
  8351. case llvm::Triple::aarch64:
  8352. return "aarch64linux";
  8353. case llvm::Triple::aarch64_be:
  8354. return "aarch64_be_linux";
  8355. case llvm::Triple::arm:
  8356. case llvm::Triple::thumb:
  8357. return "armelf_linux_eabi";
  8358. case llvm::Triple::armeb:
  8359. case llvm::Triple::thumbeb:
  8360. return "armelfb_linux_eabi";
  8361. case llvm::Triple::ppc:
  8362. return "elf32ppclinux";
  8363. case llvm::Triple::ppc64:
  8364. return "elf64ppc";
  8365. case llvm::Triple::ppc64le:
  8366. return "elf64lppc";
  8367. case llvm::Triple::sparc:
  8368. case llvm::Triple::sparcel:
  8369. return "elf32_sparc";
  8370. case llvm::Triple::sparcv9:
  8371. return "elf64_sparc";
  8372. case llvm::Triple::mips:
  8373. return "elf32btsmip";
  8374. case llvm::Triple::mipsel:
  8375. return "elf32ltsmip";
  8376. case llvm::Triple::mips64:
  8377. if (mips::hasMipsAbiArg(Args, "n32"))
  8378. return "elf32btsmipn32";
  8379. return "elf64btsmip";
  8380. case llvm::Triple::mips64el:
  8381. if (mips::hasMipsAbiArg(Args, "n32"))
  8382. return "elf32ltsmipn32";
  8383. return "elf64ltsmip";
  8384. case llvm::Triple::systemz:
  8385. return "elf64_s390";
  8386. case llvm::Triple::x86_64:
  8387. if (T.getEnvironment() == llvm::Triple::GNUX32)
  8388. return "elf32_x86_64";
  8389. return "elf_x86_64";
  8390. default:
  8391. llvm_unreachable("Unexpected arch");
  8392. }
  8393. }
  8394. void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8395. const InputInfo &Output,
  8396. const InputInfoList &Inputs,
  8397. const ArgList &Args,
  8398. const char *LinkingOutput) const {
  8399. const toolchains::Linux &ToolChain =
  8400. static_cast<const toolchains::Linux &>(getToolChain());
  8401. const Driver &D = ToolChain.getDriver();
  8402. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  8403. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  8404. const bool isAndroid = ToolChain.getTriple().isAndroid();
  8405. const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
  8406. const bool IsPIE =
  8407. !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
  8408. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  8409. const bool HasCRTBeginEndFiles =
  8410. ToolChain.getTriple().hasEnvironment() ||
  8411. (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
  8412. ArgStringList CmdArgs;
  8413. // Silence warning for "clang -g foo.o -o foo"
  8414. Args.ClaimAllArgs(options::OPT_g_Group);
  8415. // and "clang -emit-llvm foo.o -o foo"
  8416. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8417. // and for "clang -w foo.o -o foo". Other warning options are already
  8418. // handled somewhere else.
  8419. Args.ClaimAllArgs(options::OPT_w);
  8420. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  8421. if (llvm::sys::path::filename(Exec) == "lld") {
  8422. CmdArgs.push_back("-flavor");
  8423. CmdArgs.push_back("old-gnu");
  8424. CmdArgs.push_back("-target");
  8425. CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
  8426. }
  8427. if (!D.SysRoot.empty())
  8428. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8429. if (IsPIE)
  8430. CmdArgs.push_back("-pie");
  8431. if (Args.hasArg(options::OPT_rdynamic))
  8432. CmdArgs.push_back("-export-dynamic");
  8433. if (Args.hasArg(options::OPT_s))
  8434. CmdArgs.push_back("-s");
  8435. if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
  8436. arm::appendEBLinkFlags(Args, CmdArgs, Triple);
  8437. // Most Android ARM64 targets should enable the linker fix for erratum
  8438. // 843419. Only non-Cortex-A53 devices are allowed to skip this flag.
  8439. if (Arch == llvm::Triple::aarch64 && isAndroid) {
  8440. std::string CPU = getCPUName(Args, Triple);
  8441. if (CPU.empty() || CPU == "generic" || CPU == "cortex-a53")
  8442. CmdArgs.push_back("--fix-cortex-a53-843419");
  8443. }
  8444. for (const auto &Opt : ToolChain.ExtraOpts)
  8445. CmdArgs.push_back(Opt.c_str());
  8446. if (!Args.hasArg(options::OPT_static)) {
  8447. CmdArgs.push_back("--eh-frame-hdr");
  8448. }
  8449. CmdArgs.push_back("-m");
  8450. CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
  8451. if (Args.hasArg(options::OPT_static)) {
  8452. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  8453. Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
  8454. CmdArgs.push_back("-Bstatic");
  8455. else
  8456. CmdArgs.push_back("-static");
  8457. } else if (Args.hasArg(options::OPT_shared)) {
  8458. CmdArgs.push_back("-shared");
  8459. }
  8460. if (!Args.hasArg(options::OPT_static)) {
  8461. if (Args.hasArg(options::OPT_rdynamic))
  8462. CmdArgs.push_back("-export-dynamic");
  8463. if (!Args.hasArg(options::OPT_shared)) {
  8464. const std::string Loader =
  8465. D.DyldPrefix + ToolChain.getDynamicLinker(Args);
  8466. CmdArgs.push_back("-dynamic-linker");
  8467. CmdArgs.push_back(Args.MakeArgString(Loader));
  8468. }
  8469. }
  8470. CmdArgs.push_back("-o");
  8471. CmdArgs.push_back(Output.getFilename());
  8472. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8473. if (!isAndroid && !IsIAMCU) {
  8474. const char *crt1 = nullptr;
  8475. if (!Args.hasArg(options::OPT_shared)) {
  8476. if (Args.hasArg(options::OPT_pg))
  8477. crt1 = "gcrt1.o";
  8478. else if (IsPIE)
  8479. crt1 = "Scrt1.o";
  8480. else
  8481. crt1 = "crt1.o";
  8482. }
  8483. if (crt1)
  8484. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  8485. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  8486. }
  8487. if (IsIAMCU)
  8488. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
  8489. else {
  8490. const char *crtbegin;
  8491. if (Args.hasArg(options::OPT_static))
  8492. crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
  8493. else if (Args.hasArg(options::OPT_shared))
  8494. crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
  8495. else if (IsPIE)
  8496. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
  8497. else
  8498. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
  8499. if (HasCRTBeginEndFiles)
  8500. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  8501. }
  8502. // Add crtfastmath.o if available and fast math is enabled.
  8503. ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  8504. }
  8505. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8506. Args.AddAllArgs(CmdArgs, options::OPT_u);
  8507. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  8508. if (D.isUsingLTO())
  8509. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin, D);
  8510. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  8511. CmdArgs.push_back("--no-demangle");
  8512. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  8513. bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
  8514. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  8515. // The profile runtime also needs access to system libraries.
  8516. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8517. if (D.CCCIsCXX() &&
  8518. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8519. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  8520. !Args.hasArg(options::OPT_static);
  8521. if (OnlyLibstdcxxStatic)
  8522. CmdArgs.push_back("-Bstatic");
  8523. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  8524. if (OnlyLibstdcxxStatic)
  8525. CmdArgs.push_back("-Bdynamic");
  8526. CmdArgs.push_back("-lm");
  8527. }
  8528. // Silence warnings when linking C code with a C++ '-stdlib' argument.
  8529. Args.ClaimAllArgs(options::OPT_stdlib_EQ);
  8530. if (!Args.hasArg(options::OPT_nostdlib)) {
  8531. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8532. if (Args.hasArg(options::OPT_static))
  8533. CmdArgs.push_back("--start-group");
  8534. if (NeedsSanitizerDeps)
  8535. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  8536. if (NeedsXRayDeps)
  8537. linkXRayRuntimeDeps(ToolChain, Args, CmdArgs);
  8538. bool WantPthread = Args.hasArg(options::OPT_pthread) ||
  8539. Args.hasArg(options::OPT_pthreads);
  8540. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  8541. options::OPT_fno_openmp, false)) {
  8542. // OpenMP runtimes implies pthreads when using the GNU toolchain.
  8543. // FIXME: Does this really make sense for all GNU toolchains?
  8544. WantPthread = true;
  8545. // Also link the particular OpenMP runtimes.
  8546. switch (ToolChain.getDriver().getOpenMPRuntime(Args)) {
  8547. case Driver::OMPRT_OMP:
  8548. CmdArgs.push_back("-lomp");
  8549. break;
  8550. case Driver::OMPRT_GOMP:
  8551. CmdArgs.push_back("-lgomp");
  8552. // FIXME: Exclude this for platforms with libgomp that don't require
  8553. // librt. Most modern Linux platforms require it, but some may not.
  8554. CmdArgs.push_back("-lrt");
  8555. break;
  8556. case Driver::OMPRT_IOMP5:
  8557. CmdArgs.push_back("-liomp5");
  8558. break;
  8559. case Driver::OMPRT_Unknown:
  8560. // Already diagnosed.
  8561. break;
  8562. }
  8563. }
  8564. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  8565. if (WantPthread && !isAndroid)
  8566. CmdArgs.push_back("-lpthread");
  8567. if (Args.hasArg(options::OPT_fsplit_stack))
  8568. CmdArgs.push_back("--wrap=pthread_create");
  8569. CmdArgs.push_back("-lc");
  8570. // Add IAMCU specific libs, if needed.
  8571. if (IsIAMCU)
  8572. CmdArgs.push_back("-lgloss");
  8573. if (Args.hasArg(options::OPT_static))
  8574. CmdArgs.push_back("--end-group");
  8575. else
  8576. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  8577. // Add IAMCU specific libs (outside the group), if needed.
  8578. if (IsIAMCU) {
  8579. CmdArgs.push_back("--as-needed");
  8580. CmdArgs.push_back("-lsoftfp");
  8581. CmdArgs.push_back("--no-as-needed");
  8582. }
  8583. }
  8584. if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
  8585. const char *crtend;
  8586. if (Args.hasArg(options::OPT_shared))
  8587. crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
  8588. else if (IsPIE)
  8589. crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
  8590. else
  8591. crtend = isAndroid ? "crtend_android.o" : "crtend.o";
  8592. if (HasCRTBeginEndFiles)
  8593. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  8594. if (!isAndroid)
  8595. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  8596. }
  8597. }
  8598. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8599. }
  8600. // NaCl ARM assembly (inline or standalone) can be written with a set of macros
  8601. // for the various SFI requirements like register masking. The assembly tool
  8602. // inserts the file containing the macros as an input into all the assembly
  8603. // jobs.
  8604. void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
  8605. const InputInfo &Output,
  8606. const InputInfoList &Inputs,
  8607. const ArgList &Args,
  8608. const char *LinkingOutput) const {
  8609. const toolchains::NaClToolChain &ToolChain =
  8610. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  8611. InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
  8612. "nacl-arm-macros.s");
  8613. InputInfoList NewInputs;
  8614. NewInputs.push_back(NaClMacros);
  8615. NewInputs.append(Inputs.begin(), Inputs.end());
  8616. gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
  8617. LinkingOutput);
  8618. }
  8619. // This is quite similar to gnutools::Linker::ConstructJob with changes that
  8620. // we use static by default, do not yet support sanitizers or LTO, and a few
  8621. // others. Eventually we can support more of that and hopefully migrate back
  8622. // to gnutools::Linker.
  8623. void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8624. const InputInfo &Output,
  8625. const InputInfoList &Inputs,
  8626. const ArgList &Args,
  8627. const char *LinkingOutput) const {
  8628. const toolchains::NaClToolChain &ToolChain =
  8629. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  8630. const Driver &D = ToolChain.getDriver();
  8631. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  8632. const bool IsStatic =
  8633. !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
  8634. ArgStringList CmdArgs;
  8635. // Silence warning for "clang -g foo.o -o foo"
  8636. Args.ClaimAllArgs(options::OPT_g_Group);
  8637. // and "clang -emit-llvm foo.o -o foo"
  8638. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8639. // and for "clang -w foo.o -o foo". Other warning options are already
  8640. // handled somewhere else.
  8641. Args.ClaimAllArgs(options::OPT_w);
  8642. if (!D.SysRoot.empty())
  8643. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8644. if (Args.hasArg(options::OPT_rdynamic))
  8645. CmdArgs.push_back("-export-dynamic");
  8646. if (Args.hasArg(options::OPT_s))
  8647. CmdArgs.push_back("-s");
  8648. // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
  8649. // from there is --build-id, which we do want.
  8650. CmdArgs.push_back("--build-id");
  8651. if (!IsStatic)
  8652. CmdArgs.push_back("--eh-frame-hdr");
  8653. CmdArgs.push_back("-m");
  8654. if (Arch == llvm::Triple::x86)
  8655. CmdArgs.push_back("elf_i386_nacl");
  8656. else if (Arch == llvm::Triple::arm)
  8657. CmdArgs.push_back("armelf_nacl");
  8658. else if (Arch == llvm::Triple::x86_64)
  8659. CmdArgs.push_back("elf_x86_64_nacl");
  8660. else if (Arch == llvm::Triple::mipsel)
  8661. CmdArgs.push_back("mipselelf_nacl");
  8662. else
  8663. D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
  8664. << "Native Client";
  8665. if (IsStatic)
  8666. CmdArgs.push_back("-static");
  8667. else if (Args.hasArg(options::OPT_shared))
  8668. CmdArgs.push_back("-shared");
  8669. CmdArgs.push_back("-o");
  8670. CmdArgs.push_back(Output.getFilename());
  8671. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8672. if (!Args.hasArg(options::OPT_shared))
  8673. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  8674. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  8675. const char *crtbegin;
  8676. if (IsStatic)
  8677. crtbegin = "crtbeginT.o";
  8678. else if (Args.hasArg(options::OPT_shared))
  8679. crtbegin = "crtbeginS.o";
  8680. else
  8681. crtbegin = "crtbegin.o";
  8682. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  8683. }
  8684. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8685. Args.AddAllArgs(CmdArgs, options::OPT_u);
  8686. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  8687. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  8688. CmdArgs.push_back("--no-demangle");
  8689. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  8690. if (D.CCCIsCXX() &&
  8691. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8692. bool OnlyLibstdcxxStatic =
  8693. Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
  8694. if (OnlyLibstdcxxStatic)
  8695. CmdArgs.push_back("-Bstatic");
  8696. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  8697. if (OnlyLibstdcxxStatic)
  8698. CmdArgs.push_back("-Bdynamic");
  8699. CmdArgs.push_back("-lm");
  8700. }
  8701. if (!Args.hasArg(options::OPT_nostdlib)) {
  8702. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8703. // Always use groups, since it has no effect on dynamic libraries.
  8704. CmdArgs.push_back("--start-group");
  8705. CmdArgs.push_back("-lc");
  8706. // NaCl's libc++ currently requires libpthread, so just always include it
  8707. // in the group for C++.
  8708. if (Args.hasArg(options::OPT_pthread) ||
  8709. Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
  8710. // Gold, used by Mips, handles nested groups differently than ld, and
  8711. // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
  8712. // which is not a desired behaviour here.
  8713. // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
  8714. if (getToolChain().getArch() == llvm::Triple::mipsel)
  8715. CmdArgs.push_back("-lnacl");
  8716. CmdArgs.push_back("-lpthread");
  8717. }
  8718. CmdArgs.push_back("-lgcc");
  8719. CmdArgs.push_back("--as-needed");
  8720. if (IsStatic)
  8721. CmdArgs.push_back("-lgcc_eh");
  8722. else
  8723. CmdArgs.push_back("-lgcc_s");
  8724. CmdArgs.push_back("--no-as-needed");
  8725. // Mips needs to create and use pnacl_legacy library that contains
  8726. // definitions from bitcode/pnaclmm.c and definitions for
  8727. // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
  8728. if (getToolChain().getArch() == llvm::Triple::mipsel)
  8729. CmdArgs.push_back("-lpnacl_legacy");
  8730. CmdArgs.push_back("--end-group");
  8731. }
  8732. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8733. const char *crtend;
  8734. if (Args.hasArg(options::OPT_shared))
  8735. crtend = "crtendS.o";
  8736. else
  8737. crtend = "crtend.o";
  8738. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  8739. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  8740. }
  8741. }
  8742. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  8743. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8744. }
  8745. void fuchsia::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8746. const InputInfo &Output,
  8747. const InputInfoList &Inputs,
  8748. const ArgList &Args,
  8749. const char *LinkingOutput) const {
  8750. const toolchains::Fuchsia &ToolChain =
  8751. static_cast<const toolchains::Fuchsia &>(getToolChain());
  8752. const Driver &D = ToolChain.getDriver();
  8753. ArgStringList CmdArgs;
  8754. // Silence warning for "clang -g foo.o -o foo"
  8755. Args.ClaimAllArgs(options::OPT_g_Group);
  8756. // and "clang -emit-llvm foo.o -o foo"
  8757. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8758. // and for "clang -w foo.o -o foo". Other warning options are already
  8759. // handled somewhere else.
  8760. Args.ClaimAllArgs(options::OPT_w);
  8761. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  8762. if (llvm::sys::path::stem(Exec).equals_lower("lld")) {
  8763. CmdArgs.push_back("-flavor");
  8764. CmdArgs.push_back("gnu");
  8765. }
  8766. if (!D.SysRoot.empty())
  8767. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8768. if (!Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_r))
  8769. CmdArgs.push_back("-pie");
  8770. if (Args.hasArg(options::OPT_rdynamic))
  8771. CmdArgs.push_back("-export-dynamic");
  8772. if (Args.hasArg(options::OPT_s))
  8773. CmdArgs.push_back("-s");
  8774. if (Args.hasArg(options::OPT_r))
  8775. CmdArgs.push_back("-r");
  8776. else
  8777. CmdArgs.push_back("--build-id");
  8778. if (!Args.hasArg(options::OPT_static))
  8779. CmdArgs.push_back("--eh-frame-hdr");
  8780. if (Args.hasArg(options::OPT_static))
  8781. CmdArgs.push_back("-Bstatic");
  8782. else if (Args.hasArg(options::OPT_shared))
  8783. CmdArgs.push_back("-shared");
  8784. if (!Args.hasArg(options::OPT_static)) {
  8785. if (Args.hasArg(options::OPT_rdynamic))
  8786. CmdArgs.push_back("-export-dynamic");
  8787. if (!Args.hasArg(options::OPT_shared)) {
  8788. CmdArgs.push_back("-dynamic-linker");
  8789. CmdArgs.push_back(Args.MakeArgString(D.DyldPrefix + "ld.so.1"));
  8790. }
  8791. }
  8792. CmdArgs.push_back("-o");
  8793. CmdArgs.push_back(Output.getFilename());
  8794. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8795. if (!Args.hasArg(options::OPT_shared)) {
  8796. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
  8797. }
  8798. }
  8799. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8800. Args.AddAllArgs(CmdArgs, options::OPT_u);
  8801. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  8802. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  8803. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8804. if (Args.hasArg(options::OPT_static))
  8805. CmdArgs.push_back("-Bdynamic");
  8806. if (D.CCCIsCXX()) {
  8807. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  8808. !Args.hasArg(options::OPT_static);
  8809. if (OnlyLibstdcxxStatic)
  8810. CmdArgs.push_back("-Bstatic");
  8811. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  8812. if (OnlyLibstdcxxStatic)
  8813. CmdArgs.push_back("-Bdynamic");
  8814. CmdArgs.push_back("-lm");
  8815. }
  8816. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  8817. if (Args.hasArg(options::OPT_pthread) ||
  8818. Args.hasArg(options::OPT_pthreads))
  8819. CmdArgs.push_back("-lpthread");
  8820. if (Args.hasArg(options::OPT_fsplit_stack))
  8821. CmdArgs.push_back("--wrap=pthread_create");
  8822. CmdArgs.push_back("-lc");
  8823. }
  8824. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8825. }
  8826. void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8827. const InputInfo &Output,
  8828. const InputInfoList &Inputs,
  8829. const ArgList &Args,
  8830. const char *LinkingOutput) const {
  8831. claimNoWarnArgs(Args);
  8832. ArgStringList CmdArgs;
  8833. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8834. CmdArgs.push_back("-o");
  8835. CmdArgs.push_back(Output.getFilename());
  8836. for (const auto &II : Inputs)
  8837. CmdArgs.push_back(II.getFilename());
  8838. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8839. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8840. }
  8841. void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8842. const InputInfo &Output,
  8843. const InputInfoList &Inputs,
  8844. const ArgList &Args,
  8845. const char *LinkingOutput) const {
  8846. const Driver &D = getToolChain().getDriver();
  8847. ArgStringList CmdArgs;
  8848. if (Output.isFilename()) {
  8849. CmdArgs.push_back("-o");
  8850. CmdArgs.push_back(Output.getFilename());
  8851. } else {
  8852. assert(Output.isNothing() && "Invalid output.");
  8853. }
  8854. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8855. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  8856. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  8857. CmdArgs.push_back(
  8858. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  8859. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  8860. }
  8861. Args.AddAllArgs(CmdArgs,
  8862. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  8863. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8864. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8865. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8866. if (D.CCCIsCXX()) {
  8867. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  8868. CmdArgs.push_back("-lm");
  8869. }
  8870. }
  8871. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8872. if (Args.hasArg(options::OPT_pthread))
  8873. CmdArgs.push_back("-lpthread");
  8874. CmdArgs.push_back("-lc");
  8875. CmdArgs.push_back("-lCompilerRT-Generic");
  8876. CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
  8877. CmdArgs.push_back(
  8878. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  8879. }
  8880. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8881. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8882. }
  8883. /// DragonFly Tools
  8884. // For now, DragonFly Assemble does just about the same as for
  8885. // FreeBSD, but this may change soon.
  8886. void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8887. const InputInfo &Output,
  8888. const InputInfoList &Inputs,
  8889. const ArgList &Args,
  8890. const char *LinkingOutput) const {
  8891. claimNoWarnArgs(Args);
  8892. ArgStringList CmdArgs;
  8893. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  8894. // instruct as in the base system to assemble 32-bit code.
  8895. if (getToolChain().getArch() == llvm::Triple::x86)
  8896. CmdArgs.push_back("--32");
  8897. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8898. CmdArgs.push_back("-o");
  8899. CmdArgs.push_back(Output.getFilename());
  8900. for (const auto &II : Inputs)
  8901. CmdArgs.push_back(II.getFilename());
  8902. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8903. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8904. }
  8905. void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8906. const InputInfo &Output,
  8907. const InputInfoList &Inputs,
  8908. const ArgList &Args,
  8909. const char *LinkingOutput) const {
  8910. const Driver &D = getToolChain().getDriver();
  8911. ArgStringList CmdArgs;
  8912. if (!D.SysRoot.empty())
  8913. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8914. CmdArgs.push_back("--eh-frame-hdr");
  8915. if (Args.hasArg(options::OPT_static)) {
  8916. CmdArgs.push_back("-Bstatic");
  8917. } else {
  8918. if (Args.hasArg(options::OPT_rdynamic))
  8919. CmdArgs.push_back("-export-dynamic");
  8920. if (Args.hasArg(options::OPT_shared))
  8921. CmdArgs.push_back("-Bshareable");
  8922. else {
  8923. CmdArgs.push_back("-dynamic-linker");
  8924. CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
  8925. }
  8926. CmdArgs.push_back("--hash-style=gnu");
  8927. CmdArgs.push_back("--enable-new-dtags");
  8928. }
  8929. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  8930. // instruct ld in the base system to link 32-bit code.
  8931. if (getToolChain().getArch() == llvm::Triple::x86) {
  8932. CmdArgs.push_back("-m");
  8933. CmdArgs.push_back("elf_i386");
  8934. }
  8935. if (Output.isFilename()) {
  8936. CmdArgs.push_back("-o");
  8937. CmdArgs.push_back(Output.getFilename());
  8938. } else {
  8939. assert(Output.isNothing() && "Invalid output.");
  8940. }
  8941. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8942. if (!Args.hasArg(options::OPT_shared)) {
  8943. if (Args.hasArg(options::OPT_pg))
  8944. CmdArgs.push_back(
  8945. Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
  8946. else {
  8947. if (Args.hasArg(options::OPT_pie))
  8948. CmdArgs.push_back(
  8949. Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
  8950. else
  8951. CmdArgs.push_back(
  8952. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  8953. }
  8954. }
  8955. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  8956. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8957. CmdArgs.push_back(
  8958. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  8959. else
  8960. CmdArgs.push_back(
  8961. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  8962. }
  8963. Args.AddAllArgs(CmdArgs,
  8964. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  8965. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8966. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8967. CmdArgs.push_back("-L/usr/lib/gcc50");
  8968. if (!Args.hasArg(options::OPT_static)) {
  8969. CmdArgs.push_back("-rpath");
  8970. CmdArgs.push_back("/usr/lib/gcc50");
  8971. }
  8972. if (D.CCCIsCXX()) {
  8973. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  8974. CmdArgs.push_back("-lm");
  8975. }
  8976. if (Args.hasArg(options::OPT_pthread))
  8977. CmdArgs.push_back("-lpthread");
  8978. if (!Args.hasArg(options::OPT_nolibc)) {
  8979. CmdArgs.push_back("-lc");
  8980. }
  8981. if (Args.hasArg(options::OPT_static) ||
  8982. Args.hasArg(options::OPT_static_libgcc)) {
  8983. CmdArgs.push_back("-lgcc");
  8984. CmdArgs.push_back("-lgcc_eh");
  8985. } else {
  8986. if (Args.hasArg(options::OPT_shared_libgcc)) {
  8987. CmdArgs.push_back("-lgcc_pic");
  8988. if (!Args.hasArg(options::OPT_shared))
  8989. CmdArgs.push_back("-lgcc");
  8990. } else {
  8991. CmdArgs.push_back("-lgcc");
  8992. CmdArgs.push_back("--as-needed");
  8993. CmdArgs.push_back("-lgcc_pic");
  8994. CmdArgs.push_back("--no-as-needed");
  8995. }
  8996. }
  8997. }
  8998. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8999. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  9000. CmdArgs.push_back(
  9001. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  9002. else
  9003. CmdArgs.push_back(
  9004. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  9005. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  9006. }
  9007. getToolChain().addProfileRTLibs(Args, CmdArgs);
  9008. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  9009. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9010. }
  9011. // Try to find Exe from a Visual Studio distribution. This first tries to find
  9012. // an installed copy of Visual Studio and, failing that, looks in the PATH,
  9013. // making sure that whatever executable that's found is not a same-named exe
  9014. // from clang itself to prevent clang from falling back to itself.
  9015. static std::string FindVisualStudioExecutable(const ToolChain &TC,
  9016. const char *Exe,
  9017. const char *ClangProgramPath) {
  9018. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  9019. std::string visualStudioBinDir;
  9020. if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
  9021. visualStudioBinDir)) {
  9022. SmallString<128> FilePath(visualStudioBinDir);
  9023. llvm::sys::path::append(FilePath, Exe);
  9024. if (llvm::sys::fs::can_execute(FilePath.c_str()))
  9025. return FilePath.str();
  9026. }
  9027. return Exe;
  9028. }
  9029. void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9030. const InputInfo &Output,
  9031. const InputInfoList &Inputs,
  9032. const ArgList &Args,
  9033. const char *LinkingOutput) const {
  9034. ArgStringList CmdArgs;
  9035. const ToolChain &TC = getToolChain();
  9036. assert((Output.isFilename() || Output.isNothing()) && "invalid output");
  9037. if (Output.isFilename())
  9038. CmdArgs.push_back(
  9039. Args.MakeArgString(std::string("-out:") + Output.getFilename()));
  9040. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
  9041. !C.getDriver().IsCLMode())
  9042. CmdArgs.push_back("-defaultlib:libcmt");
  9043. if (!llvm::sys::Process::GetEnv("LIB")) {
  9044. // If the VC environment hasn't been configured (perhaps because the user
  9045. // did not run vcvarsall), try to build a consistent link environment. If
  9046. // the environment variable is set however, assume the user knows what
  9047. // they're doing.
  9048. std::string VisualStudioDir;
  9049. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  9050. if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
  9051. SmallString<128> LibDir(VisualStudioDir);
  9052. llvm::sys::path::append(LibDir, "VC", "lib");
  9053. switch (MSVC.getArch()) {
  9054. case llvm::Triple::x86:
  9055. // x86 just puts the libraries directly in lib
  9056. break;
  9057. case llvm::Triple::x86_64:
  9058. llvm::sys::path::append(LibDir, "amd64");
  9059. break;
  9060. case llvm::Triple::arm:
  9061. llvm::sys::path::append(LibDir, "arm");
  9062. break;
  9063. default:
  9064. break;
  9065. }
  9066. CmdArgs.push_back(
  9067. Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
  9068. if (MSVC.useUniversalCRT(VisualStudioDir)) {
  9069. std::string UniversalCRTLibPath;
  9070. if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
  9071. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  9072. UniversalCRTLibPath.c_str()));
  9073. }
  9074. }
  9075. std::string WindowsSdkLibPath;
  9076. if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
  9077. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  9078. WindowsSdkLibPath.c_str()));
  9079. }
  9080. if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L))
  9081. for (const auto &LibPath : Args.getAllArgValues(options::OPT_L))
  9082. CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
  9083. CmdArgs.push_back("-nologo");
  9084. if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7,
  9085. options::OPT__SLASH_Zd))
  9086. CmdArgs.push_back("-debug");
  9087. bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
  9088. options::OPT_shared);
  9089. if (DLL) {
  9090. CmdArgs.push_back(Args.MakeArgString("-dll"));
  9091. SmallString<128> ImplibName(Output.getFilename());
  9092. llvm::sys::path::replace_extension(ImplibName, "lib");
  9093. CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
  9094. }
  9095. if (TC.getSanitizerArgs().needsAsanRt()) {
  9096. CmdArgs.push_back(Args.MakeArgString("-debug"));
  9097. CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
  9098. if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
  9099. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  9100. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  9101. // Make sure the dynamic runtime thunk is not optimized out at link time
  9102. // to ensure proper SEH handling.
  9103. CmdArgs.push_back(Args.MakeArgString(
  9104. TC.getArch() == llvm::Triple::x86
  9105. ? "-include:___asan_seh_interceptor"
  9106. : "-include:__asan_seh_interceptor"));
  9107. } else if (DLL) {
  9108. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  9109. } else {
  9110. for (const auto &Lib : {"asan", "asan_cxx"})
  9111. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  9112. }
  9113. }
  9114. Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
  9115. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  9116. options::OPT_fno_openmp, false)) {
  9117. CmdArgs.push_back("-nodefaultlib:vcomp.lib");
  9118. CmdArgs.push_back("-nodefaultlib:vcompd.lib");
  9119. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  9120. TC.getDriver().Dir + "/../lib"));
  9121. switch (TC.getDriver().getOpenMPRuntime(Args)) {
  9122. case Driver::OMPRT_OMP:
  9123. CmdArgs.push_back("-defaultlib:libomp.lib");
  9124. break;
  9125. case Driver::OMPRT_IOMP5:
  9126. CmdArgs.push_back("-defaultlib:libiomp5md.lib");
  9127. break;
  9128. case Driver::OMPRT_GOMP:
  9129. break;
  9130. case Driver::OMPRT_Unknown:
  9131. // Already diagnosed.
  9132. break;
  9133. }
  9134. }
  9135. // Add compiler-rt lib in case if it was explicitly
  9136. // specified as an argument for --rtlib option.
  9137. if (!Args.hasArg(options::OPT_nostdlib)) {
  9138. AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
  9139. }
  9140. // Add filenames, libraries, and other linker inputs.
  9141. for (const auto &Input : Inputs) {
  9142. if (Input.isFilename()) {
  9143. CmdArgs.push_back(Input.getFilename());
  9144. continue;
  9145. }
  9146. const Arg &A = Input.getInputArg();
  9147. // Render -l options differently for the MSVC linker.
  9148. if (A.getOption().matches(options::OPT_l)) {
  9149. StringRef Lib = A.getValue();
  9150. const char *LinkLibArg;
  9151. if (Lib.endswith(".lib"))
  9152. LinkLibArg = Args.MakeArgString(Lib);
  9153. else
  9154. LinkLibArg = Args.MakeArgString(Lib + ".lib");
  9155. CmdArgs.push_back(LinkLibArg);
  9156. continue;
  9157. }
  9158. // Otherwise, this is some other kind of linker input option like -Wl, -z,
  9159. // or -L. Render it, even if MSVC doesn't understand it.
  9160. A.renderAsInput(Args, CmdArgs);
  9161. }
  9162. TC.addProfileRTLibs(Args, CmdArgs);
  9163. // We need to special case some linker paths. In the case of lld, we need to
  9164. // translate 'lld' into 'lld-link', and in the case of the regular msvc
  9165. // linker, we need to use a special search algorithm.
  9166. llvm::SmallString<128> linkPath;
  9167. StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
  9168. if (Linker.equals_lower("lld"))
  9169. Linker = "lld-link";
  9170. if (Linker.equals_lower("link")) {
  9171. // If we're using the MSVC linker, it's not sufficient to just use link
  9172. // from the program PATH, because other environments like GnuWin32 install
  9173. // their own link.exe which may come first.
  9174. linkPath = FindVisualStudioExecutable(TC, "link.exe",
  9175. C.getDriver().getClangProgramPath());
  9176. } else {
  9177. linkPath = Linker;
  9178. llvm::sys::path::replace_extension(linkPath, "exe");
  9179. linkPath = TC.GetProgramPath(linkPath.c_str());
  9180. }
  9181. const char *Exec = Args.MakeArgString(linkPath);
  9182. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9183. }
  9184. void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  9185. const InputInfo &Output,
  9186. const InputInfoList &Inputs,
  9187. const ArgList &Args,
  9188. const char *LinkingOutput) const {
  9189. C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
  9190. }
  9191. std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
  9192. Compilation &C, const JobAction &JA, const InputInfo &Output,
  9193. const InputInfoList &Inputs, const ArgList &Args,
  9194. const char *LinkingOutput) const {
  9195. ArgStringList CmdArgs;
  9196. CmdArgs.push_back("/nologo");
  9197. CmdArgs.push_back("/c"); // Compile only.
  9198. CmdArgs.push_back("/W0"); // No warnings.
  9199. // The goal is to be able to invoke this tool correctly based on
  9200. // any flag accepted by clang-cl.
  9201. // These are spelled the same way in clang and cl.exe,.
  9202. Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
  9203. // Optimization level.
  9204. if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
  9205. CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
  9206. : "/Oi-");
  9207. if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
  9208. if (A->getOption().getID() == options::OPT_O0) {
  9209. CmdArgs.push_back("/Od");
  9210. } else {
  9211. CmdArgs.push_back("/Og");
  9212. StringRef OptLevel = A->getValue();
  9213. if (OptLevel == "s" || OptLevel == "z")
  9214. CmdArgs.push_back("/Os");
  9215. else
  9216. CmdArgs.push_back("/Ot");
  9217. CmdArgs.push_back("/Ob2");
  9218. }
  9219. }
  9220. if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
  9221. options::OPT_fno_omit_frame_pointer))
  9222. CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
  9223. ? "/Oy"
  9224. : "/Oy-");
  9225. if (!Args.hasArg(options::OPT_fwritable_strings))
  9226. CmdArgs.push_back("/GF");
  9227. // Flags for which clang-cl has an alias.
  9228. // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
  9229. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  9230. /*default=*/false))
  9231. CmdArgs.push_back("/GR-");
  9232. if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS,
  9233. /*default=*/false))
  9234. CmdArgs.push_back("/GS-");
  9235. if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
  9236. options::OPT_fno_function_sections))
  9237. CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
  9238. ? "/Gy"
  9239. : "/Gy-");
  9240. if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
  9241. options::OPT_fno_data_sections))
  9242. CmdArgs.push_back(
  9243. A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
  9244. if (Args.hasArg(options::OPT_fsyntax_only))
  9245. CmdArgs.push_back("/Zs");
  9246. if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
  9247. options::OPT__SLASH_Z7))
  9248. CmdArgs.push_back("/Z7");
  9249. std::vector<std::string> Includes =
  9250. Args.getAllArgValues(options::OPT_include);
  9251. for (const auto &Include : Includes)
  9252. CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
  9253. // Flags that can simply be passed through.
  9254. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
  9255. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
  9256. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
  9257. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
  9258. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
  9259. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
  9260. // The order of these flags is relevant, so pick the last one.
  9261. if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
  9262. options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
  9263. A->render(Args, CmdArgs);
  9264. // Pass through all unknown arguments so that the fallback command can see
  9265. // them too.
  9266. Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
  9267. // Input filename.
  9268. assert(Inputs.size() == 1);
  9269. const InputInfo &II = Inputs[0];
  9270. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
  9271. CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
  9272. if (II.isFilename())
  9273. CmdArgs.push_back(II.getFilename());
  9274. else
  9275. II.getInputArg().renderAsInput(Args, CmdArgs);
  9276. // Output filename.
  9277. assert(Output.getType() == types::TY_Object);
  9278. const char *Fo =
  9279. Args.MakeArgString(std::string("/Fo") + Output.getFilename());
  9280. CmdArgs.push_back(Fo);
  9281. const Driver &D = getToolChain().getDriver();
  9282. std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
  9283. D.getClangProgramPath());
  9284. return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9285. CmdArgs, Inputs);
  9286. }
  9287. /// MinGW Tools
  9288. void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9289. const InputInfo &Output,
  9290. const InputInfoList &Inputs,
  9291. const ArgList &Args,
  9292. const char *LinkingOutput) const {
  9293. claimNoWarnArgs(Args);
  9294. ArgStringList CmdArgs;
  9295. if (getToolChain().getArch() == llvm::Triple::x86) {
  9296. CmdArgs.push_back("--32");
  9297. } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
  9298. CmdArgs.push_back("--64");
  9299. }
  9300. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9301. CmdArgs.push_back("-o");
  9302. CmdArgs.push_back(Output.getFilename());
  9303. for (const auto &II : Inputs)
  9304. CmdArgs.push_back(II.getFilename());
  9305. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  9306. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9307. if (Args.hasArg(options::OPT_gsplit_dwarf))
  9308. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  9309. SplitDebugName(Args, Inputs[0]));
  9310. }
  9311. void MinGW::Linker::AddLibGCC(const ArgList &Args,
  9312. ArgStringList &CmdArgs) const {
  9313. if (Args.hasArg(options::OPT_mthreads))
  9314. CmdArgs.push_back("-lmingwthrd");
  9315. CmdArgs.push_back("-lmingw32");
  9316. // Make use of compiler-rt if --rtlib option is used
  9317. ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
  9318. if (RLT == ToolChain::RLT_Libgcc) {
  9319. bool Static = Args.hasArg(options::OPT_static_libgcc) ||
  9320. Args.hasArg(options::OPT_static);
  9321. bool Shared = Args.hasArg(options::OPT_shared);
  9322. bool CXX = getToolChain().getDriver().CCCIsCXX();
  9323. if (Static || (!CXX && !Shared)) {
  9324. CmdArgs.push_back("-lgcc");
  9325. CmdArgs.push_back("-lgcc_eh");
  9326. } else {
  9327. CmdArgs.push_back("-lgcc_s");
  9328. CmdArgs.push_back("-lgcc");
  9329. }
  9330. } else {
  9331. AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
  9332. }
  9333. CmdArgs.push_back("-lmoldname");
  9334. CmdArgs.push_back("-lmingwex");
  9335. CmdArgs.push_back("-lmsvcrt");
  9336. }
  9337. void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9338. const InputInfo &Output,
  9339. const InputInfoList &Inputs,
  9340. const ArgList &Args,
  9341. const char *LinkingOutput) const {
  9342. const ToolChain &TC = getToolChain();
  9343. const Driver &D = TC.getDriver();
  9344. // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
  9345. ArgStringList CmdArgs;
  9346. // Silence warning for "clang -g foo.o -o foo"
  9347. Args.ClaimAllArgs(options::OPT_g_Group);
  9348. // and "clang -emit-llvm foo.o -o foo"
  9349. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9350. // and for "clang -w foo.o -o foo". Other warning options are already
  9351. // handled somewhere else.
  9352. Args.ClaimAllArgs(options::OPT_w);
  9353. StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
  9354. if (LinkerName.equals_lower("lld")) {
  9355. CmdArgs.push_back("-flavor");
  9356. CmdArgs.push_back("gnu");
  9357. } else if (!LinkerName.equals_lower("ld")) {
  9358. D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
  9359. }
  9360. if (!D.SysRoot.empty())
  9361. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9362. if (Args.hasArg(options::OPT_s))
  9363. CmdArgs.push_back("-s");
  9364. CmdArgs.push_back("-m");
  9365. if (TC.getArch() == llvm::Triple::x86)
  9366. CmdArgs.push_back("i386pe");
  9367. if (TC.getArch() == llvm::Triple::x86_64)
  9368. CmdArgs.push_back("i386pep");
  9369. if (TC.getArch() == llvm::Triple::arm)
  9370. CmdArgs.push_back("thumb2pe");
  9371. if (Args.hasArg(options::OPT_mwindows)) {
  9372. CmdArgs.push_back("--subsystem");
  9373. CmdArgs.push_back("windows");
  9374. } else if (Args.hasArg(options::OPT_mconsole)) {
  9375. CmdArgs.push_back("--subsystem");
  9376. CmdArgs.push_back("console");
  9377. }
  9378. if (Args.hasArg(options::OPT_static))
  9379. CmdArgs.push_back("-Bstatic");
  9380. else {
  9381. if (Args.hasArg(options::OPT_mdll))
  9382. CmdArgs.push_back("--dll");
  9383. else if (Args.hasArg(options::OPT_shared))
  9384. CmdArgs.push_back("--shared");
  9385. CmdArgs.push_back("-Bdynamic");
  9386. if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
  9387. CmdArgs.push_back("-e");
  9388. if (TC.getArch() == llvm::Triple::x86)
  9389. CmdArgs.push_back("_DllMainCRTStartup@12");
  9390. else
  9391. CmdArgs.push_back("DllMainCRTStartup");
  9392. CmdArgs.push_back("--enable-auto-image-base");
  9393. }
  9394. }
  9395. CmdArgs.push_back("-o");
  9396. CmdArgs.push_back(Output.getFilename());
  9397. Args.AddAllArgs(CmdArgs, options::OPT_e);
  9398. // FIXME: add -N, -n flags
  9399. Args.AddLastArg(CmdArgs, options::OPT_r);
  9400. Args.AddLastArg(CmdArgs, options::OPT_s);
  9401. Args.AddLastArg(CmdArgs, options::OPT_t);
  9402. Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
  9403. Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
  9404. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9405. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
  9406. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
  9407. } else {
  9408. if (Args.hasArg(options::OPT_municode))
  9409. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
  9410. else
  9411. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
  9412. }
  9413. if (Args.hasArg(options::OPT_pg))
  9414. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
  9415. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  9416. }
  9417. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9418. TC.AddFilePathLibArgs(Args, CmdArgs);
  9419. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  9420. // TODO: Add ASan stuff here
  9421. // TODO: Add profile stuff here
  9422. if (D.CCCIsCXX() &&
  9423. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  9424. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  9425. !Args.hasArg(options::OPT_static);
  9426. if (OnlyLibstdcxxStatic)
  9427. CmdArgs.push_back("-Bstatic");
  9428. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  9429. if (OnlyLibstdcxxStatic)
  9430. CmdArgs.push_back("-Bdynamic");
  9431. }
  9432. if (!Args.hasArg(options::OPT_nostdlib)) {
  9433. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  9434. if (Args.hasArg(options::OPT_static))
  9435. CmdArgs.push_back("--start-group");
  9436. if (Args.hasArg(options::OPT_fstack_protector) ||
  9437. Args.hasArg(options::OPT_fstack_protector_strong) ||
  9438. Args.hasArg(options::OPT_fstack_protector_all)) {
  9439. CmdArgs.push_back("-lssp_nonshared");
  9440. CmdArgs.push_back("-lssp");
  9441. }
  9442. if (Args.hasArg(options::OPT_fopenmp))
  9443. CmdArgs.push_back("-lgomp");
  9444. AddLibGCC(Args, CmdArgs);
  9445. if (Args.hasArg(options::OPT_pg))
  9446. CmdArgs.push_back("-lgmon");
  9447. if (Args.hasArg(options::OPT_pthread))
  9448. CmdArgs.push_back("-lpthread");
  9449. // add system libraries
  9450. if (Args.hasArg(options::OPT_mwindows)) {
  9451. CmdArgs.push_back("-lgdi32");
  9452. CmdArgs.push_back("-lcomdlg32");
  9453. }
  9454. CmdArgs.push_back("-ladvapi32");
  9455. CmdArgs.push_back("-lshell32");
  9456. CmdArgs.push_back("-luser32");
  9457. CmdArgs.push_back("-lkernel32");
  9458. if (Args.hasArg(options::OPT_static))
  9459. CmdArgs.push_back("--end-group");
  9460. else if (!LinkerName.equals_lower("lld"))
  9461. AddLibGCC(Args, CmdArgs);
  9462. }
  9463. if (!Args.hasArg(options::OPT_nostartfiles)) {
  9464. // Add crtfastmath.o if available and fast math is enabled.
  9465. TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  9466. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  9467. }
  9468. }
  9469. const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
  9470. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9471. }
  9472. /// XCore Tools
  9473. // We pass assemble and link construction to the xcc tool.
  9474. void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9475. const InputInfo &Output,
  9476. const InputInfoList &Inputs,
  9477. const ArgList &Args,
  9478. const char *LinkingOutput) const {
  9479. claimNoWarnArgs(Args);
  9480. ArgStringList CmdArgs;
  9481. CmdArgs.push_back("-o");
  9482. CmdArgs.push_back(Output.getFilename());
  9483. CmdArgs.push_back("-c");
  9484. if (Args.hasArg(options::OPT_v))
  9485. CmdArgs.push_back("-v");
  9486. if (Arg *A = Args.getLastArg(options::OPT_g_Group))
  9487. if (!A->getOption().matches(options::OPT_g0))
  9488. CmdArgs.push_back("-g");
  9489. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  9490. false))
  9491. CmdArgs.push_back("-fverbose-asm");
  9492. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9493. for (const auto &II : Inputs)
  9494. CmdArgs.push_back(II.getFilename());
  9495. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  9496. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9497. }
  9498. void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9499. const InputInfo &Output,
  9500. const InputInfoList &Inputs,
  9501. const ArgList &Args,
  9502. const char *LinkingOutput) const {
  9503. ArgStringList CmdArgs;
  9504. if (Output.isFilename()) {
  9505. CmdArgs.push_back("-o");
  9506. CmdArgs.push_back(Output.getFilename());
  9507. } else {
  9508. assert(Output.isNothing() && "Invalid output.");
  9509. }
  9510. if (Args.hasArg(options::OPT_v))
  9511. CmdArgs.push_back("-v");
  9512. // Pass -fexceptions through to the linker if it was present.
  9513. if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  9514. false))
  9515. CmdArgs.push_back("-fexceptions");
  9516. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  9517. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  9518. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9519. }
  9520. void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9521. const InputInfo &Output,
  9522. const InputInfoList &Inputs,
  9523. const ArgList &Args,
  9524. const char *LinkingOutput) const {
  9525. claimNoWarnArgs(Args);
  9526. const auto &TC =
  9527. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  9528. ArgStringList CmdArgs;
  9529. const char *Exec;
  9530. switch (TC.getArch()) {
  9531. default:
  9532. llvm_unreachable("unsupported architecture");
  9533. case llvm::Triple::arm:
  9534. case llvm::Triple::thumb:
  9535. break;
  9536. case llvm::Triple::x86:
  9537. CmdArgs.push_back("--32");
  9538. break;
  9539. case llvm::Triple::x86_64:
  9540. CmdArgs.push_back("--64");
  9541. break;
  9542. }
  9543. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9544. CmdArgs.push_back("-o");
  9545. CmdArgs.push_back(Output.getFilename());
  9546. for (const auto &Input : Inputs)
  9547. CmdArgs.push_back(Input.getFilename());
  9548. const std::string Assembler = TC.GetProgramPath("as");
  9549. Exec = Args.MakeArgString(Assembler);
  9550. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9551. }
  9552. void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9553. const InputInfo &Output,
  9554. const InputInfoList &Inputs,
  9555. const ArgList &Args,
  9556. const char *LinkingOutput) const {
  9557. const auto &TC =
  9558. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  9559. const llvm::Triple &T = TC.getTriple();
  9560. const Driver &D = TC.getDriver();
  9561. SmallString<128> EntryPoint;
  9562. ArgStringList CmdArgs;
  9563. const char *Exec;
  9564. // Silence warning for "clang -g foo.o -o foo"
  9565. Args.ClaimAllArgs(options::OPT_g_Group);
  9566. // and "clang -emit-llvm foo.o -o foo"
  9567. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9568. // and for "clang -w foo.o -o foo"
  9569. Args.ClaimAllArgs(options::OPT_w);
  9570. // Other warning options are already handled somewhere else.
  9571. if (!D.SysRoot.empty())
  9572. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9573. if (Args.hasArg(options::OPT_pie))
  9574. CmdArgs.push_back("-pie");
  9575. if (Args.hasArg(options::OPT_rdynamic))
  9576. CmdArgs.push_back("-export-dynamic");
  9577. if (Args.hasArg(options::OPT_s))
  9578. CmdArgs.push_back("--strip-all");
  9579. CmdArgs.push_back("-m");
  9580. switch (TC.getArch()) {
  9581. default:
  9582. llvm_unreachable("unsupported architecture");
  9583. case llvm::Triple::arm:
  9584. case llvm::Triple::thumb:
  9585. // FIXME: this is incorrect for WinCE
  9586. CmdArgs.push_back("thumb2pe");
  9587. break;
  9588. case llvm::Triple::x86:
  9589. CmdArgs.push_back("i386pe");
  9590. EntryPoint.append("_");
  9591. break;
  9592. case llvm::Triple::x86_64:
  9593. CmdArgs.push_back("i386pep");
  9594. break;
  9595. }
  9596. if (Args.hasArg(options::OPT_shared)) {
  9597. switch (T.getArch()) {
  9598. default:
  9599. llvm_unreachable("unsupported architecture");
  9600. case llvm::Triple::arm:
  9601. case llvm::Triple::thumb:
  9602. case llvm::Triple::x86_64:
  9603. EntryPoint.append("_DllMainCRTStartup");
  9604. break;
  9605. case llvm::Triple::x86:
  9606. EntryPoint.append("_DllMainCRTStartup@12");
  9607. break;
  9608. }
  9609. CmdArgs.push_back("-shared");
  9610. CmdArgs.push_back("-Bdynamic");
  9611. CmdArgs.push_back("--enable-auto-image-base");
  9612. CmdArgs.push_back("--entry");
  9613. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  9614. } else {
  9615. EntryPoint.append("mainCRTStartup");
  9616. CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
  9617. : "-Bdynamic");
  9618. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9619. CmdArgs.push_back("--entry");
  9620. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  9621. }
  9622. // FIXME: handle subsystem
  9623. }
  9624. // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
  9625. CmdArgs.push_back("--allow-multiple-definition");
  9626. CmdArgs.push_back("-o");
  9627. CmdArgs.push_back(Output.getFilename());
  9628. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
  9629. SmallString<261> ImpLib(Output.getFilename());
  9630. llvm::sys::path::replace_extension(ImpLib, ".lib");
  9631. CmdArgs.push_back("--out-implib");
  9632. CmdArgs.push_back(Args.MakeArgString(ImpLib));
  9633. }
  9634. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9635. const std::string CRTPath(D.SysRoot + "/usr/lib/");
  9636. const char *CRTBegin;
  9637. CRTBegin =
  9638. Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
  9639. CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
  9640. }
  9641. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9642. TC.AddFilePathLibArgs(Args, CmdArgs);
  9643. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  9644. if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
  9645. !Args.hasArg(options::OPT_nodefaultlibs)) {
  9646. bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
  9647. !Args.hasArg(options::OPT_static);
  9648. if (StaticCXX)
  9649. CmdArgs.push_back("-Bstatic");
  9650. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  9651. if (StaticCXX)
  9652. CmdArgs.push_back("-Bdynamic");
  9653. }
  9654. if (!Args.hasArg(options::OPT_nostdlib)) {
  9655. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  9656. // TODO handle /MT[d] /MD[d]
  9657. CmdArgs.push_back("-lmsvcrt");
  9658. AddRunTimeLibs(TC, D, CmdArgs, Args);
  9659. }
  9660. }
  9661. if (TC.getSanitizerArgs().needsAsanRt()) {
  9662. // TODO handle /MT[d] /MD[d]
  9663. if (Args.hasArg(options::OPT_shared)) {
  9664. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  9665. } else {
  9666. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  9667. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  9668. // Make sure the dynamic runtime thunk is not optimized out at link time
  9669. // to ensure proper SEH handling.
  9670. CmdArgs.push_back(Args.MakeArgString("--undefined"));
  9671. CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
  9672. ? "___asan_seh_interceptor"
  9673. : "__asan_seh_interceptor"));
  9674. }
  9675. }
  9676. Exec = Args.MakeArgString(TC.GetLinkerPath());
  9677. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9678. }
  9679. void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  9680. const InputInfo &Output,
  9681. const InputInfoList &Inputs,
  9682. const ArgList &Args,
  9683. const char *LinkingOutput) const {
  9684. ArgStringList CmdArgs;
  9685. assert(Inputs.size() == 1);
  9686. const InputInfo &II = Inputs[0];
  9687. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
  9688. II.getType() == types::TY_PP_CXX);
  9689. if (JA.getKind() == Action::PreprocessJobClass) {
  9690. Args.ClaimAllArgs();
  9691. CmdArgs.push_back("-E");
  9692. } else {
  9693. assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
  9694. CmdArgs.push_back("-S");
  9695. CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
  9696. }
  9697. CmdArgs.push_back("-DMYRIAD2");
  9698. // Append all -I, -iquote, -isystem paths, defines/undefines,
  9699. // 'f' flags, optimize flags, and warning options.
  9700. // These are spelled the same way in clang and moviCompile.
  9701. Args.AddAllArgsExcept(
  9702. CmdArgs,
  9703. {options::OPT_I_Group, options::OPT_clang_i_Group, options::OPT_std_EQ,
  9704. options::OPT_D, options::OPT_U, options::OPT_f_Group,
  9705. options::OPT_f_clang_Group, options::OPT_g_Group, options::OPT_M_Group,
  9706. options::OPT_O_Group, options::OPT_W_Group, options::OPT_mcpu_EQ},
  9707. {options::OPT_fno_split_dwarf_inlining});
  9708. Args.hasArg(options::OPT_fno_split_dwarf_inlining); // Claim it if present.
  9709. // If we're producing a dependency file, and assembly is the final action,
  9710. // then the name of the target in the dependency file should be the '.o'
  9711. // file, not the '.s' file produced by this step. For example, instead of
  9712. // /tmp/mumble.s: mumble.c .../someheader.h
  9713. // the filename on the lefthand side should be "mumble.o"
  9714. if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
  9715. C.getActions().size() == 1 &&
  9716. C.getActions()[0]->getKind() == Action::AssembleJobClass) {
  9717. Arg *A = Args.getLastArg(options::OPT_o);
  9718. if (A) {
  9719. CmdArgs.push_back("-MT");
  9720. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  9721. }
  9722. }
  9723. CmdArgs.push_back(II.getFilename());
  9724. CmdArgs.push_back("-o");
  9725. CmdArgs.push_back(Output.getFilename());
  9726. std::string Exec =
  9727. Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
  9728. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9729. CmdArgs, Inputs));
  9730. }
  9731. void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9732. const InputInfo &Output,
  9733. const InputInfoList &Inputs,
  9734. const ArgList &Args,
  9735. const char *LinkingOutput) const {
  9736. ArgStringList CmdArgs;
  9737. assert(Inputs.size() == 1);
  9738. const InputInfo &II = Inputs[0];
  9739. assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
  9740. assert(Output.getType() == types::TY_Object);
  9741. CmdArgs.push_back("-no6thSlotCompression");
  9742. const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  9743. if (CPUArg)
  9744. CmdArgs.push_back(
  9745. Args.MakeArgString("-cv:" + StringRef(CPUArg->getValue())));
  9746. CmdArgs.push_back("-noSPrefixing");
  9747. CmdArgs.push_back("-a"); // Mystery option.
  9748. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9749. for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
  9750. A->claim();
  9751. CmdArgs.push_back(
  9752. Args.MakeArgString(std::string("-i:") + A->getValue(0)));
  9753. }
  9754. CmdArgs.push_back("-elf"); // Output format.
  9755. CmdArgs.push_back(II.getFilename());
  9756. CmdArgs.push_back(
  9757. Args.MakeArgString(std::string("-o:") + Output.getFilename()));
  9758. std::string Exec =
  9759. Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
  9760. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9761. CmdArgs, Inputs));
  9762. }
  9763. void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9764. const InputInfo &Output,
  9765. const InputInfoList &Inputs,
  9766. const ArgList &Args,
  9767. const char *LinkingOutput) const {
  9768. const auto &TC =
  9769. static_cast<const toolchains::MyriadToolChain &>(getToolChain());
  9770. const llvm::Triple &T = TC.getTriple();
  9771. ArgStringList CmdArgs;
  9772. bool UseStartfiles =
  9773. !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
  9774. bool UseDefaultLibs =
  9775. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
  9776. // Silence warning if the args contain both -nostdlib and -stdlib=.
  9777. Args.getLastArg(options::OPT_stdlib_EQ);
  9778. if (T.getArch() == llvm::Triple::sparc)
  9779. CmdArgs.push_back("-EB");
  9780. else // SHAVE assumes little-endian, and sparcel is expressly so.
  9781. CmdArgs.push_back("-EL");
  9782. // The remaining logic is mostly like gnutools::Linker::ConstructJob,
  9783. // but we never pass through a --sysroot option and various other bits.
  9784. // For example, there are no sanitizers (yet) nor gold linker.
  9785. // Eat some arguments that may be present but have no effect.
  9786. Args.ClaimAllArgs(options::OPT_g_Group);
  9787. Args.ClaimAllArgs(options::OPT_w);
  9788. Args.ClaimAllArgs(options::OPT_static_libgcc);
  9789. if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
  9790. CmdArgs.push_back("-s");
  9791. CmdArgs.push_back("-o");
  9792. CmdArgs.push_back(Output.getFilename());
  9793. if (UseStartfiles) {
  9794. // If you want startfiles, it means you want the builtin crti and crtbegin,
  9795. // but not crt0. Myriad link commands provide their own crt0.o as needed.
  9796. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
  9797. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  9798. }
  9799. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  9800. options::OPT_e, options::OPT_s, options::OPT_t,
  9801. options::OPT_Z_Flag, options::OPT_r});
  9802. TC.AddFilePathLibArgs(Args, CmdArgs);
  9803. bool NeedsSanitizerDeps = addSanitizerRuntimes(TC, Args, CmdArgs);
  9804. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  9805. if (UseDefaultLibs) {
  9806. if (NeedsSanitizerDeps)
  9807. linkSanitizerRuntimeDeps(TC, CmdArgs);
  9808. if (C.getDriver().CCCIsCXX()) {
  9809. if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) {
  9810. CmdArgs.push_back("-lc++");
  9811. CmdArgs.push_back("-lc++abi");
  9812. } else
  9813. CmdArgs.push_back("-lstdc++");
  9814. }
  9815. if (T.getOS() == llvm::Triple::RTEMS) {
  9816. CmdArgs.push_back("--start-group");
  9817. CmdArgs.push_back("-lc");
  9818. CmdArgs.push_back("-lgcc"); // circularly dependent on rtems
  9819. // You must provide your own "-L" option to enable finding these.
  9820. CmdArgs.push_back("-lrtemscpu");
  9821. CmdArgs.push_back("-lrtemsbsp");
  9822. CmdArgs.push_back("--end-group");
  9823. } else {
  9824. CmdArgs.push_back("-lc");
  9825. CmdArgs.push_back("-lgcc");
  9826. }
  9827. }
  9828. if (UseStartfiles) {
  9829. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  9830. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
  9831. }
  9832. std::string Exec =
  9833. Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
  9834. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9835. CmdArgs, Inputs));
  9836. }
  9837. void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
  9838. const InputInfo &Output,
  9839. const InputInfoList &Inputs,
  9840. const ArgList &Args,
  9841. const char *LinkingOutput) const {
  9842. claimNoWarnArgs(Args);
  9843. ArgStringList CmdArgs;
  9844. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9845. CmdArgs.push_back("-o");
  9846. CmdArgs.push_back(Output.getFilename());
  9847. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  9848. const InputInfo &Input = Inputs[0];
  9849. assert(Input.isFilename() && "Invalid input.");
  9850. CmdArgs.push_back(Input.getFilename());
  9851. const char *Exec =
  9852. Args.MakeArgString(getToolChain().GetProgramPath("orbis-as"));
  9853. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9854. }
  9855. static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
  9856. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  9857. if (SanArgs.needsUbsanRt()) {
  9858. CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
  9859. }
  9860. if (SanArgs.needsAsanRt()) {
  9861. CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
  9862. }
  9863. }
  9864. static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
  9865. const JobAction &JA, const InputInfo &Output,
  9866. const InputInfoList &Inputs,
  9867. const ArgList &Args,
  9868. const char *LinkingOutput) {
  9869. const toolchains::FreeBSD &ToolChain =
  9870. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  9871. const Driver &D = ToolChain.getDriver();
  9872. ArgStringList CmdArgs;
  9873. // Silence warning for "clang -g foo.o -o foo"
  9874. Args.ClaimAllArgs(options::OPT_g_Group);
  9875. // and "clang -emit-llvm foo.o -o foo"
  9876. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9877. // and for "clang -w foo.o -o foo". Other warning options are already
  9878. // handled somewhere else.
  9879. Args.ClaimAllArgs(options::OPT_w);
  9880. if (!D.SysRoot.empty())
  9881. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9882. if (Args.hasArg(options::OPT_pie))
  9883. CmdArgs.push_back("-pie");
  9884. if (Args.hasArg(options::OPT_rdynamic))
  9885. CmdArgs.push_back("-export-dynamic");
  9886. if (Args.hasArg(options::OPT_shared))
  9887. CmdArgs.push_back("--oformat=so");
  9888. if (Output.isFilename()) {
  9889. CmdArgs.push_back("-o");
  9890. CmdArgs.push_back(Output.getFilename());
  9891. } else {
  9892. assert(Output.isNothing() && "Invalid output.");
  9893. }
  9894. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  9895. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9896. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  9897. Args.AddAllArgs(CmdArgs, options::OPT_e);
  9898. Args.AddAllArgs(CmdArgs, options::OPT_s);
  9899. Args.AddAllArgs(CmdArgs, options::OPT_t);
  9900. Args.AddAllArgs(CmdArgs, options::OPT_r);
  9901. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  9902. CmdArgs.push_back("--no-demangle");
  9903. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  9904. if (Args.hasArg(options::OPT_pthread)) {
  9905. CmdArgs.push_back("-lpthread");
  9906. }
  9907. const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
  9908. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  9909. }
  9910. static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
  9911. const JobAction &JA, const InputInfo &Output,
  9912. const InputInfoList &Inputs,
  9913. const ArgList &Args,
  9914. const char *LinkingOutput) {
  9915. const toolchains::FreeBSD &ToolChain =
  9916. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  9917. const Driver &D = ToolChain.getDriver();
  9918. ArgStringList CmdArgs;
  9919. // Silence warning for "clang -g foo.o -o foo"
  9920. Args.ClaimAllArgs(options::OPT_g_Group);
  9921. // and "clang -emit-llvm foo.o -o foo"
  9922. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9923. // and for "clang -w foo.o -o foo". Other warning options are already
  9924. // handled somewhere else.
  9925. Args.ClaimAllArgs(options::OPT_w);
  9926. if (!D.SysRoot.empty())
  9927. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9928. if (Args.hasArg(options::OPT_pie))
  9929. CmdArgs.push_back("-pie");
  9930. if (Args.hasArg(options::OPT_static)) {
  9931. CmdArgs.push_back("-Bstatic");
  9932. } else {
  9933. if (Args.hasArg(options::OPT_rdynamic))
  9934. CmdArgs.push_back("-export-dynamic");
  9935. CmdArgs.push_back("--eh-frame-hdr");
  9936. if (Args.hasArg(options::OPT_shared)) {
  9937. CmdArgs.push_back("-Bshareable");
  9938. } else {
  9939. CmdArgs.push_back("-dynamic-linker");
  9940. CmdArgs.push_back("/libexec/ld-elf.so.1");
  9941. }
  9942. CmdArgs.push_back("--enable-new-dtags");
  9943. }
  9944. if (Output.isFilename()) {
  9945. CmdArgs.push_back("-o");
  9946. CmdArgs.push_back(Output.getFilename());
  9947. } else {
  9948. assert(Output.isNothing() && "Invalid output.");
  9949. }
  9950. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  9951. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9952. const char *crt1 = nullptr;
  9953. if (!Args.hasArg(options::OPT_shared)) {
  9954. if (Args.hasArg(options::OPT_pg))
  9955. crt1 = "gcrt1.o";
  9956. else if (Args.hasArg(options::OPT_pie))
  9957. crt1 = "Scrt1.o";
  9958. else
  9959. crt1 = "crt1.o";
  9960. }
  9961. if (crt1)
  9962. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  9963. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  9964. const char *crtbegin = nullptr;
  9965. if (Args.hasArg(options::OPT_static))
  9966. crtbegin = "crtbeginT.o";
  9967. else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  9968. crtbegin = "crtbeginS.o";
  9969. else
  9970. crtbegin = "crtbegin.o";
  9971. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  9972. }
  9973. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9974. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  9975. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  9976. Args.AddAllArgs(CmdArgs, options::OPT_e);
  9977. Args.AddAllArgs(CmdArgs, options::OPT_s);
  9978. Args.AddAllArgs(CmdArgs, options::OPT_t);
  9979. Args.AddAllArgs(CmdArgs, options::OPT_r);
  9980. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  9981. CmdArgs.push_back("--no-demangle");
  9982. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  9983. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  9984. // For PS4, we always want to pass libm, libstdc++ and libkernel
  9985. // libraries for both C and C++ compilations.
  9986. CmdArgs.push_back("-lkernel");
  9987. if (D.CCCIsCXX()) {
  9988. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  9989. if (Args.hasArg(options::OPT_pg))
  9990. CmdArgs.push_back("-lm_p");
  9991. else
  9992. CmdArgs.push_back("-lm");
  9993. }
  9994. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  9995. // the default system libraries. Just mimic this for now.
  9996. if (Args.hasArg(options::OPT_pg))
  9997. CmdArgs.push_back("-lgcc_p");
  9998. else
  9999. CmdArgs.push_back("-lcompiler_rt");
  10000. if (Args.hasArg(options::OPT_static)) {
  10001. CmdArgs.push_back("-lstdc++");
  10002. } else if (Args.hasArg(options::OPT_pg)) {
  10003. CmdArgs.push_back("-lgcc_eh_p");
  10004. } else {
  10005. CmdArgs.push_back("--as-needed");
  10006. CmdArgs.push_back("-lstdc++");
  10007. CmdArgs.push_back("--no-as-needed");
  10008. }
  10009. if (Args.hasArg(options::OPT_pthread)) {
  10010. if (Args.hasArg(options::OPT_pg))
  10011. CmdArgs.push_back("-lpthread_p");
  10012. else
  10013. CmdArgs.push_back("-lpthread");
  10014. }
  10015. if (Args.hasArg(options::OPT_pg)) {
  10016. if (Args.hasArg(options::OPT_shared))
  10017. CmdArgs.push_back("-lc");
  10018. else {
  10019. if (Args.hasArg(options::OPT_static)) {
  10020. CmdArgs.push_back("--start-group");
  10021. CmdArgs.push_back("-lc_p");
  10022. CmdArgs.push_back("-lpthread_p");
  10023. CmdArgs.push_back("--end-group");
  10024. } else {
  10025. CmdArgs.push_back("-lc_p");
  10026. }
  10027. }
  10028. CmdArgs.push_back("-lgcc_p");
  10029. } else {
  10030. if (Args.hasArg(options::OPT_static)) {
  10031. CmdArgs.push_back("--start-group");
  10032. CmdArgs.push_back("-lc");
  10033. CmdArgs.push_back("-lpthread");
  10034. CmdArgs.push_back("--end-group");
  10035. } else {
  10036. CmdArgs.push_back("-lc");
  10037. }
  10038. CmdArgs.push_back("-lcompiler_rt");
  10039. }
  10040. if (Args.hasArg(options::OPT_static)) {
  10041. CmdArgs.push_back("-lstdc++");
  10042. } else if (Args.hasArg(options::OPT_pg)) {
  10043. CmdArgs.push_back("-lgcc_eh_p");
  10044. } else {
  10045. CmdArgs.push_back("--as-needed");
  10046. CmdArgs.push_back("-lstdc++");
  10047. CmdArgs.push_back("--no-as-needed");
  10048. }
  10049. }
  10050. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  10051. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  10052. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  10053. else
  10054. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  10055. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  10056. }
  10057. const char *Exec =
  10058. #ifdef LLVM_ON_WIN32
  10059. Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld.gold"));
  10060. #else
  10061. Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
  10062. #endif
  10063. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  10064. }
  10065. void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
  10066. const InputInfo &Output,
  10067. const InputInfoList &Inputs,
  10068. const ArgList &Args,
  10069. const char *LinkingOutput) const {
  10070. const toolchains::FreeBSD &ToolChain =
  10071. static_cast<const toolchains::FreeBSD &>(getToolChain());
  10072. const Driver &D = ToolChain.getDriver();
  10073. bool PS4Linker;
  10074. StringRef LinkerOptName;
  10075. if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
  10076. LinkerOptName = A->getValue();
  10077. if (LinkerOptName != "ps4" && LinkerOptName != "gold")
  10078. D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
  10079. }
  10080. if (LinkerOptName == "gold")
  10081. PS4Linker = false;
  10082. else if (LinkerOptName == "ps4")
  10083. PS4Linker = true;
  10084. else
  10085. PS4Linker = !Args.hasArg(options::OPT_shared);
  10086. if (PS4Linker)
  10087. ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  10088. else
  10089. ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  10090. }
  10091. void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  10092. const InputInfo &Output,
  10093. const InputInfoList &Inputs,
  10094. const ArgList &Args,
  10095. const char *LinkingOutput) const {
  10096. const auto &TC =
  10097. static_cast<const toolchains::CudaToolChain &>(getToolChain());
  10098. assert(TC.getTriple().isNVPTX() && "Wrong platform");
  10099. // Obtain architecture from the action.
  10100. CudaArch gpu_arch = StringToCudaArch(JA.getOffloadingArch());
  10101. assert(gpu_arch != CudaArch::UNKNOWN &&
  10102. "Device action expected to have an architecture.");
  10103. // Check that our installation's ptxas supports gpu_arch.
  10104. if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
  10105. TC.cudaInstallation().CheckCudaVersionSupportsArch(gpu_arch);
  10106. }
  10107. ArgStringList CmdArgs;
  10108. CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
  10109. if (Args.hasFlag(options::OPT_cuda_noopt_device_debug,
  10110. options::OPT_no_cuda_noopt_device_debug, false)) {
  10111. // ptxas does not accept -g option if optimization is enabled, so
  10112. // we ignore the compiler's -O* options if we want debug info.
  10113. CmdArgs.push_back("-g");
  10114. CmdArgs.push_back("--dont-merge-basicblocks");
  10115. CmdArgs.push_back("--return-at-end");
  10116. } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  10117. // Map the -O we received to -O{0,1,2,3}.
  10118. //
  10119. // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
  10120. // default, so it may correspond more closely to the spirit of clang -O2.
  10121. // -O3 seems like the least-bad option when -Osomething is specified to
  10122. // clang but it isn't handled below.
  10123. StringRef OOpt = "3";
  10124. if (A->getOption().matches(options::OPT_O4) ||
  10125. A->getOption().matches(options::OPT_Ofast))
  10126. OOpt = "3";
  10127. else if (A->getOption().matches(options::OPT_O0))
  10128. OOpt = "0";
  10129. else if (A->getOption().matches(options::OPT_O)) {
  10130. // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
  10131. OOpt = llvm::StringSwitch<const char *>(A->getValue())
  10132. .Case("1", "1")
  10133. .Case("2", "2")
  10134. .Case("3", "3")
  10135. .Case("s", "2")
  10136. .Case("z", "2")
  10137. .Default("2");
  10138. }
  10139. CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
  10140. } else {
  10141. // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
  10142. // to no optimizations, but ptxas's default is -O3.
  10143. CmdArgs.push_back("-O0");
  10144. }
  10145. CmdArgs.push_back("--gpu-name");
  10146. CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
  10147. CmdArgs.push_back("--output-file");
  10148. CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
  10149. for (const auto& II : Inputs)
  10150. CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
  10151. for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
  10152. CmdArgs.push_back(Args.MakeArgString(A));
  10153. const char *Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
  10154. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  10155. }
  10156. // All inputs to this linker must be from CudaDeviceActions, as we need to look
  10157. // at the Inputs' Actions in order to figure out which GPU architecture they
  10158. // correspond to.
  10159. void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  10160. const InputInfo &Output,
  10161. const InputInfoList &Inputs,
  10162. const ArgList &Args,
  10163. const char *LinkingOutput) const {
  10164. const auto &TC =
  10165. static_cast<const toolchains::CudaToolChain &>(getToolChain());
  10166. assert(TC.getTriple().isNVPTX() && "Wrong platform");
  10167. ArgStringList CmdArgs;
  10168. CmdArgs.push_back("--cuda");
  10169. CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
  10170. CmdArgs.push_back(Args.MakeArgString("--create"));
  10171. CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
  10172. for (const auto& II : Inputs) {
  10173. auto *A = II.getAction();
  10174. assert(A->getInputs().size() == 1 &&
  10175. "Device offload action is expected to have a single input");
  10176. const char *gpu_arch_str = A->getOffloadingArch();
  10177. assert(gpu_arch_str &&
  10178. "Device action expected to have associated a GPU architecture!");
  10179. CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
  10180. // We need to pass an Arch of the form "sm_XX" for cubin files and
  10181. // "compute_XX" for ptx.
  10182. const char *Arch =
  10183. (II.getType() == types::TY_PP_Asm)
  10184. ? CudaVirtualArchToString(VirtualArchForCudaArch(gpu_arch))
  10185. : gpu_arch_str;
  10186. CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
  10187. Arch + ",file=" + II.getFilename()));
  10188. }
  10189. for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
  10190. CmdArgs.push_back(Args.MakeArgString(A));
  10191. const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
  10192. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  10193. }