Driver.cpp 187 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971
  1. //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/Driver/Driver.h"
  9. #include "InputInfo.h"
  10. #include "ToolChains/AMDGPU.h"
  11. #include "ToolChains/AVR.h"
  12. #include "ToolChains/Ananas.h"
  13. #include "ToolChains/BareMetal.h"
  14. #include "ToolChains/Clang.h"
  15. #include "ToolChains/CloudABI.h"
  16. #include "ToolChains/Contiki.h"
  17. #include "ToolChains/CrossWindows.h"
  18. #include "ToolChains/Cuda.h"
  19. #include "ToolChains/Darwin.h"
  20. #include "ToolChains/DragonFly.h"
  21. #include "ToolChains/FreeBSD.h"
  22. #include "ToolChains/Fuchsia.h"
  23. #include "ToolChains/Gnu.h"
  24. #include "ToolChains/HIP.h"
  25. #include "ToolChains/Haiku.h"
  26. #include "ToolChains/Hexagon.h"
  27. #include "ToolChains/Hurd.h"
  28. #include "ToolChains/Lanai.h"
  29. #include "ToolChains/Linux.h"
  30. #include "ToolChains/MSP430.h"
  31. #include "ToolChains/MSVC.h"
  32. #include "ToolChains/MinGW.h"
  33. #include "ToolChains/Minix.h"
  34. #include "ToolChains/MipsLinux.h"
  35. #include "ToolChains/Myriad.h"
  36. #include "ToolChains/NaCl.h"
  37. #include "ToolChains/NetBSD.h"
  38. #include "ToolChains/OpenBSD.h"
  39. #include "ToolChains/PS4CPU.h"
  40. #include "ToolChains/PPCLinux.h"
  41. #include "ToolChains/RISCVToolchain.h"
  42. #include "ToolChains/Solaris.h"
  43. #include "ToolChains/TCE.h"
  44. #include "ToolChains/WebAssembly.h"
  45. #include "ToolChains/XCore.h"
  46. #include "clang/Basic/Version.h"
  47. #include "clang/Config/config.h"
  48. #include "clang/Driver/Action.h"
  49. #include "clang/Driver/Compilation.h"
  50. #include "clang/Driver/DriverDiagnostic.h"
  51. #include "clang/Driver/Job.h"
  52. #include "clang/Driver/Options.h"
  53. #include "clang/Driver/SanitizerArgs.h"
  54. #include "clang/Driver/Tool.h"
  55. #include "clang/Driver/ToolChain.h"
  56. #include "llvm/ADT/ArrayRef.h"
  57. #include "llvm/ADT/STLExtras.h"
  58. #include "llvm/ADT/SmallSet.h"
  59. #include "llvm/ADT/StringExtras.h"
  60. #include "llvm/ADT/StringSet.h"
  61. #include "llvm/ADT/StringSwitch.h"
  62. #include "llvm/Config/llvm-config.h"
  63. #include "llvm/Option/Arg.h"
  64. #include "llvm/Option/ArgList.h"
  65. #include "llvm/Option/OptSpecifier.h"
  66. #include "llvm/Option/OptTable.h"
  67. #include "llvm/Option/Option.h"
  68. #include "llvm/Support/CommandLine.h"
  69. #include "llvm/Support/ErrorHandling.h"
  70. #include "llvm/Support/FileSystem.h"
  71. #include "llvm/Support/FormatVariadic.h"
  72. #include "llvm/Support/Path.h"
  73. #include "llvm/Support/PrettyStackTrace.h"
  74. #include "llvm/Support/Process.h"
  75. #include "llvm/Support/Program.h"
  76. #include "llvm/Support/StringSaver.h"
  77. #include "llvm/Support/TargetRegistry.h"
  78. #include "llvm/Support/VirtualFileSystem.h"
  79. #include "llvm/Support/raw_ostream.h"
  80. #include <map>
  81. #include <memory>
  82. #include <utility>
  83. #if LLVM_ON_UNIX
  84. #include <unistd.h> // getpid
  85. #include <sysexits.h> // EX_IOERR
  86. #endif
  87. #ifdef __APPLE__
  88. #include <TargetConditionals.h>
  89. #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
  90. #include "ios_error.h"
  91. #endif
  92. #endif
  93. using namespace clang::driver;
  94. using namespace clang;
  95. using namespace llvm::opt;
  96. // static
  97. std::string Driver::GetResourcesPath(StringRef BinaryPath,
  98. StringRef CustomResourceDir) {
  99. // Since the resource directory is embedded in the module hash, it's important
  100. // that all places that need it call this function, so that they get the
  101. // exact same string ("a/../b/" and "b/" get different hashes, for example).
  102. // Dir is bin/ or lib/, depending on where BinaryPath is.
  103. std::string Dir = llvm::sys::path::parent_path(BinaryPath);
  104. SmallString<128> P(Dir);
  105. if (CustomResourceDir != "") {
  106. llvm::sys::path::append(P, CustomResourceDir);
  107. } else {
  108. // On Windows, libclang.dll is in bin/.
  109. // On non-Windows, libclang.so/.dylib is in lib/.
  110. // With a static-library build of libclang, LibClangPath will contain the
  111. // path of the embedding binary, which for LLVM binaries will be in bin/.
  112. // ../lib gets us to lib/ in both cases.
  113. P = llvm::sys::path::parent_path(Dir);
  114. llvm::sys::path::append(P, Twine("lib") + CLANG_LIBDIR_SUFFIX, "clang",
  115. CLANG_VERSION_STRING);
  116. }
  117. return P.str();
  118. }
  119. Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
  120. DiagnosticsEngine &Diags,
  121. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
  122. : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
  123. SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
  124. ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
  125. DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
  126. CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
  127. CCCPrintBindings(false), CCPrintOptions(false), CCPrintHeaders(false),
  128. CCLogDiagnostics(false), CCGenDiagnostics(false),
  129. TargetTriple(TargetTriple), CCCGenericGCCName(""), Saver(Alloc),
  130. CheckInputsExist(true), GenReproducer(false),
  131. SuppressMissingInputWarning(false) {
  132. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  133. // sysroot location depends on App location, which is unknown at compile time:
  134. SysRoot = ::getenv("SYSROOT");
  135. #endif
  136. // Provide a sane fallback if no VFS is specified.
  137. if (!this->VFS)
  138. this->VFS = llvm::vfs::getRealFileSystem();
  139. Name = llvm::sys::path::filename(ClangExecutable);
  140. Dir = llvm::sys::path::parent_path(ClangExecutable);
  141. InstalledDir = Dir; // Provide a sensible default installed dir.
  142. #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
  143. SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
  144. #endif
  145. #if defined(CLANG_CONFIG_FILE_USER_DIR)
  146. UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
  147. #endif
  148. // Compute the path to the resource directory.
  149. ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
  150. }
  151. void Driver::ParseDriverMode(StringRef ProgramName,
  152. ArrayRef<const char *> Args) {
  153. if (ClangNameParts.isEmpty())
  154. ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
  155. setDriverModeFromOption(ClangNameParts.DriverMode);
  156. for (const char *ArgPtr : Args) {
  157. // Ignore nullptrs, they are the response file's EOL markers.
  158. if (ArgPtr == nullptr)
  159. continue;
  160. const StringRef Arg = ArgPtr;
  161. setDriverModeFromOption(Arg);
  162. }
  163. }
  164. void Driver::setDriverModeFromOption(StringRef Opt) {
  165. const std::string OptName =
  166. getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
  167. if (!Opt.startswith(OptName))
  168. return;
  169. StringRef Value = Opt.drop_front(OptName.size());
  170. if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
  171. .Case("gcc", GCCMode)
  172. .Case("g++", GXXMode)
  173. .Case("cpp", CPPMode)
  174. .Case("cl", CLMode)
  175. .Default(None))
  176. Mode = *M;
  177. else
  178. Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
  179. }
  180. InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
  181. bool IsClCompatMode,
  182. bool &ContainsError) {
  183. llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
  184. ContainsError = false;
  185. unsigned IncludedFlagsBitmask;
  186. unsigned ExcludedFlagsBitmask;
  187. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  188. getIncludeExcludeOptionFlagMasks(IsClCompatMode);
  189. unsigned MissingArgIndex, MissingArgCount;
  190. InputArgList Args =
  191. getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
  192. IncludedFlagsBitmask, ExcludedFlagsBitmask);
  193. // Check for missing argument error.
  194. if (MissingArgCount) {
  195. Diag(diag::err_drv_missing_argument)
  196. << Args.getArgString(MissingArgIndex) << MissingArgCount;
  197. ContainsError |=
  198. Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
  199. SourceLocation()) > DiagnosticsEngine::Warning;
  200. }
  201. // Check for unsupported options.
  202. for (const Arg *A : Args) {
  203. if (A->getOption().hasFlag(options::Unsupported)) {
  204. unsigned DiagID;
  205. auto ArgString = A->getAsString(Args);
  206. std::string Nearest;
  207. if (getOpts().findNearest(
  208. ArgString, Nearest, IncludedFlagsBitmask,
  209. ExcludedFlagsBitmask | options::Unsupported) > 1) {
  210. DiagID = diag::err_drv_unsupported_opt;
  211. Diag(DiagID) << ArgString;
  212. } else {
  213. DiagID = diag::err_drv_unsupported_opt_with_suggestion;
  214. Diag(DiagID) << ArgString << Nearest;
  215. }
  216. ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
  217. DiagnosticsEngine::Warning;
  218. continue;
  219. }
  220. // Warn about -mcpu= without an argument.
  221. if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
  222. Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
  223. ContainsError |= Diags.getDiagnosticLevel(
  224. diag::warn_drv_empty_joined_argument,
  225. SourceLocation()) > DiagnosticsEngine::Warning;
  226. }
  227. }
  228. for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
  229. unsigned DiagID;
  230. auto ArgString = A->getAsString(Args);
  231. std::string Nearest;
  232. if (getOpts().findNearest(
  233. ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
  234. DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
  235. : diag::err_drv_unknown_argument;
  236. Diags.Report(DiagID) << ArgString;
  237. } else {
  238. DiagID = IsCLMode()
  239. ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
  240. : diag::err_drv_unknown_argument_with_suggestion;
  241. Diags.Report(DiagID) << ArgString << Nearest;
  242. }
  243. ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
  244. DiagnosticsEngine::Warning;
  245. }
  246. return Args;
  247. }
  248. // Determine which compilation mode we are in. We look for options which
  249. // affect the phase, starting with the earliest phases, and record which
  250. // option we used to determine the final phase.
  251. phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
  252. Arg **FinalPhaseArg) const {
  253. Arg *PhaseArg = nullptr;
  254. phases::ID FinalPhase;
  255. // -{E,EP,P,M,MM} only run the preprocessor.
  256. if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
  257. (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
  258. (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
  259. (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
  260. FinalPhase = phases::Preprocess;
  261. // --precompile only runs up to precompilation.
  262. } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
  263. FinalPhase = phases::Precompile;
  264. // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
  265. } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
  266. (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
  267. (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
  268. (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
  269. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
  270. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
  271. (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
  272. (PhaseArg = DAL.getLastArg(options::OPT__analyze)) ||
  273. (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
  274. FinalPhase = phases::Compile;
  275. // clang interface stubs
  276. } else if ((PhaseArg = DAL.getLastArg(options::OPT_emit_interface_stubs))) {
  277. FinalPhase = phases::IfsMerge;
  278. // -S only runs up to the backend.
  279. } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
  280. FinalPhase = phases::Backend;
  281. // -c compilation only runs up to the assembler.
  282. } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
  283. FinalPhase = phases::Assemble;
  284. // Otherwise do everything.
  285. } else
  286. FinalPhase = phases::Link;
  287. if (FinalPhaseArg)
  288. *FinalPhaseArg = PhaseArg;
  289. return FinalPhase;
  290. }
  291. static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
  292. StringRef Value, bool Claim = true) {
  293. Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
  294. Args.getBaseArgs().MakeIndex(Value), Value.data());
  295. Args.AddSynthesizedArg(A);
  296. if (Claim)
  297. A->claim();
  298. return A;
  299. }
  300. DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
  301. const llvm::opt::OptTable &Opts = getOpts();
  302. DerivedArgList *DAL = new DerivedArgList(Args);
  303. bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
  304. bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
  305. bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
  306. for (Arg *A : Args) {
  307. // Unfortunately, we have to parse some forwarding options (-Xassembler,
  308. // -Xlinker, -Xpreprocessor) because we either integrate their functionality
  309. // (assembler and preprocessor), or bypass a previous driver ('collect2').
  310. // Rewrite linker options, to replace --no-demangle with a custom internal
  311. // option.
  312. if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
  313. A->getOption().matches(options::OPT_Xlinker)) &&
  314. A->containsValue("--no-demangle")) {
  315. // Add the rewritten no-demangle argument.
  316. DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
  317. // Add the remaining values as Xlinker arguments.
  318. for (StringRef Val : A->getValues())
  319. if (Val != "--no-demangle")
  320. DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
  321. continue;
  322. }
  323. // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
  324. // some build systems. We don't try to be complete here because we don't
  325. // care to encourage this usage model.
  326. if (A->getOption().matches(options::OPT_Wp_COMMA) &&
  327. (A->getValue(0) == StringRef("-MD") ||
  328. A->getValue(0) == StringRef("-MMD"))) {
  329. // Rewrite to -MD/-MMD along with -MF.
  330. if (A->getValue(0) == StringRef("-MD"))
  331. DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
  332. else
  333. DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
  334. if (A->getNumValues() == 2)
  335. DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
  336. continue;
  337. }
  338. // Rewrite reserved library names.
  339. if (A->getOption().matches(options::OPT_l)) {
  340. StringRef Value = A->getValue();
  341. // Rewrite unless -nostdlib is present.
  342. if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
  343. Value == "stdc++") {
  344. DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
  345. continue;
  346. }
  347. // Rewrite unconditionally.
  348. if (Value == "cc_kext") {
  349. DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
  350. continue;
  351. }
  352. }
  353. // Pick up inputs via the -- option.
  354. if (A->getOption().matches(options::OPT__DASH_DASH)) {
  355. A->claim();
  356. for (StringRef Val : A->getValues())
  357. DAL->append(MakeInputArg(*DAL, Opts, Val, false));
  358. continue;
  359. }
  360. DAL->append(A);
  361. }
  362. // Enforce -static if -miamcu is present.
  363. if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
  364. DAL->AddFlagArg(0, Opts.getOption(options::OPT_static));
  365. // Add a default value of -mlinker-version=, if one was given and the user
  366. // didn't specify one.
  367. #if defined(HOST_LINK_VERSION)
  368. if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
  369. strlen(HOST_LINK_VERSION) > 0) {
  370. DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
  371. HOST_LINK_VERSION);
  372. DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
  373. }
  374. #endif
  375. return DAL;
  376. }
  377. /// Compute target triple from args.
  378. ///
  379. /// This routine provides the logic to compute a target triple from various
  380. /// args passed to the driver and the default triple string.
  381. static llvm::Triple computeTargetTriple(const Driver &D,
  382. StringRef TargetTriple,
  383. const ArgList &Args,
  384. StringRef DarwinArchName = "") {
  385. // FIXME: Already done in Compilation *Driver::BuildCompilation
  386. if (const Arg *A = Args.getLastArg(options::OPT_target))
  387. TargetTriple = A->getValue();
  388. llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
  389. // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
  390. // -gnu* only, and we can not change this, so we have to detect that case as
  391. // being the Hurd OS.
  392. if (TargetTriple.find("-unknown-gnu") != StringRef::npos ||
  393. TargetTriple.find("-pc-gnu") != StringRef::npos)
  394. Target.setOSName("hurd");
  395. // Handle Apple-specific options available here.
  396. if (Target.isOSBinFormatMachO()) {
  397. // If an explicit Darwin arch name is given, that trumps all.
  398. if (!DarwinArchName.empty()) {
  399. tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
  400. return Target;
  401. }
  402. // Handle the Darwin '-arch' flag.
  403. if (Arg *A = Args.getLastArg(options::OPT_arch)) {
  404. StringRef ArchName = A->getValue();
  405. tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
  406. }
  407. }
  408. // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
  409. // '-mbig-endian'/'-EB'.
  410. if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
  411. options::OPT_mbig_endian)) {
  412. if (A->getOption().matches(options::OPT_mlittle_endian)) {
  413. llvm::Triple LE = Target.getLittleEndianArchVariant();
  414. if (LE.getArch() != llvm::Triple::UnknownArch)
  415. Target = std::move(LE);
  416. } else {
  417. llvm::Triple BE = Target.getBigEndianArchVariant();
  418. if (BE.getArch() != llvm::Triple::UnknownArch)
  419. Target = std::move(BE);
  420. }
  421. }
  422. // Skip further flag support on OSes which don't support '-m32' or '-m64'.
  423. if (Target.getArch() == llvm::Triple::tce ||
  424. Target.getOS() == llvm::Triple::Minix)
  425. return Target;
  426. // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
  427. Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
  428. options::OPT_m32, options::OPT_m16);
  429. if (A) {
  430. llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
  431. if (A->getOption().matches(options::OPT_m64)) {
  432. AT = Target.get64BitArchVariant().getArch();
  433. if (Target.getEnvironment() == llvm::Triple::GNUX32)
  434. Target.setEnvironment(llvm::Triple::GNU);
  435. } else if (A->getOption().matches(options::OPT_mx32) &&
  436. Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
  437. AT = llvm::Triple::x86_64;
  438. Target.setEnvironment(llvm::Triple::GNUX32);
  439. } else if (A->getOption().matches(options::OPT_m32)) {
  440. AT = Target.get32BitArchVariant().getArch();
  441. if (Target.getEnvironment() == llvm::Triple::GNUX32)
  442. Target.setEnvironment(llvm::Triple::GNU);
  443. } else if (A->getOption().matches(options::OPT_m16) &&
  444. Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
  445. AT = llvm::Triple::x86;
  446. Target.setEnvironment(llvm::Triple::CODE16);
  447. }
  448. if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
  449. Target.setArch(AT);
  450. }
  451. // Handle -miamcu flag.
  452. if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
  453. if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
  454. D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
  455. << Target.str();
  456. if (A && !A->getOption().matches(options::OPT_m32))
  457. D.Diag(diag::err_drv_argument_not_allowed_with)
  458. << "-miamcu" << A->getBaseArg().getAsString(Args);
  459. Target.setArch(llvm::Triple::x86);
  460. Target.setArchName("i586");
  461. Target.setEnvironment(llvm::Triple::UnknownEnvironment);
  462. Target.setEnvironmentName("");
  463. Target.setOS(llvm::Triple::ELFIAMCU);
  464. Target.setVendor(llvm::Triple::UnknownVendor);
  465. Target.setVendorName("intel");
  466. }
  467. // If target is MIPS adjust the target triple
  468. // accordingly to provided ABI name.
  469. A = Args.getLastArg(options::OPT_mabi_EQ);
  470. if (A && Target.isMIPS()) {
  471. StringRef ABIName = A->getValue();
  472. if (ABIName == "32") {
  473. Target = Target.get32BitArchVariant();
  474. if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
  475. Target.getEnvironment() == llvm::Triple::GNUABIN32)
  476. Target.setEnvironment(llvm::Triple::GNU);
  477. } else if (ABIName == "n32") {
  478. Target = Target.get64BitArchVariant();
  479. if (Target.getEnvironment() == llvm::Triple::GNU ||
  480. Target.getEnvironment() == llvm::Triple::GNUABI64)
  481. Target.setEnvironment(llvm::Triple::GNUABIN32);
  482. } else if (ABIName == "64") {
  483. Target = Target.get64BitArchVariant();
  484. if (Target.getEnvironment() == llvm::Triple::GNU ||
  485. Target.getEnvironment() == llvm::Triple::GNUABIN32)
  486. Target.setEnvironment(llvm::Triple::GNUABI64);
  487. }
  488. }
  489. return Target;
  490. }
  491. // Parse the LTO options and record the type of LTO compilation
  492. // based on which -f(no-)?lto(=.*)? option occurs last.
  493. void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
  494. LTOMode = LTOK_None;
  495. if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
  496. options::OPT_fno_lto, false))
  497. return;
  498. StringRef LTOName("full");
  499. const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
  500. if (A)
  501. LTOName = A->getValue();
  502. LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
  503. .Case("full", LTOK_Full)
  504. .Case("thin", LTOK_Thin)
  505. .Default(LTOK_Unknown);
  506. if (LTOMode == LTOK_Unknown) {
  507. assert(A);
  508. Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
  509. << A->getValue();
  510. }
  511. }
  512. /// Compute the desired OpenMP runtime from the flags provided.
  513. Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
  514. StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
  515. const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
  516. if (A)
  517. RuntimeName = A->getValue();
  518. auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
  519. .Case("libomp", OMPRT_OMP)
  520. .Case("libgomp", OMPRT_GOMP)
  521. .Case("libiomp5", OMPRT_IOMP5)
  522. .Default(OMPRT_Unknown);
  523. if (RT == OMPRT_Unknown) {
  524. if (A)
  525. Diag(diag::err_drv_unsupported_option_argument)
  526. << A->getOption().getName() << A->getValue();
  527. else
  528. // FIXME: We could use a nicer diagnostic here.
  529. Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
  530. }
  531. return RT;
  532. }
  533. void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
  534. InputList &Inputs) {
  535. //
  536. // CUDA/HIP
  537. //
  538. // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
  539. // or HIP type. However, mixed CUDA/HIP compilation is not supported.
  540. bool IsCuda =
  541. llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
  542. return types::isCuda(I.first);
  543. });
  544. bool IsHIP =
  545. llvm::any_of(Inputs,
  546. [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
  547. return types::isHIP(I.first);
  548. }) ||
  549. C.getInputArgs().hasArg(options::OPT_hip_link);
  550. if (IsCuda && IsHIP) {
  551. Diag(clang::diag::err_drv_mix_cuda_hip);
  552. return;
  553. }
  554. if (IsCuda) {
  555. const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
  556. const llvm::Triple &HostTriple = HostTC->getTriple();
  557. StringRef DeviceTripleStr;
  558. auto OFK = Action::OFK_Cuda;
  559. DeviceTripleStr =
  560. HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
  561. llvm::Triple CudaTriple(DeviceTripleStr);
  562. // Use the CUDA and host triples as the key into the ToolChains map,
  563. // because the device toolchain we create depends on both.
  564. auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
  565. if (!CudaTC) {
  566. CudaTC = std::make_unique<toolchains::CudaToolChain>(
  567. *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
  568. }
  569. C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
  570. } else if (IsHIP) {
  571. const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
  572. const llvm::Triple &HostTriple = HostTC->getTriple();
  573. StringRef DeviceTripleStr;
  574. auto OFK = Action::OFK_HIP;
  575. DeviceTripleStr = "amdgcn-amd-amdhsa";
  576. llvm::Triple HIPTriple(DeviceTripleStr);
  577. // Use the HIP and host triples as the key into the ToolChains map,
  578. // because the device toolchain we create depends on both.
  579. auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
  580. if (!HIPTC) {
  581. HIPTC = std::make_unique<toolchains::HIPToolChain>(
  582. *this, HIPTriple, *HostTC, C.getInputArgs());
  583. }
  584. C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
  585. }
  586. //
  587. // OpenMP
  588. //
  589. // We need to generate an OpenMP toolchain if the user specified targets with
  590. // the -fopenmp-targets option.
  591. if (Arg *OpenMPTargets =
  592. C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
  593. if (OpenMPTargets->getNumValues()) {
  594. // We expect that -fopenmp-targets is always used in conjunction with the
  595. // option -fopenmp specifying a valid runtime with offloading support,
  596. // i.e. libomp or libiomp.
  597. bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
  598. options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  599. options::OPT_fno_openmp, false);
  600. if (HasValidOpenMPRuntime) {
  601. OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
  602. HasValidOpenMPRuntime =
  603. OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
  604. }
  605. if (HasValidOpenMPRuntime) {
  606. llvm::StringMap<const char *> FoundNormalizedTriples;
  607. for (const char *Val : OpenMPTargets->getValues()) {
  608. llvm::Triple TT(Val);
  609. std::string NormalizedName = TT.normalize();
  610. // Make sure we don't have a duplicate triple.
  611. auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
  612. if (Duplicate != FoundNormalizedTriples.end()) {
  613. Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
  614. << Val << Duplicate->second;
  615. continue;
  616. }
  617. // Store the current triple so that we can check for duplicates in the
  618. // following iterations.
  619. FoundNormalizedTriples[NormalizedName] = Val;
  620. // If the specified target is invalid, emit a diagnostic.
  621. if (TT.getArch() == llvm::Triple::UnknownArch)
  622. Diag(clang::diag::err_drv_invalid_omp_target) << Val;
  623. else {
  624. const ToolChain *TC;
  625. // CUDA toolchains have to be selected differently. They pair host
  626. // and device in their implementation.
  627. if (TT.isNVPTX()) {
  628. const ToolChain *HostTC =
  629. C.getSingleOffloadToolChain<Action::OFK_Host>();
  630. assert(HostTC && "Host toolchain should be always defined.");
  631. auto &CudaTC =
  632. ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
  633. if (!CudaTC)
  634. CudaTC = std::make_unique<toolchains::CudaToolChain>(
  635. *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
  636. TC = CudaTC.get();
  637. } else
  638. TC = &getToolChain(C.getInputArgs(), TT);
  639. C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
  640. }
  641. }
  642. } else
  643. Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
  644. } else
  645. Diag(clang::diag::warn_drv_empty_joined_argument)
  646. << OpenMPTargets->getAsString(C.getInputArgs());
  647. }
  648. //
  649. // TODO: Add support for other offloading programming models here.
  650. //
  651. }
  652. /// Looks the given directories for the specified file.
  653. ///
  654. /// \param[out] FilePath File path, if the file was found.
  655. /// \param[in] Dirs Directories used for the search.
  656. /// \param[in] FileName Name of the file to search for.
  657. /// \return True if file was found.
  658. ///
  659. /// Looks for file specified by FileName sequentially in directories specified
  660. /// by Dirs.
  661. ///
  662. static bool searchForFile(SmallVectorImpl<char> &FilePath,
  663. ArrayRef<std::string> Dirs,
  664. StringRef FileName) {
  665. SmallString<128> WPath;
  666. for (const StringRef &Dir : Dirs) {
  667. if (Dir.empty())
  668. continue;
  669. WPath.clear();
  670. llvm::sys::path::append(WPath, Dir, FileName);
  671. llvm::sys::path::native(WPath);
  672. if (llvm::sys::fs::is_regular_file(WPath)) {
  673. FilePath = std::move(WPath);
  674. return true;
  675. }
  676. }
  677. return false;
  678. }
  679. bool Driver::readConfigFile(StringRef FileName) {
  680. // Try reading the given file.
  681. SmallVector<const char *, 32> NewCfgArgs;
  682. if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
  683. Diag(diag::err_drv_cannot_read_config_file) << FileName;
  684. return true;
  685. }
  686. // Read options from config file.
  687. llvm::SmallString<128> CfgFileName(FileName);
  688. llvm::sys::path::native(CfgFileName);
  689. ConfigFile = CfgFileName.str();
  690. bool ContainErrors;
  691. CfgOptions = std::make_unique<InputArgList>(
  692. ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
  693. if (ContainErrors) {
  694. CfgOptions.reset();
  695. return true;
  696. }
  697. if (CfgOptions->hasArg(options::OPT_config)) {
  698. CfgOptions.reset();
  699. Diag(diag::err_drv_nested_config_file);
  700. return true;
  701. }
  702. // Claim all arguments that come from a configuration file so that the driver
  703. // does not warn on any that is unused.
  704. for (Arg *A : *CfgOptions)
  705. A->claim();
  706. return false;
  707. }
  708. bool Driver::loadConfigFile() {
  709. std::string CfgFileName;
  710. bool FileSpecifiedExplicitly = false;
  711. // Process options that change search path for config files.
  712. if (CLOptions) {
  713. if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
  714. SmallString<128> CfgDir;
  715. CfgDir.append(
  716. CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
  717. if (!CfgDir.empty()) {
  718. if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
  719. SystemConfigDir.clear();
  720. else
  721. SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
  722. }
  723. }
  724. if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
  725. SmallString<128> CfgDir;
  726. CfgDir.append(
  727. CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
  728. if (!CfgDir.empty()) {
  729. if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
  730. UserConfigDir.clear();
  731. else
  732. UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
  733. }
  734. }
  735. }
  736. // First try to find config file specified in command line.
  737. if (CLOptions) {
  738. std::vector<std::string> ConfigFiles =
  739. CLOptions->getAllArgValues(options::OPT_config);
  740. if (ConfigFiles.size() > 1) {
  741. Diag(diag::err_drv_duplicate_config);
  742. return true;
  743. }
  744. if (!ConfigFiles.empty()) {
  745. CfgFileName = ConfigFiles.front();
  746. assert(!CfgFileName.empty());
  747. // If argument contains directory separator, treat it as a path to
  748. // configuration file.
  749. if (llvm::sys::path::has_parent_path(CfgFileName)) {
  750. SmallString<128> CfgFilePath;
  751. if (llvm::sys::path::is_relative(CfgFileName))
  752. llvm::sys::fs::current_path(CfgFilePath);
  753. llvm::sys::path::append(CfgFilePath, CfgFileName);
  754. if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
  755. Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
  756. return true;
  757. }
  758. return readConfigFile(CfgFilePath);
  759. }
  760. FileSpecifiedExplicitly = true;
  761. }
  762. }
  763. // If config file is not specified explicitly, try to deduce configuration
  764. // from executable name. For instance, an executable 'armv7l-clang' will
  765. // search for config file 'armv7l-clang.cfg'.
  766. if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
  767. CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
  768. if (CfgFileName.empty())
  769. return false;
  770. // Determine architecture part of the file name, if it is present.
  771. StringRef CfgFileArch = CfgFileName;
  772. size_t ArchPrefixLen = CfgFileArch.find('-');
  773. if (ArchPrefixLen == StringRef::npos)
  774. ArchPrefixLen = CfgFileArch.size();
  775. llvm::Triple CfgTriple;
  776. CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
  777. CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
  778. if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
  779. ArchPrefixLen = 0;
  780. if (!StringRef(CfgFileName).endswith(".cfg"))
  781. CfgFileName += ".cfg";
  782. // If config file starts with architecture name and command line options
  783. // redefine architecture (with options like -m32 -LE etc), try finding new
  784. // config file with that architecture.
  785. SmallString<128> FixedConfigFile;
  786. size_t FixedArchPrefixLen = 0;
  787. if (ArchPrefixLen) {
  788. // Get architecture name from config file name like 'i386.cfg' or
  789. // 'armv7l-clang.cfg'.
  790. // Check if command line options changes effective triple.
  791. llvm::Triple EffectiveTriple = computeTargetTriple(*this,
  792. CfgTriple.getTriple(), *CLOptions);
  793. if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
  794. FixedConfigFile = EffectiveTriple.getArchName();
  795. FixedArchPrefixLen = FixedConfigFile.size();
  796. // Append the rest of original file name so that file name transforms
  797. // like: i386-clang.cfg -> x86_64-clang.cfg.
  798. if (ArchPrefixLen < CfgFileName.size())
  799. FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
  800. }
  801. }
  802. // Prepare list of directories where config file is searched for.
  803. SmallVector<std::string, 3> CfgFileSearchDirs;
  804. CfgFileSearchDirs.push_back(UserConfigDir);
  805. CfgFileSearchDirs.push_back(SystemConfigDir);
  806. CfgFileSearchDirs.push_back(Dir);
  807. // Try to find config file. First try file with corrected architecture.
  808. llvm::SmallString<128> CfgFilePath;
  809. if (!FixedConfigFile.empty()) {
  810. if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
  811. return readConfigFile(CfgFilePath);
  812. // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
  813. FixedConfigFile.resize(FixedArchPrefixLen);
  814. FixedConfigFile.append(".cfg");
  815. if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
  816. return readConfigFile(CfgFilePath);
  817. }
  818. // Then try original file name.
  819. if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
  820. return readConfigFile(CfgFilePath);
  821. // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
  822. if (!ClangNameParts.ModeSuffix.empty() &&
  823. !ClangNameParts.TargetPrefix.empty()) {
  824. CfgFileName.assign(ClangNameParts.TargetPrefix);
  825. CfgFileName.append(".cfg");
  826. if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
  827. return readConfigFile(CfgFilePath);
  828. }
  829. // Report error but only if config file was specified explicitly, by option
  830. // --config. If it was deduced from executable name, it is not an error.
  831. if (FileSpecifiedExplicitly) {
  832. Diag(diag::err_drv_config_file_not_found) << CfgFileName;
  833. for (const std::string &SearchDir : CfgFileSearchDirs)
  834. if (!SearchDir.empty())
  835. Diag(diag::note_drv_config_file_searched_in) << SearchDir;
  836. return true;
  837. }
  838. return false;
  839. }
  840. Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
  841. llvm::PrettyStackTraceString CrashInfo("Compilation construction");
  842. // FIXME: Handle environment options which affect driver behavior, somewhere
  843. // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
  844. if (Optional<std::string> CompilerPathValue =
  845. llvm::sys::Process::GetEnv("COMPILER_PATH")) {
  846. StringRef CompilerPath = *CompilerPathValue;
  847. while (!CompilerPath.empty()) {
  848. std::pair<StringRef, StringRef> Split =
  849. CompilerPath.split(llvm::sys::EnvPathSeparator);
  850. PrefixDirs.push_back(Split.first);
  851. CompilerPath = Split.second;
  852. }
  853. }
  854. // We look for the driver mode option early, because the mode can affect
  855. // how other options are parsed.
  856. ParseDriverMode(ClangExecutable, ArgList.slice(1));
  857. // FIXME: What are we going to do with -V and -b?
  858. // Arguments specified in command line.
  859. bool ContainsError;
  860. CLOptions = std::make_unique<InputArgList>(
  861. ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
  862. // Try parsing configuration file.
  863. if (!ContainsError)
  864. ContainsError = loadConfigFile();
  865. bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
  866. // All arguments, from both config file and command line.
  867. InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
  868. : std::move(*CLOptions));
  869. // The args for config files or /clang: flags belong to different InputArgList
  870. // objects than Args. This copies an Arg from one of those other InputArgLists
  871. // to the ownership of Args.
  872. auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
  873. unsigned Index = Args.MakeIndex(Opt->getSpelling());
  874. Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
  875. Index, BaseArg);
  876. Copy->getValues() = Opt->getValues();
  877. if (Opt->isClaimed())
  878. Copy->claim();
  879. Args.append(Copy);
  880. };
  881. if (HasConfigFile)
  882. for (auto *Opt : *CLOptions) {
  883. if (Opt->getOption().matches(options::OPT_config))
  884. continue;
  885. const Arg *BaseArg = &Opt->getBaseArg();
  886. if (BaseArg == Opt)
  887. BaseArg = nullptr;
  888. appendOneArg(Opt, BaseArg);
  889. }
  890. // In CL mode, look for any pass-through arguments
  891. if (IsCLMode() && !ContainsError) {
  892. SmallVector<const char *, 16> CLModePassThroughArgList;
  893. for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
  894. A->claim();
  895. CLModePassThroughArgList.push_back(A->getValue());
  896. }
  897. if (!CLModePassThroughArgList.empty()) {
  898. // Parse any pass through args using default clang processing rather
  899. // than clang-cl processing.
  900. auto CLModePassThroughOptions = std::make_unique<InputArgList>(
  901. ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
  902. if (!ContainsError)
  903. for (auto *Opt : *CLModePassThroughOptions) {
  904. appendOneArg(Opt, nullptr);
  905. }
  906. }
  907. }
  908. // Check for working directory option before accessing any files
  909. if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
  910. if (VFS->setCurrentWorkingDirectory(WD->getValue()))
  911. Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
  912. // FIXME: This stuff needs to go into the Compilation, not the driver.
  913. bool CCCPrintPhases;
  914. // Silence driver warnings if requested
  915. Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
  916. // -no-canonical-prefixes is used very early in main.
  917. Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
  918. // Ignore -pipe.
  919. Args.ClaimAllArgs(options::OPT_pipe);
  920. // Extract -ccc args.
  921. //
  922. // FIXME: We need to figure out where this behavior should live. Most of it
  923. // should be outside in the client; the parts that aren't should have proper
  924. // options, either by introducing new ones or by overloading gcc ones like -V
  925. // or -b.
  926. CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
  927. CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
  928. if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
  929. CCCGenericGCCName = A->getValue();
  930. GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
  931. options::OPT_fno_crash_diagnostics,
  932. !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
  933. // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
  934. // and getToolChain is const.
  935. if (IsCLMode()) {
  936. // clang-cl targets MSVC-style Win32.
  937. llvm::Triple T(TargetTriple);
  938. T.setOS(llvm::Triple::Win32);
  939. T.setVendor(llvm::Triple::PC);
  940. T.setEnvironment(llvm::Triple::MSVC);
  941. T.setObjectFormat(llvm::Triple::COFF);
  942. TargetTriple = T.str();
  943. }
  944. if (const Arg *A = Args.getLastArg(options::OPT_target))
  945. TargetTriple = A->getValue();
  946. if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
  947. Dir = InstalledDir = A->getValue();
  948. for (const Arg *A : Args.filtered(options::OPT_B)) {
  949. A->claim();
  950. PrefixDirs.push_back(A->getValue(0));
  951. }
  952. if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
  953. SysRoot = A->getValue();
  954. if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
  955. DyldPrefix = A->getValue();
  956. if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
  957. ResourceDir = A->getValue();
  958. if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
  959. SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
  960. .Case("cwd", SaveTempsCwd)
  961. .Case("obj", SaveTempsObj)
  962. .Default(SaveTempsCwd);
  963. }
  964. setLTOMode(Args);
  965. // Process -fembed-bitcode= flags.
  966. if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
  967. StringRef Name = A->getValue();
  968. unsigned Model = llvm::StringSwitch<unsigned>(Name)
  969. .Case("off", EmbedNone)
  970. .Case("all", EmbedBitcode)
  971. .Case("bitcode", EmbedBitcode)
  972. .Case("marker", EmbedMarker)
  973. .Default(~0U);
  974. if (Model == ~0U) {
  975. Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
  976. << Name;
  977. } else
  978. BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
  979. }
  980. std::unique_ptr<llvm::opt::InputArgList> UArgs =
  981. std::make_unique<InputArgList>(std::move(Args));
  982. // Perform the default argument translations.
  983. DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
  984. // Owned by the host.
  985. const ToolChain &TC = getToolChain(
  986. *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
  987. // The compilation takes ownership of Args.
  988. Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
  989. ContainsError);
  990. if (!HandleImmediateArgs(*C))
  991. return C;
  992. // Construct the list of inputs.
  993. InputList Inputs;
  994. BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
  995. // Populate the tool chains for the offloading devices, if any.
  996. CreateOffloadingDeviceToolChains(*C, Inputs);
  997. // Construct the list of abstract actions to perform for this compilation. On
  998. // MachO targets this uses the driver-driver and universal actions.
  999. if (TC.getTriple().isOSBinFormatMachO())
  1000. BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
  1001. else
  1002. BuildActions(*C, C->getArgs(), Inputs, C->getActions());
  1003. if (CCCPrintPhases) {
  1004. PrintActions(*C);
  1005. return C;
  1006. }
  1007. BuildJobs(*C);
  1008. return C;
  1009. }
  1010. static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
  1011. llvm::opt::ArgStringList ASL;
  1012. for (const auto *A : Args)
  1013. A->render(Args, ASL);
  1014. for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
  1015. if (I != ASL.begin())
  1016. OS << ' ';
  1017. Command::printArg(OS, *I, true);
  1018. }
  1019. OS << '\n';
  1020. }
  1021. bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
  1022. SmallString<128> &CrashDiagDir) {
  1023. using namespace llvm::sys;
  1024. assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
  1025. "Only knows about .crash files on Darwin");
  1026. // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
  1027. // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
  1028. // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
  1029. path::home_directory(CrashDiagDir);
  1030. if (CrashDiagDir.startswith("/var/root"))
  1031. CrashDiagDir = "/";
  1032. path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
  1033. int PID =
  1034. #if LLVM_ON_UNIX
  1035. getpid();
  1036. #else
  1037. 0;
  1038. #endif
  1039. std::error_code EC;
  1040. fs::file_status FileStatus;
  1041. TimePoint<> LastAccessTime;
  1042. SmallString<128> CrashFilePath;
  1043. // Lookup the .crash files and get the one generated by a subprocess spawned
  1044. // by this driver invocation.
  1045. for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
  1046. File != FileEnd && !EC; File.increment(EC)) {
  1047. StringRef FileName = path::filename(File->path());
  1048. if (!FileName.startswith(Name))
  1049. continue;
  1050. if (fs::status(File->path(), FileStatus))
  1051. continue;
  1052. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
  1053. llvm::MemoryBuffer::getFile(File->path());
  1054. if (!CrashFile)
  1055. continue;
  1056. // The first line should start with "Process:", otherwise this isn't a real
  1057. // .crash file.
  1058. StringRef Data = CrashFile.get()->getBuffer();
  1059. if (!Data.startswith("Process:"))
  1060. continue;
  1061. // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
  1062. size_t ParentProcPos = Data.find("Parent Process:");
  1063. if (ParentProcPos == StringRef::npos)
  1064. continue;
  1065. size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
  1066. if (LineEnd == StringRef::npos)
  1067. continue;
  1068. StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
  1069. int OpenBracket = -1, CloseBracket = -1;
  1070. for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
  1071. if (ParentProcess[i] == '[')
  1072. OpenBracket = i;
  1073. if (ParentProcess[i] == ']')
  1074. CloseBracket = i;
  1075. }
  1076. // Extract the parent process PID from the .crash file and check whether
  1077. // it matches this driver invocation pid.
  1078. int CrashPID;
  1079. if (OpenBracket < 0 || CloseBracket < 0 ||
  1080. ParentProcess.slice(OpenBracket + 1, CloseBracket)
  1081. .getAsInteger(10, CrashPID) || CrashPID != PID) {
  1082. continue;
  1083. }
  1084. // Found a .crash file matching the driver pid. To avoid getting an older
  1085. // and misleading crash file, continue looking for the most recent.
  1086. // FIXME: the driver can dispatch multiple cc1 invocations, leading to
  1087. // multiple crashes poiting to the same parent process. Since the driver
  1088. // does not collect pid information for the dispatched invocation there's
  1089. // currently no way to distinguish among them.
  1090. const auto FileAccessTime = FileStatus.getLastModificationTime();
  1091. if (FileAccessTime > LastAccessTime) {
  1092. CrashFilePath.assign(File->path());
  1093. LastAccessTime = FileAccessTime;
  1094. }
  1095. }
  1096. // If found, copy it over to the location of other reproducer files.
  1097. if (!CrashFilePath.empty()) {
  1098. EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
  1099. if (EC)
  1100. return false;
  1101. return true;
  1102. }
  1103. return false;
  1104. }
  1105. // When clang crashes, produce diagnostic information including the fully
  1106. // preprocessed source file(s). Request that the developer attach the
  1107. // diagnostic information to a bug report.
  1108. void Driver::generateCompilationDiagnostics(
  1109. Compilation &C, const Command &FailingCommand,
  1110. StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
  1111. if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
  1112. return;
  1113. // Don't try to generate diagnostics for link or dsymutil jobs.
  1114. if (FailingCommand.getCreator().isLinkJob() ||
  1115. FailingCommand.getCreator().isDsymutilJob())
  1116. return;
  1117. // Print the version of the compiler.
  1118. PrintVersion(C, llvm::errs());
  1119. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1120. << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
  1121. "crash backtrace, preprocessed source, and associated run script.";
  1122. // Suppress driver output and emit preprocessor output to temp file.
  1123. Mode = CPPMode;
  1124. CCGenDiagnostics = true;
  1125. // Save the original job command(s).
  1126. Command Cmd = FailingCommand;
  1127. // Keep track of whether we produce any errors while trying to produce
  1128. // preprocessed sources.
  1129. DiagnosticErrorTrap Trap(Diags);
  1130. // Suppress tool output.
  1131. C.initCompilationForDiagnostics();
  1132. // Construct the list of inputs.
  1133. InputList Inputs;
  1134. BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
  1135. for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
  1136. bool IgnoreInput = false;
  1137. // Ignore input from stdin or any inputs that cannot be preprocessed.
  1138. // Check type first as not all linker inputs have a value.
  1139. if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
  1140. IgnoreInput = true;
  1141. } else if (!strcmp(it->second->getValue(), "-")) {
  1142. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1143. << "Error generating preprocessed source(s) - "
  1144. "ignoring input from stdin.";
  1145. IgnoreInput = true;
  1146. }
  1147. if (IgnoreInput) {
  1148. it = Inputs.erase(it);
  1149. ie = Inputs.end();
  1150. } else {
  1151. ++it;
  1152. }
  1153. }
  1154. if (Inputs.empty()) {
  1155. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1156. << "Error generating preprocessed source(s) - "
  1157. "no preprocessable inputs.";
  1158. return;
  1159. }
  1160. // Don't attempt to generate preprocessed files if multiple -arch options are
  1161. // used, unless they're all duplicates.
  1162. llvm::StringSet<> ArchNames;
  1163. for (const Arg *A : C.getArgs()) {
  1164. if (A->getOption().matches(options::OPT_arch)) {
  1165. StringRef ArchName = A->getValue();
  1166. ArchNames.insert(ArchName);
  1167. }
  1168. }
  1169. if (ArchNames.size() > 1) {
  1170. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1171. << "Error generating preprocessed source(s) - cannot generate "
  1172. "preprocessed source with multiple -arch options.";
  1173. return;
  1174. }
  1175. // Construct the list of abstract actions to perform for this compilation. On
  1176. // Darwin OSes this uses the driver-driver and builds universal actions.
  1177. const ToolChain &TC = C.getDefaultToolChain();
  1178. if (TC.getTriple().isOSBinFormatMachO())
  1179. BuildUniversalActions(C, TC, Inputs);
  1180. else
  1181. BuildActions(C, C.getArgs(), Inputs, C.getActions());
  1182. BuildJobs(C);
  1183. // If there were errors building the compilation, quit now.
  1184. if (Trap.hasErrorOccurred()) {
  1185. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1186. << "Error generating preprocessed source(s).";
  1187. return;
  1188. }
  1189. // Generate preprocessed output.
  1190. SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
  1191. C.ExecuteJobs(C.getJobs(), FailingCommands);
  1192. // If any of the preprocessing commands failed, clean up and exit.
  1193. if (!FailingCommands.empty()) {
  1194. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1195. << "Error generating preprocessed source(s).";
  1196. return;
  1197. }
  1198. const ArgStringList &TempFiles = C.getTempFiles();
  1199. if (TempFiles.empty()) {
  1200. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1201. << "Error generating preprocessed source(s).";
  1202. return;
  1203. }
  1204. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1205. << "\n********************\n\n"
  1206. "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
  1207. "Preprocessed source(s) and associated run script(s) are located at:";
  1208. SmallString<128> VFS;
  1209. SmallString<128> ReproCrashFilename;
  1210. for (const char *TempFile : TempFiles) {
  1211. Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
  1212. if (Report)
  1213. Report->TemporaryFiles.push_back(TempFile);
  1214. if (ReproCrashFilename.empty()) {
  1215. ReproCrashFilename = TempFile;
  1216. llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
  1217. }
  1218. if (StringRef(TempFile).endswith(".cache")) {
  1219. // In some cases (modules) we'll dump extra data to help with reproducing
  1220. // the crash into a directory next to the output.
  1221. VFS = llvm::sys::path::filename(TempFile);
  1222. llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
  1223. }
  1224. }
  1225. // Assume associated files are based off of the first temporary file.
  1226. CrashReportInfo CrashInfo(TempFiles[0], VFS);
  1227. llvm::SmallString<128> Script(CrashInfo.Filename);
  1228. llvm::sys::path::replace_extension(Script, "sh");
  1229. std::error_code EC;
  1230. llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
  1231. if (EC) {
  1232. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1233. << "Error generating run script: " << Script << " " << EC.message();
  1234. } else {
  1235. ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
  1236. << "# Driver args: ";
  1237. printArgList(ScriptOS, C.getInputArgs());
  1238. ScriptOS << "# Original command: ";
  1239. Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
  1240. Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
  1241. if (!AdditionalInformation.empty())
  1242. ScriptOS << "\n# Additional information: " << AdditionalInformation
  1243. << "\n";
  1244. if (Report)
  1245. Report->TemporaryFiles.push_back(Script.str());
  1246. Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
  1247. }
  1248. // On darwin, provide information about the .crash diagnostic report.
  1249. if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
  1250. SmallString<128> CrashDiagDir;
  1251. if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
  1252. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1253. << ReproCrashFilename.str();
  1254. } else { // Suggest a directory for the user to look for .crash files.
  1255. llvm::sys::path::append(CrashDiagDir, Name);
  1256. CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
  1257. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1258. << "Crash backtrace is located in";
  1259. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1260. << CrashDiagDir.str();
  1261. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1262. << "(choose the .crash file that corresponds to your crash)";
  1263. }
  1264. }
  1265. for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
  1266. options::OPT_frewrite_map_file_EQ))
  1267. Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
  1268. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1269. << "\n\n********************";
  1270. }
  1271. void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
  1272. // Since commandLineFitsWithinSystemLimits() may underestimate system's
  1273. // capacity if the tool does not support response files, there is a chance/
  1274. // that things will just work without a response file, so we silently just
  1275. // skip it.
  1276. if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
  1277. llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
  1278. Cmd.getArguments()))
  1279. return;
  1280. std::string TmpName = GetTemporaryPath("response", "txt");
  1281. Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
  1282. }
  1283. int Driver::ExecuteCompilation(
  1284. Compilation &C,
  1285. SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
  1286. // Just print if -### was present.
  1287. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
  1288. C.getJobs().Print(llvm::errs(), "\n", true);
  1289. return 0;
  1290. }
  1291. // If there were errors building the compilation, quit now.
  1292. if (Diags.hasErrorOccurred())
  1293. return 1;
  1294. // Set up response file names for each command, if necessary
  1295. for (auto &Job : C.getJobs())
  1296. setUpResponseFiles(C, Job);
  1297. C.ExecuteJobs(C.getJobs(), FailingCommands);
  1298. // If the command succeeded, we are done.
  1299. if (FailingCommands.empty())
  1300. return 0;
  1301. // Otherwise, remove result files and print extra information about abnormal
  1302. // failures.
  1303. int Res = 0;
  1304. for (const auto &CmdPair : FailingCommands) {
  1305. int CommandRes = CmdPair.first;
  1306. const Command *FailingCommand = CmdPair.second;
  1307. // Remove result files if we're not saving temps.
  1308. if (!isSaveTempsEnabled()) {
  1309. const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
  1310. C.CleanupFileMap(C.getResultFiles(), JA, true);
  1311. // Failure result files are valid unless we crashed.
  1312. if (CommandRes < 0)
  1313. C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
  1314. }
  1315. #if LLVM_ON_UNIX
  1316. // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
  1317. // for SIGPIPE. Do not print diagnostics for this case.
  1318. if (CommandRes == EX_IOERR) {
  1319. Res = CommandRes;
  1320. continue;
  1321. }
  1322. #endif
  1323. // Print extra information about abnormal failures, if possible.
  1324. //
  1325. // This is ad-hoc, but we don't want to be excessively noisy. If the result
  1326. // status was 1, assume the command failed normally. In particular, if it
  1327. // was the compiler then assume it gave a reasonable error code. Failures
  1328. // in other tools are less common, and they generally have worse
  1329. // diagnostics, so always print the diagnostic there.
  1330. const Tool &FailingTool = FailingCommand->getCreator();
  1331. if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
  1332. // FIXME: See FIXME above regarding result code interpretation.
  1333. if (CommandRes < 0)
  1334. Diag(clang::diag::err_drv_command_signalled)
  1335. << FailingTool.getShortName();
  1336. else
  1337. Diag(clang::diag::err_drv_command_failed)
  1338. << FailingTool.getShortName() << CommandRes;
  1339. }
  1340. }
  1341. return Res;
  1342. }
  1343. void Driver::PrintHelp(bool ShowHidden) const {
  1344. unsigned IncludedFlagsBitmask;
  1345. unsigned ExcludedFlagsBitmask;
  1346. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  1347. getIncludeExcludeOptionFlagMasks(IsCLMode());
  1348. ExcludedFlagsBitmask |= options::NoDriverOption;
  1349. if (!ShowHidden)
  1350. ExcludedFlagsBitmask |= HelpHidden;
  1351. std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
  1352. getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
  1353. IncludedFlagsBitmask, ExcludedFlagsBitmask,
  1354. /*ShowAllAliases=*/false);
  1355. }
  1356. void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
  1357. // FIXME: The following handlers should use a callback mechanism, we don't
  1358. // know what the client would like to do.
  1359. OS << getClangFullVersion() << '\n';
  1360. const ToolChain &TC = C.getDefaultToolChain();
  1361. OS << "Target: " << TC.getTripleString() << '\n';
  1362. // Print the threading model.
  1363. if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
  1364. // Don't print if the ToolChain would have barfed on it already
  1365. if (TC.isThreadModelSupported(A->getValue()))
  1366. OS << "Thread model: " << A->getValue();
  1367. } else
  1368. OS << "Thread model: " << TC.getThreadModel();
  1369. OS << '\n';
  1370. // Print out the install directory.
  1371. OS << "InstalledDir: " << InstalledDir << '\n';
  1372. // If configuration file was used, print its path.
  1373. if (!ConfigFile.empty())
  1374. OS << "Configuration file: " << ConfigFile << '\n';
  1375. }
  1376. /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
  1377. /// option.
  1378. static void PrintDiagnosticCategories(raw_ostream &OS) {
  1379. // Skip the empty category.
  1380. for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
  1381. ++i)
  1382. OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
  1383. }
  1384. void Driver::HandleAutocompletions(StringRef PassedFlags) const {
  1385. if (PassedFlags == "")
  1386. return;
  1387. // Print out all options that start with a given argument. This is used for
  1388. // shell autocompletion.
  1389. std::vector<std::string> SuggestedCompletions;
  1390. std::vector<std::string> Flags;
  1391. unsigned short DisableFlags =
  1392. options::NoDriverOption | options::Unsupported | options::Ignored;
  1393. // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
  1394. // because the latter indicates that the user put space before pushing tab
  1395. // which should end up in a file completion.
  1396. const bool HasSpace = PassedFlags.endswith(",");
  1397. // Parse PassedFlags by "," as all the command-line flags are passed to this
  1398. // function separated by ","
  1399. StringRef TargetFlags = PassedFlags;
  1400. while (TargetFlags != "") {
  1401. StringRef CurFlag;
  1402. std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
  1403. Flags.push_back(std::string(CurFlag));
  1404. }
  1405. // We want to show cc1-only options only when clang is invoked with -cc1 or
  1406. // -Xclang.
  1407. if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
  1408. DisableFlags &= ~options::NoDriverOption;
  1409. const llvm::opt::OptTable &Opts = getOpts();
  1410. StringRef Cur;
  1411. Cur = Flags.at(Flags.size() - 1);
  1412. StringRef Prev;
  1413. if (Flags.size() >= 2) {
  1414. Prev = Flags.at(Flags.size() - 2);
  1415. SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
  1416. }
  1417. if (SuggestedCompletions.empty())
  1418. SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
  1419. // If Flags were empty, it means the user typed `clang [tab]` where we should
  1420. // list all possible flags. If there was no value completion and the user
  1421. // pressed tab after a space, we should fall back to a file completion.
  1422. // We're printing a newline to be consistent with what we print at the end of
  1423. // this function.
  1424. if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
  1425. llvm::outs() << '\n';
  1426. return;
  1427. }
  1428. // When flag ends with '=' and there was no value completion, return empty
  1429. // string and fall back to the file autocompletion.
  1430. if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
  1431. // If the flag is in the form of "--autocomplete=-foo",
  1432. // we were requested to print out all option names that start with "-foo".
  1433. // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
  1434. SuggestedCompletions = Opts.findByPrefix(Cur, DisableFlags);
  1435. // We have to query the -W flags manually as they're not in the OptTable.
  1436. // TODO: Find a good way to add them to OptTable instead and them remove
  1437. // this code.
  1438. for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
  1439. if (S.startswith(Cur))
  1440. SuggestedCompletions.push_back(S);
  1441. }
  1442. // Sort the autocomplete candidates so that shells print them out in a
  1443. // deterministic order. We could sort in any way, but we chose
  1444. // case-insensitive sorting for consistency with the -help option
  1445. // which prints out options in the case-insensitive alphabetical order.
  1446. llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
  1447. if (int X = A.compare_lower(B))
  1448. return X < 0;
  1449. return A.compare(B) > 0;
  1450. });
  1451. llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
  1452. }
  1453. bool Driver::HandleImmediateArgs(const Compilation &C) {
  1454. // The order these options are handled in gcc is all over the place, but we
  1455. // don't expect inconsistencies w.r.t. that to matter in practice.
  1456. if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
  1457. llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
  1458. return false;
  1459. }
  1460. if (C.getArgs().hasArg(options::OPT_dumpversion)) {
  1461. // Since -dumpversion is only implemented for pedantic GCC compatibility, we
  1462. // return an answer which matches our definition of __VERSION__.
  1463. llvm::outs() << CLANG_VERSION_STRING << "\n";
  1464. return false;
  1465. }
  1466. if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
  1467. PrintDiagnosticCategories(llvm::outs());
  1468. return false;
  1469. }
  1470. if (C.getArgs().hasArg(options::OPT_help) ||
  1471. C.getArgs().hasArg(options::OPT__help_hidden)) {
  1472. PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
  1473. return false;
  1474. }
  1475. if (C.getArgs().hasArg(options::OPT__version)) {
  1476. // Follow gcc behavior and use stdout for --version and stderr for -v.
  1477. PrintVersion(C, llvm::outs());
  1478. return false;
  1479. }
  1480. if (C.getArgs().hasArg(options::OPT_v) ||
  1481. C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
  1482. C.getArgs().hasArg(options::OPT_print_supported_cpus)) {
  1483. PrintVersion(C, llvm::errs());
  1484. SuppressMissingInputWarning = true;
  1485. }
  1486. if (C.getArgs().hasArg(options::OPT_v)) {
  1487. if (!SystemConfigDir.empty())
  1488. llvm::errs() << "System configuration file directory: "
  1489. << SystemConfigDir << "\n";
  1490. if (!UserConfigDir.empty())
  1491. llvm::errs() << "User configuration file directory: "
  1492. << UserConfigDir << "\n";
  1493. }
  1494. const ToolChain &TC = C.getDefaultToolChain();
  1495. if (C.getArgs().hasArg(options::OPT_v))
  1496. TC.printVerboseInfo(llvm::errs());
  1497. if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
  1498. llvm::outs() << ResourceDir << '\n';
  1499. return false;
  1500. }
  1501. if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
  1502. llvm::outs() << "programs: =";
  1503. bool separator = false;
  1504. for (const std::string &Path : TC.getProgramPaths()) {
  1505. if (separator)
  1506. llvm::outs() << llvm::sys::EnvPathSeparator;
  1507. llvm::outs() << Path;
  1508. separator = true;
  1509. }
  1510. llvm::outs() << "\n";
  1511. llvm::outs() << "libraries: =" << ResourceDir;
  1512. StringRef sysroot = C.getSysRoot();
  1513. for (const std::string &Path : TC.getFilePaths()) {
  1514. // Always print a separator. ResourceDir was the first item shown.
  1515. llvm::outs() << llvm::sys::EnvPathSeparator;
  1516. // Interpretation of leading '=' is needed only for NetBSD.
  1517. if (Path[0] == '=')
  1518. llvm::outs() << sysroot << Path.substr(1);
  1519. else
  1520. llvm::outs() << Path;
  1521. }
  1522. llvm::outs() << "\n";
  1523. return false;
  1524. }
  1525. // FIXME: The following handlers should use a callback mechanism, we don't
  1526. // know what the client would like to do.
  1527. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
  1528. llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
  1529. return false;
  1530. }
  1531. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
  1532. StringRef ProgName = A->getValue();
  1533. // Null program name cannot have a path.
  1534. if (! ProgName.empty())
  1535. llvm::outs() << GetProgramPath(ProgName, TC);
  1536. llvm::outs() << "\n";
  1537. return false;
  1538. }
  1539. if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
  1540. StringRef PassedFlags = A->getValue();
  1541. HandleAutocompletions(PassedFlags);
  1542. return false;
  1543. }
  1544. if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
  1545. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
  1546. const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
  1547. RegisterEffectiveTriple TripleRAII(TC, Triple);
  1548. switch (RLT) {
  1549. case ToolChain::RLT_CompilerRT:
  1550. llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
  1551. break;
  1552. case ToolChain::RLT_Libgcc:
  1553. llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
  1554. break;
  1555. }
  1556. return false;
  1557. }
  1558. if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
  1559. for (const Multilib &Multilib : TC.getMultilibs())
  1560. llvm::outs() << Multilib << "\n";
  1561. return false;
  1562. }
  1563. if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
  1564. const Multilib &Multilib = TC.getMultilib();
  1565. if (Multilib.gccSuffix().empty())
  1566. llvm::outs() << ".\n";
  1567. else {
  1568. StringRef Suffix(Multilib.gccSuffix());
  1569. assert(Suffix.front() == '/');
  1570. llvm::outs() << Suffix.substr(1) << "\n";
  1571. }
  1572. return false;
  1573. }
  1574. if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
  1575. llvm::outs() << TC.getTripleString() << "\n";
  1576. return false;
  1577. }
  1578. if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
  1579. const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
  1580. llvm::outs() << Triple.getTriple() << "\n";
  1581. return false;
  1582. }
  1583. return true;
  1584. }
  1585. enum {
  1586. TopLevelAction = 0,
  1587. HeadSibAction = 1,
  1588. OtherSibAction = 2,
  1589. };
  1590. // Display an action graph human-readably. Action A is the "sink" node
  1591. // and latest-occuring action. Traversal is in pre-order, visiting the
  1592. // inputs to each action before printing the action itself.
  1593. static unsigned PrintActions1(const Compilation &C, Action *A,
  1594. std::map<Action *, unsigned> &Ids,
  1595. Twine Indent = {}, int Kind = TopLevelAction) {
  1596. if (Ids.count(A)) // A was already visited.
  1597. return Ids[A];
  1598. std::string str;
  1599. llvm::raw_string_ostream os(str);
  1600. auto getSibIndent = [](int K) -> Twine {
  1601. return (K == HeadSibAction) ? " " : (K == OtherSibAction) ? "| " : "";
  1602. };
  1603. Twine SibIndent = Indent + getSibIndent(Kind);
  1604. int SibKind = HeadSibAction;
  1605. os << Action::getClassName(A->getKind()) << ", ";
  1606. if (InputAction *IA = dyn_cast<InputAction>(A)) {
  1607. os << "\"" << IA->getInputArg().getValue() << "\"";
  1608. } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
  1609. os << '"' << BIA->getArchName() << '"' << ", {"
  1610. << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
  1611. } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
  1612. bool IsFirst = true;
  1613. OA->doOnEachDependence(
  1614. [&](Action *A, const ToolChain *TC, const char *BoundArch) {
  1615. // E.g. for two CUDA device dependences whose bound arch is sm_20 and
  1616. // sm_35 this will generate:
  1617. // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
  1618. // (nvptx64-nvidia-cuda:sm_35) {#ID}
  1619. if (!IsFirst)
  1620. os << ", ";
  1621. os << '"';
  1622. if (TC)
  1623. os << A->getOffloadingKindPrefix();
  1624. else
  1625. os << "host";
  1626. os << " (";
  1627. os << TC->getTriple().normalize();
  1628. if (BoundArch)
  1629. os << ":" << BoundArch;
  1630. os << ")";
  1631. os << '"';
  1632. os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
  1633. IsFirst = false;
  1634. SibKind = OtherSibAction;
  1635. });
  1636. } else {
  1637. const ActionList *AL = &A->getInputs();
  1638. if (AL->size()) {
  1639. const char *Prefix = "{";
  1640. for (Action *PreRequisite : *AL) {
  1641. os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
  1642. Prefix = ", ";
  1643. SibKind = OtherSibAction;
  1644. }
  1645. os << "}";
  1646. } else
  1647. os << "{}";
  1648. }
  1649. // Append offload info for all options other than the offloading action
  1650. // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
  1651. std::string offload_str;
  1652. llvm::raw_string_ostream offload_os(offload_str);
  1653. if (!isa<OffloadAction>(A)) {
  1654. auto S = A->getOffloadingKindPrefix();
  1655. if (!S.empty()) {
  1656. offload_os << ", (" << S;
  1657. if (A->getOffloadingArch())
  1658. offload_os << ", " << A->getOffloadingArch();
  1659. offload_os << ")";
  1660. }
  1661. }
  1662. auto getSelfIndent = [](int K) -> Twine {
  1663. return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
  1664. };
  1665. unsigned Id = Ids.size();
  1666. Ids[A] = Id;
  1667. llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
  1668. << types::getTypeName(A->getType()) << offload_os.str() << "\n";
  1669. return Id;
  1670. }
  1671. // Print the action graphs in a compilation C.
  1672. // For example "clang -c file1.c file2.c" is composed of two subgraphs.
  1673. void Driver::PrintActions(const Compilation &C) const {
  1674. std::map<Action *, unsigned> Ids;
  1675. for (Action *A : C.getActions())
  1676. PrintActions1(C, A, Ids);
  1677. }
  1678. /// Check whether the given input tree contains any compilation or
  1679. /// assembly actions.
  1680. static bool ContainsCompileOrAssembleAction(const Action *A) {
  1681. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
  1682. isa<AssembleJobAction>(A))
  1683. return true;
  1684. for (const Action *Input : A->inputs())
  1685. if (ContainsCompileOrAssembleAction(Input))
  1686. return true;
  1687. return false;
  1688. }
  1689. void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
  1690. const InputList &BAInputs) const {
  1691. DerivedArgList &Args = C.getArgs();
  1692. ActionList &Actions = C.getActions();
  1693. llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
  1694. // Collect the list of architectures. Duplicates are allowed, but should only
  1695. // be handled once (in the order seen).
  1696. llvm::StringSet<> ArchNames;
  1697. SmallVector<const char *, 4> Archs;
  1698. for (Arg *A : Args) {
  1699. if (A->getOption().matches(options::OPT_arch)) {
  1700. // Validate the option here; we don't save the type here because its
  1701. // particular spelling may participate in other driver choices.
  1702. llvm::Triple::ArchType Arch =
  1703. tools::darwin::getArchTypeForMachOArchName(A->getValue());
  1704. if (Arch == llvm::Triple::UnknownArch) {
  1705. Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
  1706. continue;
  1707. }
  1708. A->claim();
  1709. if (ArchNames.insert(A->getValue()).second)
  1710. Archs.push_back(A->getValue());
  1711. }
  1712. }
  1713. // When there is no explicit arch for this platform, make sure we still bind
  1714. // the architecture (to the default) so that -Xarch_ is handled correctly.
  1715. if (!Archs.size())
  1716. Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
  1717. ActionList SingleActions;
  1718. BuildActions(C, Args, BAInputs, SingleActions);
  1719. // Add in arch bindings for every top level action, as well as lipo and
  1720. // dsymutil steps if needed.
  1721. for (Action* Act : SingleActions) {
  1722. // Make sure we can lipo this kind of output. If not (and it is an actual
  1723. // output) then we disallow, since we can't create an output file with the
  1724. // right name without overwriting it. We could remove this oddity by just
  1725. // changing the output names to include the arch, which would also fix
  1726. // -save-temps. Compatibility wins for now.
  1727. if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
  1728. Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
  1729. << types::getTypeName(Act->getType());
  1730. ActionList Inputs;
  1731. for (unsigned i = 0, e = Archs.size(); i != e; ++i)
  1732. Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
  1733. // Lipo if necessary, we do it this way because we need to set the arch flag
  1734. // so that -Xarch_ gets overwritten.
  1735. if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
  1736. Actions.append(Inputs.begin(), Inputs.end());
  1737. else
  1738. Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
  1739. // Handle debug info queries.
  1740. Arg *A = Args.getLastArg(options::OPT_g_Group);
  1741. if (A && !A->getOption().matches(options::OPT_g0) &&
  1742. !A->getOption().matches(options::OPT_gstabs) &&
  1743. ContainsCompileOrAssembleAction(Actions.back())) {
  1744. // Add a 'dsymutil' step if necessary, when debug info is enabled and we
  1745. // have a compile input. We need to run 'dsymutil' ourselves in such cases
  1746. // because the debug info will refer to a temporary object file which
  1747. // will be removed at the end of the compilation process.
  1748. if (Act->getType() == types::TY_Image) {
  1749. ActionList Inputs;
  1750. Inputs.push_back(Actions.back());
  1751. Actions.pop_back();
  1752. Actions.push_back(
  1753. C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
  1754. }
  1755. // Verify the debug info output.
  1756. if (Args.hasArg(options::OPT_verify_debug_info)) {
  1757. Action* LastAction = Actions.back();
  1758. Actions.pop_back();
  1759. Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
  1760. LastAction, types::TY_Nothing));
  1761. }
  1762. }
  1763. }
  1764. }
  1765. bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
  1766. types::ID Ty, bool TypoCorrect) const {
  1767. if (!getCheckInputsExist())
  1768. return true;
  1769. // stdin always exists.
  1770. if (Value == "-")
  1771. return true;
  1772. if (getVFS().exists(Value))
  1773. return true;
  1774. if (IsCLMode()) {
  1775. if (!llvm::sys::path::is_absolute(Twine(Value)) &&
  1776. llvm::sys::Process::FindInEnvPath("LIB", Value))
  1777. return true;
  1778. if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
  1779. // Arguments to the /link flag might cause the linker to search for object
  1780. // and library files in paths we don't know about. Don't error in such
  1781. // cases.
  1782. return true;
  1783. }
  1784. }
  1785. if (TypoCorrect) {
  1786. // Check if the filename is a typo for an option flag. OptTable thinks
  1787. // that all args that are not known options and that start with / are
  1788. // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
  1789. // the option `/diagnostics:caret` than a reference to a file in the root
  1790. // directory.
  1791. unsigned IncludedFlagsBitmask;
  1792. unsigned ExcludedFlagsBitmask;
  1793. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  1794. getIncludeExcludeOptionFlagMasks(IsCLMode());
  1795. std::string Nearest;
  1796. if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
  1797. ExcludedFlagsBitmask) <= 1) {
  1798. Diag(clang::diag::err_drv_no_such_file_with_suggestion)
  1799. << Value << Nearest;
  1800. return false;
  1801. }
  1802. }
  1803. Diag(clang::diag::err_drv_no_such_file) << Value;
  1804. return false;
  1805. }
  1806. // Construct a the list of inputs and their types.
  1807. void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
  1808. InputList &Inputs) const {
  1809. const llvm::opt::OptTable &Opts = getOpts();
  1810. // Track the current user specified (-x) input. We also explicitly track the
  1811. // argument used to set the type; we only want to claim the type when we
  1812. // actually use it, so we warn about unused -x arguments.
  1813. types::ID InputType = types::TY_Nothing;
  1814. Arg *InputTypeArg = nullptr;
  1815. // The last /TC or /TP option sets the input type to C or C++ globally.
  1816. if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
  1817. options::OPT__SLASH_TP)) {
  1818. InputTypeArg = TCTP;
  1819. InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
  1820. ? types::TY_C
  1821. : types::TY_CXX;
  1822. Arg *Previous = nullptr;
  1823. bool ShowNote = false;
  1824. for (Arg *A :
  1825. Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
  1826. if (Previous) {
  1827. Diag(clang::diag::warn_drv_overriding_flag_option)
  1828. << Previous->getSpelling() << A->getSpelling();
  1829. ShowNote = true;
  1830. }
  1831. Previous = A;
  1832. }
  1833. if (ShowNote)
  1834. Diag(clang::diag::note_drv_t_option_is_global);
  1835. // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
  1836. assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
  1837. }
  1838. for (Arg *A : Args) {
  1839. if (A->getOption().getKind() == Option::InputClass) {
  1840. const char *Value = A->getValue();
  1841. types::ID Ty = types::TY_INVALID;
  1842. // Infer the input type if necessary.
  1843. if (InputType == types::TY_Nothing) {
  1844. // If there was an explicit arg for this, claim it.
  1845. if (InputTypeArg)
  1846. InputTypeArg->claim();
  1847. // stdin must be handled specially.
  1848. if (memcmp(Value, "-", 2) == 0) {
  1849. // If running with -E, treat as a C input (this changes the builtin
  1850. // macros, for example). This may be overridden by -ObjC below.
  1851. //
  1852. // Otherwise emit an error but still use a valid type to avoid
  1853. // spurious errors (e.g., no inputs).
  1854. if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
  1855. Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
  1856. : clang::diag::err_drv_unknown_stdin_type);
  1857. Ty = types::TY_C;
  1858. } else {
  1859. // Otherwise lookup by extension.
  1860. // Fallback is C if invoked as C preprocessor, C++ if invoked with
  1861. // clang-cl /E, or Object otherwise.
  1862. // We use a host hook here because Darwin at least has its own
  1863. // idea of what .s is.
  1864. if (const char *Ext = strrchr(Value, '.'))
  1865. Ty = TC.LookupTypeForExtension(Ext + 1);
  1866. if (Ty == types::TY_INVALID) {
  1867. if (CCCIsCPP())
  1868. Ty = types::TY_C;
  1869. else if (IsCLMode() && Args.hasArgNoClaim(options::OPT_E))
  1870. Ty = types::TY_CXX;
  1871. else
  1872. Ty = types::TY_Object;
  1873. }
  1874. // If the driver is invoked as C++ compiler (like clang++ or c++) it
  1875. // should autodetect some input files as C++ for g++ compatibility.
  1876. if (CCCIsCXX()) {
  1877. types::ID OldTy = Ty;
  1878. Ty = types::lookupCXXTypeForCType(Ty);
  1879. if (Ty != OldTy)
  1880. Diag(clang::diag::warn_drv_treating_input_as_cxx)
  1881. << getTypeName(OldTy) << getTypeName(Ty);
  1882. }
  1883. // If running with -fthinlto-index=, extensions that normally identify
  1884. // native object files actually identify LLVM bitcode files.
  1885. if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
  1886. Ty == types::TY_Object)
  1887. Ty = types::TY_LLVM_BC;
  1888. }
  1889. // -ObjC and -ObjC++ override the default language, but only for "source
  1890. // files". We just treat everything that isn't a linker input as a
  1891. // source file.
  1892. //
  1893. // FIXME: Clean this up if we move the phase sequence into the type.
  1894. if (Ty != types::TY_Object) {
  1895. if (Args.hasArg(options::OPT_ObjC))
  1896. Ty = types::TY_ObjC;
  1897. else if (Args.hasArg(options::OPT_ObjCXX))
  1898. Ty = types::TY_ObjCXX;
  1899. }
  1900. } else {
  1901. assert(InputTypeArg && "InputType set w/o InputTypeArg");
  1902. if (!InputTypeArg->getOption().matches(options::OPT_x)) {
  1903. // If emulating cl.exe, make sure that /TC and /TP don't affect input
  1904. // object files.
  1905. const char *Ext = strrchr(Value, '.');
  1906. if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
  1907. Ty = types::TY_Object;
  1908. }
  1909. if (Ty == types::TY_INVALID) {
  1910. Ty = InputType;
  1911. InputTypeArg->claim();
  1912. }
  1913. }
  1914. if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
  1915. Inputs.push_back(std::make_pair(Ty, A));
  1916. } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
  1917. StringRef Value = A->getValue();
  1918. if (DiagnoseInputExistence(Args, Value, types::TY_C,
  1919. /*TypoCorrect=*/false)) {
  1920. Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
  1921. Inputs.push_back(std::make_pair(types::TY_C, InputArg));
  1922. }
  1923. A->claim();
  1924. } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
  1925. StringRef Value = A->getValue();
  1926. if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
  1927. /*TypoCorrect=*/false)) {
  1928. Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
  1929. Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
  1930. }
  1931. A->claim();
  1932. } else if (A->getOption().hasFlag(options::LinkerInput)) {
  1933. // Just treat as object type, we could make a special type for this if
  1934. // necessary.
  1935. Inputs.push_back(std::make_pair(types::TY_Object, A));
  1936. } else if (A->getOption().matches(options::OPT_x)) {
  1937. InputTypeArg = A;
  1938. InputType = types::lookupTypeForTypeSpecifier(A->getValue());
  1939. A->claim();
  1940. // Follow gcc behavior and treat as linker input for invalid -x
  1941. // options. Its not clear why we shouldn't just revert to unknown; but
  1942. // this isn't very important, we might as well be bug compatible.
  1943. if (!InputType) {
  1944. Diag(clang::diag::err_drv_unknown_language) << A->getValue();
  1945. InputType = types::TY_Object;
  1946. }
  1947. } else if (A->getOption().getID() == options::OPT_U) {
  1948. assert(A->getNumValues() == 1 && "The /U option has one value.");
  1949. StringRef Val = A->getValue(0);
  1950. if (Val.find_first_of("/\\") != StringRef::npos) {
  1951. // Warn about e.g. "/Users/me/myfile.c".
  1952. Diag(diag::warn_slash_u_filename) << Val;
  1953. Diag(diag::note_use_dashdash);
  1954. }
  1955. }
  1956. }
  1957. if (CCCIsCPP() && Inputs.empty()) {
  1958. // If called as standalone preprocessor, stdin is processed
  1959. // if no other input is present.
  1960. Arg *A = MakeInputArg(Args, Opts, "-");
  1961. Inputs.push_back(std::make_pair(types::TY_C, A));
  1962. }
  1963. }
  1964. namespace {
  1965. /// Provides a convenient interface for different programming models to generate
  1966. /// the required device actions.
  1967. class OffloadingActionBuilder final {
  1968. /// Flag used to trace errors in the builder.
  1969. bool IsValid = false;
  1970. /// The compilation that is using this builder.
  1971. Compilation &C;
  1972. /// Map between an input argument and the offload kinds used to process it.
  1973. std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
  1974. /// Builder interface. It doesn't build anything or keep any state.
  1975. class DeviceActionBuilder {
  1976. public:
  1977. typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
  1978. enum ActionBuilderReturnCode {
  1979. // The builder acted successfully on the current action.
  1980. ABRT_Success,
  1981. // The builder didn't have to act on the current action.
  1982. ABRT_Inactive,
  1983. // The builder was successful and requested the host action to not be
  1984. // generated.
  1985. ABRT_Ignore_Host,
  1986. };
  1987. protected:
  1988. /// Compilation associated with this builder.
  1989. Compilation &C;
  1990. /// Tool chains associated with this builder. The same programming
  1991. /// model may have associated one or more tool chains.
  1992. SmallVector<const ToolChain *, 2> ToolChains;
  1993. /// The derived arguments associated with this builder.
  1994. DerivedArgList &Args;
  1995. /// The inputs associated with this builder.
  1996. const Driver::InputList &Inputs;
  1997. /// The associated offload kind.
  1998. Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
  1999. public:
  2000. DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
  2001. const Driver::InputList &Inputs,
  2002. Action::OffloadKind AssociatedOffloadKind)
  2003. : C(C), Args(Args), Inputs(Inputs),
  2004. AssociatedOffloadKind(AssociatedOffloadKind) {}
  2005. virtual ~DeviceActionBuilder() {}
  2006. /// Fill up the array \a DA with all the device dependences that should be
  2007. /// added to the provided host action \a HostAction. By default it is
  2008. /// inactive.
  2009. virtual ActionBuilderReturnCode
  2010. getDeviceDependences(OffloadAction::DeviceDependences &DA,
  2011. phases::ID CurPhase, phases::ID FinalPhase,
  2012. PhasesTy &Phases) {
  2013. return ABRT_Inactive;
  2014. }
  2015. /// Update the state to include the provided host action \a HostAction as a
  2016. /// dependency of the current device action. By default it is inactive.
  2017. virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
  2018. return ABRT_Inactive;
  2019. }
  2020. /// Append top level actions generated by the builder.
  2021. virtual void appendTopLevelActions(ActionList &AL) {}
  2022. /// Append linker actions generated by the builder.
  2023. virtual void appendLinkActions(ActionList &AL) {}
  2024. /// Append linker actions generated by the builder.
  2025. virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
  2026. /// Initialize the builder. Return true if any initialization errors are
  2027. /// found.
  2028. virtual bool initialize() { return false; }
  2029. /// Return true if the builder can use bundling/unbundling.
  2030. virtual bool canUseBundlerUnbundler() const { return false; }
  2031. /// Return true if this builder is valid. We have a valid builder if we have
  2032. /// associated device tool chains.
  2033. bool isValid() { return !ToolChains.empty(); }
  2034. /// Return the associated offload kind.
  2035. Action::OffloadKind getAssociatedOffloadKind() {
  2036. return AssociatedOffloadKind;
  2037. }
  2038. };
  2039. /// Base class for CUDA/HIP action builder. It injects device code in
  2040. /// the host backend action.
  2041. class CudaActionBuilderBase : public DeviceActionBuilder {
  2042. protected:
  2043. /// Flags to signal if the user requested host-only or device-only
  2044. /// compilation.
  2045. bool CompileHostOnly = false;
  2046. bool CompileDeviceOnly = false;
  2047. bool EmitLLVM = false;
  2048. bool EmitAsm = false;
  2049. /// List of GPU architectures to use in this compilation.
  2050. SmallVector<CudaArch, 4> GpuArchList;
  2051. /// The CUDA actions for the current input.
  2052. ActionList CudaDeviceActions;
  2053. /// The CUDA fat binary if it was generated for the current input.
  2054. Action *CudaFatBinary = nullptr;
  2055. /// Flag that is set to true if this builder acted on the current input.
  2056. bool IsActive = false;
  2057. /// Flag for -fgpu-rdc.
  2058. bool Relocatable = false;
  2059. /// Default GPU architecture if there's no one specified.
  2060. CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
  2061. public:
  2062. CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
  2063. const Driver::InputList &Inputs,
  2064. Action::OffloadKind OFKind)
  2065. : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
  2066. ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
  2067. // While generating code for CUDA, we only depend on the host input action
  2068. // to trigger the creation of all the CUDA device actions.
  2069. // If we are dealing with an input action, replicate it for each GPU
  2070. // architecture. If we are in host-only mode we return 'success' so that
  2071. // the host uses the CUDA offload kind.
  2072. if (auto *IA = dyn_cast<InputAction>(HostAction)) {
  2073. assert(!GpuArchList.empty() &&
  2074. "We should have at least one GPU architecture.");
  2075. // If the host input is not CUDA or HIP, we don't need to bother about
  2076. // this input.
  2077. if (IA->getType() != types::TY_CUDA &&
  2078. IA->getType() != types::TY_HIP) {
  2079. // The builder will ignore this input.
  2080. IsActive = false;
  2081. return ABRT_Inactive;
  2082. }
  2083. // Set the flag to true, so that the builder acts on the current input.
  2084. IsActive = true;
  2085. if (CompileHostOnly)
  2086. return ABRT_Success;
  2087. // Replicate inputs for each GPU architecture.
  2088. auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
  2089. : types::TY_CUDA_DEVICE;
  2090. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
  2091. CudaDeviceActions.push_back(
  2092. C.MakeAction<InputAction>(IA->getInputArg(), Ty));
  2093. }
  2094. return ABRT_Success;
  2095. }
  2096. // If this is an unbundling action use it as is for each CUDA toolchain.
  2097. if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
  2098. // If -fgpu-rdc is disabled, should not unbundle since there is no
  2099. // device code to link.
  2100. if (!Relocatable)
  2101. return ABRT_Inactive;
  2102. CudaDeviceActions.clear();
  2103. auto *IA = cast<InputAction>(UA->getInputs().back());
  2104. std::string FileName = IA->getInputArg().getAsString(Args);
  2105. // Check if the type of the file is the same as the action. Do not
  2106. // unbundle it if it is not. Do not unbundle .so files, for example,
  2107. // which are not object files.
  2108. if (IA->getType() == types::TY_Object &&
  2109. (!llvm::sys::path::has_extension(FileName) ||
  2110. types::lookupTypeForExtension(
  2111. llvm::sys::path::extension(FileName).drop_front()) !=
  2112. types::TY_Object))
  2113. return ABRT_Inactive;
  2114. for (auto Arch : GpuArchList) {
  2115. CudaDeviceActions.push_back(UA);
  2116. UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
  2117. AssociatedOffloadKind);
  2118. }
  2119. return ABRT_Success;
  2120. }
  2121. return IsActive ? ABRT_Success : ABRT_Inactive;
  2122. }
  2123. void appendTopLevelActions(ActionList &AL) override {
  2124. // Utility to append actions to the top level list.
  2125. auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
  2126. OffloadAction::DeviceDependences Dep;
  2127. Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
  2128. AssociatedOffloadKind);
  2129. AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
  2130. };
  2131. // If we have a fat binary, add it to the list.
  2132. if (CudaFatBinary) {
  2133. AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
  2134. CudaDeviceActions.clear();
  2135. CudaFatBinary = nullptr;
  2136. return;
  2137. }
  2138. if (CudaDeviceActions.empty())
  2139. return;
  2140. // If we have CUDA actions at this point, that's because we have a have
  2141. // partial compilation, so we should have an action for each GPU
  2142. // architecture.
  2143. assert(CudaDeviceActions.size() == GpuArchList.size() &&
  2144. "Expecting one action per GPU architecture.");
  2145. assert(ToolChains.size() == 1 &&
  2146. "Expecting to have a sing CUDA toolchain.");
  2147. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
  2148. AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
  2149. CudaDeviceActions.clear();
  2150. }
  2151. bool initialize() override {
  2152. assert(AssociatedOffloadKind == Action::OFK_Cuda ||
  2153. AssociatedOffloadKind == Action::OFK_HIP);
  2154. // We don't need to support CUDA.
  2155. if (AssociatedOffloadKind == Action::OFK_Cuda &&
  2156. !C.hasOffloadToolChain<Action::OFK_Cuda>())
  2157. return false;
  2158. // We don't need to support HIP.
  2159. if (AssociatedOffloadKind == Action::OFK_HIP &&
  2160. !C.hasOffloadToolChain<Action::OFK_HIP>())
  2161. return false;
  2162. Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
  2163. options::OPT_fno_gpu_rdc, /*Default=*/false);
  2164. const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
  2165. assert(HostTC && "No toolchain for host compilation.");
  2166. if (HostTC->getTriple().isNVPTX() ||
  2167. HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
  2168. // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
  2169. // an error and abort pipeline construction early so we don't trip
  2170. // asserts that assume device-side compilation.
  2171. C.getDriver().Diag(diag::err_drv_cuda_host_arch)
  2172. << HostTC->getTriple().getArchName();
  2173. return true;
  2174. }
  2175. ToolChains.push_back(
  2176. AssociatedOffloadKind == Action::OFK_Cuda
  2177. ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
  2178. : C.getSingleOffloadToolChain<Action::OFK_HIP>());
  2179. Arg *PartialCompilationArg = Args.getLastArg(
  2180. options::OPT_cuda_host_only, options::OPT_cuda_device_only,
  2181. options::OPT_cuda_compile_host_device);
  2182. CompileHostOnly = PartialCompilationArg &&
  2183. PartialCompilationArg->getOption().matches(
  2184. options::OPT_cuda_host_only);
  2185. CompileDeviceOnly = PartialCompilationArg &&
  2186. PartialCompilationArg->getOption().matches(
  2187. options::OPT_cuda_device_only);
  2188. EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
  2189. EmitAsm = Args.getLastArg(options::OPT_S);
  2190. // Collect all cuda_gpu_arch parameters, removing duplicates.
  2191. std::set<CudaArch> GpuArchs;
  2192. bool Error = false;
  2193. for (Arg *A : Args) {
  2194. if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
  2195. A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
  2196. continue;
  2197. A->claim();
  2198. const StringRef ArchStr = A->getValue();
  2199. if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
  2200. ArchStr == "all") {
  2201. GpuArchs.clear();
  2202. continue;
  2203. }
  2204. CudaArch Arch = StringToCudaArch(ArchStr);
  2205. if (Arch == CudaArch::UNKNOWN) {
  2206. C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
  2207. Error = true;
  2208. } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
  2209. GpuArchs.insert(Arch);
  2210. else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
  2211. GpuArchs.erase(Arch);
  2212. else
  2213. llvm_unreachable("Unexpected option.");
  2214. }
  2215. // Collect list of GPUs remaining in the set.
  2216. for (CudaArch Arch : GpuArchs)
  2217. GpuArchList.push_back(Arch);
  2218. // Default to sm_20 which is the lowest common denominator for
  2219. // supported GPUs. sm_20 code should work correctly, if
  2220. // suboptimally, on all newer GPUs.
  2221. if (GpuArchList.empty())
  2222. GpuArchList.push_back(DefaultCudaArch);
  2223. return Error;
  2224. }
  2225. };
  2226. /// \brief CUDA action builder. It injects device code in the host backend
  2227. /// action.
  2228. class CudaActionBuilder final : public CudaActionBuilderBase {
  2229. public:
  2230. CudaActionBuilder(Compilation &C, DerivedArgList &Args,
  2231. const Driver::InputList &Inputs)
  2232. : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
  2233. DefaultCudaArch = CudaArch::SM_20;
  2234. }
  2235. ActionBuilderReturnCode
  2236. getDeviceDependences(OffloadAction::DeviceDependences &DA,
  2237. phases::ID CurPhase, phases::ID FinalPhase,
  2238. PhasesTy &Phases) override {
  2239. if (!IsActive)
  2240. return ABRT_Inactive;
  2241. // If we don't have more CUDA actions, we don't have any dependences to
  2242. // create for the host.
  2243. if (CudaDeviceActions.empty())
  2244. return ABRT_Success;
  2245. assert(CudaDeviceActions.size() == GpuArchList.size() &&
  2246. "Expecting one action per GPU architecture.");
  2247. assert(!CompileHostOnly &&
  2248. "Not expecting CUDA actions in host-only compilation.");
  2249. // If we are generating code for the device or we are in a backend phase,
  2250. // we attempt to generate the fat binary. We compile each arch to ptx and
  2251. // assemble to cubin, then feed the cubin *and* the ptx into a device
  2252. // "link" action, which uses fatbinary to combine these cubins into one
  2253. // fatbin. The fatbin is then an input to the host action if not in
  2254. // device-only mode.
  2255. if (CompileDeviceOnly || CurPhase == phases::Backend) {
  2256. ActionList DeviceActions;
  2257. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
  2258. // Produce the device action from the current phase up to the assemble
  2259. // phase.
  2260. for (auto Ph : Phases) {
  2261. // Skip the phases that were already dealt with.
  2262. if (Ph < CurPhase)
  2263. continue;
  2264. // We have to be consistent with the host final phase.
  2265. if (Ph > FinalPhase)
  2266. break;
  2267. CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
  2268. C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
  2269. if (Ph == phases::Assemble)
  2270. break;
  2271. }
  2272. // If we didn't reach the assemble phase, we can't generate the fat
  2273. // binary. We don't need to generate the fat binary if we are not in
  2274. // device-only mode.
  2275. if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
  2276. CompileDeviceOnly)
  2277. continue;
  2278. Action *AssembleAction = CudaDeviceActions[I];
  2279. assert(AssembleAction->getType() == types::TY_Object);
  2280. assert(AssembleAction->getInputs().size() == 1);
  2281. Action *BackendAction = AssembleAction->getInputs()[0];
  2282. assert(BackendAction->getType() == types::TY_PP_Asm);
  2283. for (auto &A : {AssembleAction, BackendAction}) {
  2284. OffloadAction::DeviceDependences DDep;
  2285. DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
  2286. Action::OFK_Cuda);
  2287. DeviceActions.push_back(
  2288. C.MakeAction<OffloadAction>(DDep, A->getType()));
  2289. }
  2290. }
  2291. // We generate the fat binary if we have device input actions.
  2292. if (!DeviceActions.empty()) {
  2293. CudaFatBinary =
  2294. C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
  2295. if (!CompileDeviceOnly) {
  2296. DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
  2297. Action::OFK_Cuda);
  2298. // Clear the fat binary, it is already a dependence to an host
  2299. // action.
  2300. CudaFatBinary = nullptr;
  2301. }
  2302. // Remove the CUDA actions as they are already connected to an host
  2303. // action or fat binary.
  2304. CudaDeviceActions.clear();
  2305. }
  2306. // We avoid creating host action in device-only mode.
  2307. return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
  2308. } else if (CurPhase > phases::Backend) {
  2309. // If we are past the backend phase and still have a device action, we
  2310. // don't have to do anything as this action is already a device
  2311. // top-level action.
  2312. return ABRT_Success;
  2313. }
  2314. assert(CurPhase < phases::Backend && "Generating single CUDA "
  2315. "instructions should only occur "
  2316. "before the backend phase!");
  2317. // By default, we produce an action for each device arch.
  2318. for (Action *&A : CudaDeviceActions)
  2319. A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
  2320. return ABRT_Success;
  2321. }
  2322. };
  2323. /// \brief HIP action builder. It injects device code in the host backend
  2324. /// action.
  2325. class HIPActionBuilder final : public CudaActionBuilderBase {
  2326. /// The linker inputs obtained for each device arch.
  2327. SmallVector<ActionList, 8> DeviceLinkerInputs;
  2328. public:
  2329. HIPActionBuilder(Compilation &C, DerivedArgList &Args,
  2330. const Driver::InputList &Inputs)
  2331. : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
  2332. DefaultCudaArch = CudaArch::GFX803;
  2333. }
  2334. bool canUseBundlerUnbundler() const override { return true; }
  2335. ActionBuilderReturnCode
  2336. getDeviceDependences(OffloadAction::DeviceDependences &DA,
  2337. phases::ID CurPhase, phases::ID FinalPhase,
  2338. PhasesTy &Phases) override {
  2339. // amdgcn does not support linking of object files, therefore we skip
  2340. // backend and assemble phases to output LLVM IR. Except for generating
  2341. // non-relocatable device coee, where we generate fat binary for device
  2342. // code and pass to host in Backend phase.
  2343. if (CudaDeviceActions.empty() ||
  2344. (CurPhase == phases::Backend && Relocatable) ||
  2345. CurPhase == phases::Assemble)
  2346. return ABRT_Success;
  2347. assert(((CurPhase == phases::Link && Relocatable) ||
  2348. CudaDeviceActions.size() == GpuArchList.size()) &&
  2349. "Expecting one action per GPU architecture.");
  2350. assert(!CompileHostOnly &&
  2351. "Not expecting CUDA actions in host-only compilation.");
  2352. if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
  2353. !EmitAsm) {
  2354. // If we are in backend phase, we attempt to generate the fat binary.
  2355. // We compile each arch to IR and use a link action to generate code
  2356. // object containing ISA. Then we use a special "link" action to create
  2357. // a fat binary containing all the code objects for different GPU's.
  2358. // The fat binary is then an input to the host action.
  2359. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
  2360. // Create a link action to link device IR with device library
  2361. // and generate ISA.
  2362. ActionList AL;
  2363. AL.push_back(CudaDeviceActions[I]);
  2364. CudaDeviceActions[I] =
  2365. C.MakeAction<LinkJobAction>(AL, types::TY_Image);
  2366. // OffloadingActionBuilder propagates device arch until an offload
  2367. // action. Since the next action for creating fatbin does
  2368. // not have device arch, whereas the above link action and its input
  2369. // have device arch, an offload action is needed to stop the null
  2370. // device arch of the next action being propagated to the above link
  2371. // action.
  2372. OffloadAction::DeviceDependences DDep;
  2373. DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
  2374. CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
  2375. CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
  2376. DDep, CudaDeviceActions[I]->getType());
  2377. }
  2378. // Create HIP fat binary with a special "link" action.
  2379. CudaFatBinary =
  2380. C.MakeAction<LinkJobAction>(CudaDeviceActions,
  2381. types::TY_HIP_FATBIN);
  2382. if (!CompileDeviceOnly) {
  2383. DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
  2384. AssociatedOffloadKind);
  2385. // Clear the fat binary, it is already a dependence to an host
  2386. // action.
  2387. CudaFatBinary = nullptr;
  2388. }
  2389. // Remove the CUDA actions as they are already connected to an host
  2390. // action or fat binary.
  2391. CudaDeviceActions.clear();
  2392. return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
  2393. } else if (CurPhase == phases::Link) {
  2394. // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
  2395. // This happens to each device action originated from each input file.
  2396. // Later on, device actions in DeviceLinkerInputs are used to create
  2397. // device link actions in appendLinkDependences and the created device
  2398. // link actions are passed to the offload action as device dependence.
  2399. DeviceLinkerInputs.resize(CudaDeviceActions.size());
  2400. auto LI = DeviceLinkerInputs.begin();
  2401. for (auto *A : CudaDeviceActions) {
  2402. LI->push_back(A);
  2403. ++LI;
  2404. }
  2405. // We will pass the device action as a host dependence, so we don't
  2406. // need to do anything else with them.
  2407. CudaDeviceActions.clear();
  2408. return ABRT_Success;
  2409. }
  2410. // By default, we produce an action for each device arch.
  2411. for (Action *&A : CudaDeviceActions)
  2412. A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
  2413. AssociatedOffloadKind);
  2414. return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host
  2415. : ABRT_Success;
  2416. }
  2417. void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
  2418. // Append a new link action for each device.
  2419. unsigned I = 0;
  2420. for (auto &LI : DeviceLinkerInputs) {
  2421. auto *DeviceLinkAction =
  2422. C.MakeAction<LinkJobAction>(LI, types::TY_Image);
  2423. DA.add(*DeviceLinkAction, *ToolChains[0],
  2424. CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
  2425. ++I;
  2426. }
  2427. }
  2428. };
  2429. /// OpenMP action builder. The host bitcode is passed to the device frontend
  2430. /// and all the device linked images are passed to the host link phase.
  2431. class OpenMPActionBuilder final : public DeviceActionBuilder {
  2432. /// The OpenMP actions for the current input.
  2433. ActionList OpenMPDeviceActions;
  2434. /// The linker inputs obtained for each toolchain.
  2435. SmallVector<ActionList, 8> DeviceLinkerInputs;
  2436. public:
  2437. OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
  2438. const Driver::InputList &Inputs)
  2439. : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
  2440. ActionBuilderReturnCode
  2441. getDeviceDependences(OffloadAction::DeviceDependences &DA,
  2442. phases::ID CurPhase, phases::ID FinalPhase,
  2443. PhasesTy &Phases) override {
  2444. if (OpenMPDeviceActions.empty())
  2445. return ABRT_Inactive;
  2446. // We should always have an action for each input.
  2447. assert(OpenMPDeviceActions.size() == ToolChains.size() &&
  2448. "Number of OpenMP actions and toolchains do not match.");
  2449. // The host only depends on device action in the linking phase, when all
  2450. // the device images have to be embedded in the host image.
  2451. if (CurPhase == phases::Link) {
  2452. assert(ToolChains.size() == DeviceLinkerInputs.size() &&
  2453. "Toolchains and linker inputs sizes do not match.");
  2454. auto LI = DeviceLinkerInputs.begin();
  2455. for (auto *A : OpenMPDeviceActions) {
  2456. LI->push_back(A);
  2457. ++LI;
  2458. }
  2459. // We passed the device action as a host dependence, so we don't need to
  2460. // do anything else with them.
  2461. OpenMPDeviceActions.clear();
  2462. return ABRT_Success;
  2463. }
  2464. // By default, we produce an action for each device arch.
  2465. for (Action *&A : OpenMPDeviceActions)
  2466. A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
  2467. return ABRT_Success;
  2468. }
  2469. ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
  2470. // If this is an input action replicate it for each OpenMP toolchain.
  2471. if (auto *IA = dyn_cast<InputAction>(HostAction)) {
  2472. OpenMPDeviceActions.clear();
  2473. for (unsigned I = 0; I < ToolChains.size(); ++I)
  2474. OpenMPDeviceActions.push_back(
  2475. C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
  2476. return ABRT_Success;
  2477. }
  2478. // If this is an unbundling action use it as is for each OpenMP toolchain.
  2479. if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
  2480. OpenMPDeviceActions.clear();
  2481. auto *IA = cast<InputAction>(UA->getInputs().back());
  2482. std::string FileName = IA->getInputArg().getAsString(Args);
  2483. // Check if the type of the file is the same as the action. Do not
  2484. // unbundle it if it is not. Do not unbundle .so files, for example,
  2485. // which are not object files.
  2486. if (IA->getType() == types::TY_Object &&
  2487. (!llvm::sys::path::has_extension(FileName) ||
  2488. types::lookupTypeForExtension(
  2489. llvm::sys::path::extension(FileName).drop_front()) !=
  2490. types::TY_Object))
  2491. return ABRT_Inactive;
  2492. for (unsigned I = 0; I < ToolChains.size(); ++I) {
  2493. OpenMPDeviceActions.push_back(UA);
  2494. UA->registerDependentActionInfo(
  2495. ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
  2496. }
  2497. return ABRT_Success;
  2498. }
  2499. // When generating code for OpenMP we use the host compile phase result as
  2500. // a dependence to the device compile phase so that it can learn what
  2501. // declarations should be emitted. However, this is not the only use for
  2502. // the host action, so we prevent it from being collapsed.
  2503. if (isa<CompileJobAction>(HostAction)) {
  2504. HostAction->setCannotBeCollapsedWithNextDependentAction();
  2505. assert(ToolChains.size() == OpenMPDeviceActions.size() &&
  2506. "Toolchains and device action sizes do not match.");
  2507. OffloadAction::HostDependence HDep(
  2508. *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
  2509. /*BoundArch=*/nullptr, Action::OFK_OpenMP);
  2510. auto TC = ToolChains.begin();
  2511. for (Action *&A : OpenMPDeviceActions) {
  2512. assert(isa<CompileJobAction>(A));
  2513. OffloadAction::DeviceDependences DDep;
  2514. DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
  2515. A = C.MakeAction<OffloadAction>(HDep, DDep);
  2516. ++TC;
  2517. }
  2518. }
  2519. return ABRT_Success;
  2520. }
  2521. void appendTopLevelActions(ActionList &AL) override {
  2522. if (OpenMPDeviceActions.empty())
  2523. return;
  2524. // We should always have an action for each input.
  2525. assert(OpenMPDeviceActions.size() == ToolChains.size() &&
  2526. "Number of OpenMP actions and toolchains do not match.");
  2527. // Append all device actions followed by the proper offload action.
  2528. auto TI = ToolChains.begin();
  2529. for (auto *A : OpenMPDeviceActions) {
  2530. OffloadAction::DeviceDependences Dep;
  2531. Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
  2532. AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
  2533. ++TI;
  2534. }
  2535. // We no longer need the action stored in this builder.
  2536. OpenMPDeviceActions.clear();
  2537. }
  2538. void appendLinkActions(ActionList &AL) override {
  2539. assert(ToolChains.size() == DeviceLinkerInputs.size() &&
  2540. "Toolchains and linker inputs sizes do not match.");
  2541. // Append a new link action for each device.
  2542. auto TC = ToolChains.begin();
  2543. for (auto &LI : DeviceLinkerInputs) {
  2544. auto *DeviceLinkAction =
  2545. C.MakeAction<LinkJobAction>(LI, types::TY_Image);
  2546. OffloadAction::DeviceDependences DeviceLinkDeps;
  2547. DeviceLinkDeps.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
  2548. Action::OFK_OpenMP);
  2549. AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
  2550. DeviceLinkAction->getType()));
  2551. ++TC;
  2552. }
  2553. DeviceLinkerInputs.clear();
  2554. }
  2555. void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
  2556. bool initialize() override {
  2557. // Get the OpenMP toolchains. If we don't get any, the action builder will
  2558. // know there is nothing to do related to OpenMP offloading.
  2559. auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
  2560. for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
  2561. ++TI)
  2562. ToolChains.push_back(TI->second);
  2563. DeviceLinkerInputs.resize(ToolChains.size());
  2564. return false;
  2565. }
  2566. bool canUseBundlerUnbundler() const override {
  2567. // OpenMP should use bundled files whenever possible.
  2568. return true;
  2569. }
  2570. };
  2571. ///
  2572. /// TODO: Add the implementation for other specialized builders here.
  2573. ///
  2574. /// Specialized builders being used by this offloading action builder.
  2575. SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
  2576. /// Flag set to true if all valid builders allow file bundling/unbundling.
  2577. bool CanUseBundler;
  2578. public:
  2579. OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
  2580. const Driver::InputList &Inputs)
  2581. : C(C) {
  2582. // Create a specialized builder for each device toolchain.
  2583. IsValid = true;
  2584. // Create a specialized builder for CUDA.
  2585. SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
  2586. // Create a specialized builder for HIP.
  2587. SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
  2588. // Create a specialized builder for OpenMP.
  2589. SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
  2590. //
  2591. // TODO: Build other specialized builders here.
  2592. //
  2593. // Initialize all the builders, keeping track of errors. If all valid
  2594. // builders agree that we can use bundling, set the flag to true.
  2595. unsigned ValidBuilders = 0u;
  2596. unsigned ValidBuildersSupportingBundling = 0u;
  2597. for (auto *SB : SpecializedBuilders) {
  2598. IsValid = IsValid && !SB->initialize();
  2599. // Update the counters if the builder is valid.
  2600. if (SB->isValid()) {
  2601. ++ValidBuilders;
  2602. if (SB->canUseBundlerUnbundler())
  2603. ++ValidBuildersSupportingBundling;
  2604. }
  2605. }
  2606. CanUseBundler =
  2607. ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
  2608. }
  2609. ~OffloadingActionBuilder() {
  2610. for (auto *SB : SpecializedBuilders)
  2611. delete SB;
  2612. }
  2613. /// Generate an action that adds device dependences (if any) to a host action.
  2614. /// If no device dependence actions exist, just return the host action \a
  2615. /// HostAction. If an error is found or if no builder requires the host action
  2616. /// to be generated, return nullptr.
  2617. Action *
  2618. addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
  2619. phases::ID CurPhase, phases::ID FinalPhase,
  2620. DeviceActionBuilder::PhasesTy &Phases) {
  2621. if (!IsValid)
  2622. return nullptr;
  2623. if (SpecializedBuilders.empty())
  2624. return HostAction;
  2625. assert(HostAction && "Invalid host action!");
  2626. OffloadAction::DeviceDependences DDeps;
  2627. // Check if all the programming models agree we should not emit the host
  2628. // action. Also, keep track of the offloading kinds employed.
  2629. auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
  2630. unsigned InactiveBuilders = 0u;
  2631. unsigned IgnoringBuilders = 0u;
  2632. for (auto *SB : SpecializedBuilders) {
  2633. if (!SB->isValid()) {
  2634. ++InactiveBuilders;
  2635. continue;
  2636. }
  2637. auto RetCode =
  2638. SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
  2639. // If the builder explicitly says the host action should be ignored,
  2640. // we need to increment the variable that tracks the builders that request
  2641. // the host object to be ignored.
  2642. if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
  2643. ++IgnoringBuilders;
  2644. // Unless the builder was inactive for this action, we have to record the
  2645. // offload kind because the host will have to use it.
  2646. if (RetCode != DeviceActionBuilder::ABRT_Inactive)
  2647. OffloadKind |= SB->getAssociatedOffloadKind();
  2648. }
  2649. // If all builders agree that the host object should be ignored, just return
  2650. // nullptr.
  2651. if (IgnoringBuilders &&
  2652. SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
  2653. return nullptr;
  2654. if (DDeps.getActions().empty())
  2655. return HostAction;
  2656. // We have dependences we need to bundle together. We use an offload action
  2657. // for that.
  2658. OffloadAction::HostDependence HDep(
  2659. *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
  2660. /*BoundArch=*/nullptr, DDeps);
  2661. return C.MakeAction<OffloadAction>(HDep, DDeps);
  2662. }
  2663. /// Generate an action that adds a host dependence to a device action. The
  2664. /// results will be kept in this action builder. Return true if an error was
  2665. /// found.
  2666. bool addHostDependenceToDeviceActions(Action *&HostAction,
  2667. const Arg *InputArg) {
  2668. if (!IsValid)
  2669. return true;
  2670. // If we are supporting bundling/unbundling and the current action is an
  2671. // input action of non-source file, we replace the host action by the
  2672. // unbundling action. The bundler tool has the logic to detect if an input
  2673. // is a bundle or not and if the input is not a bundle it assumes it is a
  2674. // host file. Therefore it is safe to create an unbundling action even if
  2675. // the input is not a bundle.
  2676. if (CanUseBundler && isa<InputAction>(HostAction) &&
  2677. InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
  2678. !types::isSrcFile(HostAction->getType())) {
  2679. auto UnbundlingHostAction =
  2680. C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
  2681. UnbundlingHostAction->registerDependentActionInfo(
  2682. C.getSingleOffloadToolChain<Action::OFK_Host>(),
  2683. /*BoundArch=*/StringRef(), Action::OFK_Host);
  2684. HostAction = UnbundlingHostAction;
  2685. }
  2686. assert(HostAction && "Invalid host action!");
  2687. // Register the offload kinds that are used.
  2688. auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
  2689. for (auto *SB : SpecializedBuilders) {
  2690. if (!SB->isValid())
  2691. continue;
  2692. auto RetCode = SB->addDeviceDepences(HostAction);
  2693. // Host dependences for device actions are not compatible with that same
  2694. // action being ignored.
  2695. assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
  2696. "Host dependence not expected to be ignored.!");
  2697. // Unless the builder was inactive for this action, we have to record the
  2698. // offload kind because the host will have to use it.
  2699. if (RetCode != DeviceActionBuilder::ABRT_Inactive)
  2700. OffloadKind |= SB->getAssociatedOffloadKind();
  2701. }
  2702. // Do not use unbundler if the Host does not depend on device action.
  2703. if (OffloadKind == Action::OFK_None && CanUseBundler)
  2704. if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
  2705. HostAction = UA->getInputs().back();
  2706. return false;
  2707. }
  2708. /// Add the offloading top level actions to the provided action list. This
  2709. /// function can replace the host action by a bundling action if the
  2710. /// programming models allow it.
  2711. bool appendTopLevelActions(ActionList &AL, Action *HostAction,
  2712. const Arg *InputArg) {
  2713. // Get the device actions to be appended.
  2714. ActionList OffloadAL;
  2715. for (auto *SB : SpecializedBuilders) {
  2716. if (!SB->isValid())
  2717. continue;
  2718. SB->appendTopLevelActions(OffloadAL);
  2719. }
  2720. // If we can use the bundler, replace the host action by the bundling one in
  2721. // the resulting list. Otherwise, just append the device actions. For
  2722. // device only compilation, HostAction is a null pointer, therefore only do
  2723. // this when HostAction is not a null pointer.
  2724. if (CanUseBundler && HostAction &&
  2725. HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
  2726. // Add the host action to the list in order to create the bundling action.
  2727. OffloadAL.push_back(HostAction);
  2728. // We expect that the host action was just appended to the action list
  2729. // before this method was called.
  2730. assert(HostAction == AL.back() && "Host action not in the list??");
  2731. HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
  2732. AL.back() = HostAction;
  2733. } else
  2734. AL.append(OffloadAL.begin(), OffloadAL.end());
  2735. // Propagate to the current host action (if any) the offload information
  2736. // associated with the current input.
  2737. if (HostAction)
  2738. HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
  2739. /*BoundArch=*/nullptr);
  2740. return false;
  2741. }
  2742. Action* makeHostLinkAction() {
  2743. // Build a list of device linking actions.
  2744. ActionList DeviceAL;
  2745. for (DeviceActionBuilder *SB : SpecializedBuilders) {
  2746. if (!SB->isValid())
  2747. continue;
  2748. SB->appendLinkActions(DeviceAL);
  2749. }
  2750. if (DeviceAL.empty())
  2751. return nullptr;
  2752. // Create wrapper bitcode from the result of device link actions and compile
  2753. // it to an object which will be added to the host link command.
  2754. auto *BC = C.MakeAction<OffloadWrapperJobAction>(DeviceAL, types::TY_LLVM_BC);
  2755. auto *ASM = C.MakeAction<BackendJobAction>(BC, types::TY_PP_Asm);
  2756. return C.MakeAction<AssembleJobAction>(ASM, types::TY_Object);
  2757. }
  2758. /// Processes the host linker action. This currently consists of replacing it
  2759. /// with an offload action if there are device link objects and propagate to
  2760. /// the host action all the offload kinds used in the current compilation. The
  2761. /// resulting action is returned.
  2762. Action *processHostLinkAction(Action *HostAction) {
  2763. // Add all the dependences from the device linking actions.
  2764. OffloadAction::DeviceDependences DDeps;
  2765. for (auto *SB : SpecializedBuilders) {
  2766. if (!SB->isValid())
  2767. continue;
  2768. SB->appendLinkDependences(DDeps);
  2769. }
  2770. // Calculate all the offload kinds used in the current compilation.
  2771. unsigned ActiveOffloadKinds = 0u;
  2772. for (auto &I : InputArgToOffloadKindMap)
  2773. ActiveOffloadKinds |= I.second;
  2774. // If we don't have device dependencies, we don't have to create an offload
  2775. // action.
  2776. if (DDeps.getActions().empty()) {
  2777. // Propagate all the active kinds to host action. Given that it is a link
  2778. // action it is assumed to depend on all actions generated so far.
  2779. HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
  2780. /*BoundArch=*/nullptr);
  2781. return HostAction;
  2782. }
  2783. // Create the offload action with all dependences. When an offload action
  2784. // is created the kinds are propagated to the host action, so we don't have
  2785. // to do that explicitly here.
  2786. OffloadAction::HostDependence HDep(
  2787. *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
  2788. /*BoundArch*/ nullptr, ActiveOffloadKinds);
  2789. return C.MakeAction<OffloadAction>(HDep, DDeps);
  2790. }
  2791. };
  2792. } // anonymous namespace.
  2793. void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
  2794. const InputList &Inputs,
  2795. ActionList &Actions) const {
  2796. // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
  2797. Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
  2798. Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
  2799. if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
  2800. Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
  2801. Args.eraseArg(options::OPT__SLASH_Yc);
  2802. Args.eraseArg(options::OPT__SLASH_Yu);
  2803. YcArg = YuArg = nullptr;
  2804. }
  2805. if (YcArg && Inputs.size() > 1) {
  2806. Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
  2807. Args.eraseArg(options::OPT__SLASH_Yc);
  2808. YcArg = nullptr;
  2809. }
  2810. Arg *FinalPhaseArg;
  2811. phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
  2812. if (FinalPhase == phases::Link) {
  2813. if (Args.hasArg(options::OPT_emit_llvm))
  2814. Diag(clang::diag::err_drv_emit_llvm_link);
  2815. if (IsCLMode() && LTOMode != LTOK_None &&
  2816. !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
  2817. Diag(clang::diag::err_drv_lto_without_lld);
  2818. }
  2819. if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
  2820. // If only preprocessing or /Y- is used, all pch handling is disabled.
  2821. // Rather than check for it everywhere, just remove clang-cl pch-related
  2822. // flags here.
  2823. Args.eraseArg(options::OPT__SLASH_Fp);
  2824. Args.eraseArg(options::OPT__SLASH_Yc);
  2825. Args.eraseArg(options::OPT__SLASH_Yu);
  2826. YcArg = YuArg = nullptr;
  2827. }
  2828. unsigned LastPLSize = 0;
  2829. for (auto &I : Inputs) {
  2830. types::ID InputType = I.first;
  2831. const Arg *InputArg = I.second;
  2832. llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
  2833. types::getCompilationPhases(InputType, PL);
  2834. LastPLSize = PL.size();
  2835. // If the first step comes after the final phase we are doing as part of
  2836. // this compilation, warn the user about it.
  2837. phases::ID InitialPhase = PL[0];
  2838. if (InitialPhase > FinalPhase) {
  2839. if (InputArg->isClaimed())
  2840. continue;
  2841. // Claim here to avoid the more general unused warning.
  2842. InputArg->claim();
  2843. // Suppress all unused style warnings with -Qunused-arguments
  2844. if (Args.hasArg(options::OPT_Qunused_arguments))
  2845. continue;
  2846. // Special case when final phase determined by binary name, rather than
  2847. // by a command-line argument with a corresponding Arg.
  2848. if (CCCIsCPP())
  2849. Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
  2850. << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
  2851. // Special case '-E' warning on a previously preprocessed file to make
  2852. // more sense.
  2853. else if (InitialPhase == phases::Compile &&
  2854. (Args.getLastArg(options::OPT__SLASH_EP,
  2855. options::OPT__SLASH_P) ||
  2856. Args.getLastArg(options::OPT_E) ||
  2857. Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
  2858. getPreprocessedType(InputType) == types::TY_INVALID)
  2859. Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
  2860. << InputArg->getAsString(Args) << !!FinalPhaseArg
  2861. << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
  2862. else
  2863. Diag(clang::diag::warn_drv_input_file_unused)
  2864. << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
  2865. << !!FinalPhaseArg
  2866. << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
  2867. continue;
  2868. }
  2869. if (YcArg) {
  2870. // Add a separate precompile phase for the compile phase.
  2871. if (FinalPhase >= phases::Compile) {
  2872. const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
  2873. llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
  2874. types::getCompilationPhases(HeaderType, PCHPL);
  2875. // Build the pipeline for the pch file.
  2876. Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
  2877. for (phases::ID Phase : PCHPL)
  2878. ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
  2879. assert(ClangClPch);
  2880. Actions.push_back(ClangClPch);
  2881. // The driver currently exits after the first failed command. This
  2882. // relies on that behavior, to make sure if the pch generation fails,
  2883. // the main compilation won't run.
  2884. // FIXME: If the main compilation fails, the PCH generation should
  2885. // probably not be considered successful either.
  2886. }
  2887. }
  2888. }
  2889. // If we are linking, claim any options which are obviously only used for
  2890. // compilation.
  2891. // FIXME: Understand why the last Phase List length is used here.
  2892. if (FinalPhase == phases::Link && LastPLSize == 1) {
  2893. Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
  2894. Args.ClaimAllArgs(options::OPT_cl_compile_Group);
  2895. }
  2896. }
  2897. void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
  2898. const InputList &Inputs, ActionList &Actions) const {
  2899. llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
  2900. if (!SuppressMissingInputWarning && Inputs.empty()) {
  2901. Diag(clang::diag::err_drv_no_input_files);
  2902. return;
  2903. }
  2904. // Reject -Z* at the top level, these options should never have been exposed
  2905. // by gcc.
  2906. if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
  2907. Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
  2908. // Diagnose misuse of /Fo.
  2909. if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
  2910. StringRef V = A->getValue();
  2911. if (Inputs.size() > 1 && !V.empty() &&
  2912. !llvm::sys::path::is_separator(V.back())) {
  2913. // Check whether /Fo tries to name an output file for multiple inputs.
  2914. Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
  2915. << A->getSpelling() << V;
  2916. Args.eraseArg(options::OPT__SLASH_Fo);
  2917. }
  2918. }
  2919. // Diagnose misuse of /Fa.
  2920. if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
  2921. StringRef V = A->getValue();
  2922. if (Inputs.size() > 1 && !V.empty() &&
  2923. !llvm::sys::path::is_separator(V.back())) {
  2924. // Check whether /Fa tries to name an asm file for multiple inputs.
  2925. Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
  2926. << A->getSpelling() << V;
  2927. Args.eraseArg(options::OPT__SLASH_Fa);
  2928. }
  2929. }
  2930. // Diagnose misuse of /o.
  2931. if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
  2932. if (A->getValue()[0] == '\0') {
  2933. // It has to have a value.
  2934. Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
  2935. Args.eraseArg(options::OPT__SLASH_o);
  2936. }
  2937. }
  2938. handleArguments(C, Args, Inputs, Actions);
  2939. // Builder to be used to build offloading actions.
  2940. OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
  2941. // Construct the actions to perform.
  2942. HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
  2943. ActionList LinkerInputs;
  2944. ActionList MergerInputs;
  2945. for (auto &I : Inputs) {
  2946. types::ID InputType = I.first;
  2947. const Arg *InputArg = I.second;
  2948. llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
  2949. types::getCompilationPhases(*this, Args, InputType, PL);
  2950. if (PL.empty())
  2951. continue;
  2952. llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> FullPL;
  2953. types::getCompilationPhases(InputType, FullPL);
  2954. // Build the pipeline for this file.
  2955. Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
  2956. // Use the current host action in any of the offloading actions, if
  2957. // required.
  2958. if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
  2959. break;
  2960. for (phases::ID Phase : PL) {
  2961. // Add any offload action the host action depends on.
  2962. Current = OffloadBuilder.addDeviceDependencesToHostAction(
  2963. Current, InputArg, Phase, PL.back(), FullPL);
  2964. if (!Current)
  2965. break;
  2966. // Queue linker inputs.
  2967. if (Phase == phases::Link) {
  2968. assert(Phase == PL.back() && "linking must be final compilation step.");
  2969. LinkerInputs.push_back(Current);
  2970. Current = nullptr;
  2971. break;
  2972. }
  2973. // TODO: Consider removing this because the merged may not end up being
  2974. // the final Phase in the pipeline. Perhaps the merged could just merge
  2975. // and then pass an artifact of some sort to the Link Phase.
  2976. // Queue merger inputs.
  2977. if (Phase == phases::IfsMerge) {
  2978. assert(Phase == PL.back() && "merging must be final compilation step.");
  2979. MergerInputs.push_back(Current);
  2980. Current = nullptr;
  2981. break;
  2982. }
  2983. // Each precompiled header file after a module file action is a module
  2984. // header of that same module file, rather than being compiled to a
  2985. // separate PCH.
  2986. if (Phase == phases::Precompile && HeaderModuleAction &&
  2987. getPrecompiledType(InputType) == types::TY_PCH) {
  2988. HeaderModuleAction->addModuleHeaderInput(Current);
  2989. Current = nullptr;
  2990. break;
  2991. }
  2992. // FIXME: Should we include any prior module file outputs as inputs of
  2993. // later actions in the same command line?
  2994. // Otherwise construct the appropriate action.
  2995. Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
  2996. // We didn't create a new action, so we will just move to the next phase.
  2997. if (NewCurrent == Current)
  2998. continue;
  2999. if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
  3000. HeaderModuleAction = HMA;
  3001. Current = NewCurrent;
  3002. // Use the current host action in any of the offloading actions, if
  3003. // required.
  3004. if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
  3005. break;
  3006. if (Current->getType() == types::TY_Nothing)
  3007. break;
  3008. }
  3009. // If we ended with something, add to the output list.
  3010. if (Current)
  3011. Actions.push_back(Current);
  3012. // Add any top level actions generated for offloading.
  3013. OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
  3014. }
  3015. // Add a link action if necessary.
  3016. if (!LinkerInputs.empty()) {
  3017. if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
  3018. LinkerInputs.push_back(Wrapper);
  3019. Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
  3020. LA = OffloadBuilder.processHostLinkAction(LA);
  3021. Actions.push_back(LA);
  3022. }
  3023. // Add an interface stubs merge action if necessary.
  3024. if (!MergerInputs.empty())
  3025. Actions.push_back(
  3026. C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
  3027. // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
  3028. // Compile phase that prints out supported cpu models and quits.
  3029. if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
  3030. // Use the -mcpu=? flag as the dummy input to cc1.
  3031. Actions.clear();
  3032. Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
  3033. Actions.push_back(
  3034. C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
  3035. for (auto &I : Inputs)
  3036. I.second->claim();
  3037. }
  3038. // Claim ignored clang-cl options.
  3039. Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
  3040. // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
  3041. // to non-CUDA compilations and should not trigger warnings there.
  3042. Args.ClaimAllArgs(options::OPT_cuda_host_only);
  3043. Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
  3044. }
  3045. Action *Driver::ConstructPhaseAction(
  3046. Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
  3047. Action::OffloadKind TargetDeviceOffloadKind) const {
  3048. llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
  3049. // Some types skip the assembler phase (e.g., llvm-bc), but we can't
  3050. // encode this in the steps because the intermediate type depends on
  3051. // arguments. Just special case here.
  3052. if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
  3053. return Input;
  3054. // Build the appropriate action.
  3055. switch (Phase) {
  3056. case phases::Link:
  3057. llvm_unreachable("link action invalid here.");
  3058. case phases::IfsMerge:
  3059. llvm_unreachable("ifsmerge action invalid here.");
  3060. case phases::Preprocess: {
  3061. types::ID OutputTy;
  3062. // -M and -MM specify the dependency file name by altering the output type,
  3063. // -if -MD and -MMD are not specified.
  3064. if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
  3065. !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
  3066. OutputTy = types::TY_Dependencies;
  3067. } else {
  3068. OutputTy = Input->getType();
  3069. if (!Args.hasFlag(options::OPT_frewrite_includes,
  3070. options::OPT_fno_rewrite_includes, false) &&
  3071. !Args.hasFlag(options::OPT_frewrite_imports,
  3072. options::OPT_fno_rewrite_imports, false) &&
  3073. !CCGenDiagnostics)
  3074. OutputTy = types::getPreprocessedType(OutputTy);
  3075. assert(OutputTy != types::TY_INVALID &&
  3076. "Cannot preprocess this input type!");
  3077. }
  3078. return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
  3079. }
  3080. case phases::Precompile: {
  3081. types::ID OutputTy = getPrecompiledType(Input->getType());
  3082. assert(OutputTy != types::TY_INVALID &&
  3083. "Cannot precompile this input type!");
  3084. // If we're given a module name, precompile header file inputs as a
  3085. // module, not as a precompiled header.
  3086. const char *ModName = nullptr;
  3087. if (OutputTy == types::TY_PCH) {
  3088. if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
  3089. ModName = A->getValue();
  3090. if (ModName)
  3091. OutputTy = types::TY_ModuleFile;
  3092. }
  3093. if (Args.hasArg(options::OPT_fsyntax_only)) {
  3094. // Syntax checks should not emit a PCH file
  3095. OutputTy = types::TY_Nothing;
  3096. }
  3097. if (ModName)
  3098. return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
  3099. ModName);
  3100. return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
  3101. }
  3102. case phases::Compile: {
  3103. if (Args.hasArg(options::OPT_fsyntax_only))
  3104. return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
  3105. if (Args.hasArg(options::OPT_rewrite_objc))
  3106. return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
  3107. if (Args.hasArg(options::OPT_rewrite_legacy_objc))
  3108. return C.MakeAction<CompileJobAction>(Input,
  3109. types::TY_RewrittenLegacyObjC);
  3110. if (Args.hasArg(options::OPT__analyze))
  3111. return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
  3112. if (Args.hasArg(options::OPT__migrate))
  3113. return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
  3114. if (Args.hasArg(options::OPT_emit_ast))
  3115. return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
  3116. if (Args.hasArg(options::OPT_module_file_info))
  3117. return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
  3118. if (Args.hasArg(options::OPT_verify_pch))
  3119. return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
  3120. if (Args.hasArg(options::OPT_emit_interface_stubs))
  3121. return C.MakeAction<CompileJobAction>(Input, types::TY_IFS_CPP);
  3122. return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
  3123. }
  3124. case phases::Backend: {
  3125. if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
  3126. types::ID Output =
  3127. Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
  3128. return C.MakeAction<BackendJobAction>(Input, Output);
  3129. }
  3130. if (Args.hasArg(options::OPT_emit_llvm)) {
  3131. types::ID Output =
  3132. Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
  3133. return C.MakeAction<BackendJobAction>(Input, Output);
  3134. }
  3135. return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
  3136. }
  3137. case phases::Assemble:
  3138. return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
  3139. }
  3140. llvm_unreachable("invalid phase in ConstructPhaseAction");
  3141. }
  3142. void Driver::BuildJobs(Compilation &C) const {
  3143. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  3144. Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
  3145. // It is an error to provide a -o option if we are making multiple output
  3146. // files.
  3147. if (FinalOutput) {
  3148. unsigned NumOutputs = 0;
  3149. for (const Action *A : C.getActions())
  3150. if (A->getType() != types::TY_Nothing)
  3151. ++NumOutputs;
  3152. if (NumOutputs > 1) {
  3153. Diag(clang::diag::err_drv_output_argument_with_multiple_files);
  3154. FinalOutput = nullptr;
  3155. }
  3156. }
  3157. // Collect the list of architectures.
  3158. llvm::StringSet<> ArchNames;
  3159. if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
  3160. for (const Arg *A : C.getArgs())
  3161. if (A->getOption().matches(options::OPT_arch))
  3162. ArchNames.insert(A->getValue());
  3163. // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
  3164. std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
  3165. for (Action *A : C.getActions()) {
  3166. // If we are linking an image for multiple archs then the linker wants
  3167. // -arch_multiple and -final_output <final image name>. Unfortunately, this
  3168. // doesn't fit in cleanly because we have to pass this information down.
  3169. //
  3170. // FIXME: This is a hack; find a cleaner way to integrate this into the
  3171. // process.
  3172. const char *LinkingOutput = nullptr;
  3173. if (isa<LipoJobAction>(A)) {
  3174. if (FinalOutput)
  3175. LinkingOutput = FinalOutput->getValue();
  3176. else
  3177. LinkingOutput = getDefaultImageName();
  3178. }
  3179. BuildJobsForAction(C, A, &C.getDefaultToolChain(),
  3180. /*BoundArch*/ StringRef(),
  3181. /*AtTopLevel*/ true,
  3182. /*MultipleArchs*/ ArchNames.size() > 1,
  3183. /*LinkingOutput*/ LinkingOutput, CachedResults,
  3184. /*TargetDeviceOffloadKind*/ Action::OFK_None);
  3185. }
  3186. // If the user passed -Qunused-arguments or there were errors, don't warn
  3187. // about any unused arguments.
  3188. if (Diags.hasErrorOccurred() ||
  3189. C.getArgs().hasArg(options::OPT_Qunused_arguments))
  3190. return;
  3191. // Claim -### here.
  3192. (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
  3193. // Claim --driver-mode, --rsp-quoting, it was handled earlier.
  3194. (void)C.getArgs().hasArg(options::OPT_driver_mode);
  3195. (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
  3196. for (Arg *A : C.getArgs()) {
  3197. // FIXME: It would be nice to be able to send the argument to the
  3198. // DiagnosticsEngine, so that extra values, position, and so on could be
  3199. // printed.
  3200. if (!A->isClaimed()) {
  3201. if (A->getOption().hasFlag(options::NoArgumentUnused))
  3202. continue;
  3203. // Suppress the warning automatically if this is just a flag, and it is an
  3204. // instance of an argument we already claimed.
  3205. const Option &Opt = A->getOption();
  3206. if (Opt.getKind() == Option::FlagClass) {
  3207. bool DuplicateClaimed = false;
  3208. for (const Arg *AA : C.getArgs().filtered(&Opt)) {
  3209. if (AA->isClaimed()) {
  3210. DuplicateClaimed = true;
  3211. break;
  3212. }
  3213. }
  3214. if (DuplicateClaimed)
  3215. continue;
  3216. }
  3217. // In clang-cl, don't mention unknown arguments here since they have
  3218. // already been warned about.
  3219. if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
  3220. Diag(clang::diag::warn_drv_unused_argument)
  3221. << A->getAsString(C.getArgs());
  3222. }
  3223. }
  3224. }
  3225. namespace {
  3226. /// Utility class to control the collapse of dependent actions and select the
  3227. /// tools accordingly.
  3228. class ToolSelector final {
  3229. /// The tool chain this selector refers to.
  3230. const ToolChain &TC;
  3231. /// The compilation this selector refers to.
  3232. const Compilation &C;
  3233. /// The base action this selector refers to.
  3234. const JobAction *BaseAction;
  3235. /// Set to true if the current toolchain refers to host actions.
  3236. bool IsHostSelector;
  3237. /// Set to true if save-temps and embed-bitcode functionalities are active.
  3238. bool SaveTemps;
  3239. bool EmbedBitcode;
  3240. /// Get previous dependent action or null if that does not exist. If
  3241. /// \a CanBeCollapsed is false, that action must be legal to collapse or
  3242. /// null will be returned.
  3243. const JobAction *getPrevDependentAction(const ActionList &Inputs,
  3244. ActionList &SavedOffloadAction,
  3245. bool CanBeCollapsed = true) {
  3246. // An option can be collapsed only if it has a single input.
  3247. if (Inputs.size() != 1)
  3248. return nullptr;
  3249. Action *CurAction = *Inputs.begin();
  3250. if (CanBeCollapsed &&
  3251. !CurAction->isCollapsingWithNextDependentActionLegal())
  3252. return nullptr;
  3253. // If the input action is an offload action. Look through it and save any
  3254. // offload action that can be dropped in the event of a collapse.
  3255. if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
  3256. // If the dependent action is a device action, we will attempt to collapse
  3257. // only with other device actions. Otherwise, we would do the same but
  3258. // with host actions only.
  3259. if (!IsHostSelector) {
  3260. if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
  3261. CurAction =
  3262. OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
  3263. if (CanBeCollapsed &&
  3264. !CurAction->isCollapsingWithNextDependentActionLegal())
  3265. return nullptr;
  3266. SavedOffloadAction.push_back(OA);
  3267. return dyn_cast<JobAction>(CurAction);
  3268. }
  3269. } else if (OA->hasHostDependence()) {
  3270. CurAction = OA->getHostDependence();
  3271. if (CanBeCollapsed &&
  3272. !CurAction->isCollapsingWithNextDependentActionLegal())
  3273. return nullptr;
  3274. SavedOffloadAction.push_back(OA);
  3275. return dyn_cast<JobAction>(CurAction);
  3276. }
  3277. return nullptr;
  3278. }
  3279. return dyn_cast<JobAction>(CurAction);
  3280. }
  3281. /// Return true if an assemble action can be collapsed.
  3282. bool canCollapseAssembleAction() const {
  3283. return TC.useIntegratedAs() && !SaveTemps &&
  3284. !C.getArgs().hasArg(options::OPT_via_file_asm) &&
  3285. !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
  3286. !C.getArgs().hasArg(options::OPT__SLASH_Fa);
  3287. }
  3288. /// Return true if a preprocessor action can be collapsed.
  3289. bool canCollapsePreprocessorAction() const {
  3290. return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
  3291. !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
  3292. !C.getArgs().hasArg(options::OPT_rewrite_objc);
  3293. }
  3294. /// Struct that relates an action with the offload actions that would be
  3295. /// collapsed with it.
  3296. struct JobActionInfo final {
  3297. /// The action this info refers to.
  3298. const JobAction *JA = nullptr;
  3299. /// The offload actions we need to take care off if this action is
  3300. /// collapsed.
  3301. ActionList SavedOffloadAction;
  3302. };
  3303. /// Append collapsed offload actions from the give nnumber of elements in the
  3304. /// action info array.
  3305. static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
  3306. ArrayRef<JobActionInfo> &ActionInfo,
  3307. unsigned ElementNum) {
  3308. assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
  3309. for (unsigned I = 0; I < ElementNum; ++I)
  3310. CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
  3311. ActionInfo[I].SavedOffloadAction.end());
  3312. }
  3313. /// Functions that attempt to perform the combining. They detect if that is
  3314. /// legal, and if so they update the inputs \a Inputs and the offload action
  3315. /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
  3316. /// the combined action is returned. If the combining is not legal or if the
  3317. /// tool does not exist, null is returned.
  3318. /// Currently three kinds of collapsing are supported:
  3319. /// - Assemble + Backend + Compile;
  3320. /// - Assemble + Backend ;
  3321. /// - Backend + Compile.
  3322. const Tool *
  3323. combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
  3324. ActionList &Inputs,
  3325. ActionList &CollapsedOffloadAction) {
  3326. if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
  3327. return nullptr;
  3328. auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
  3329. auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
  3330. auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
  3331. if (!AJ || !BJ || !CJ)
  3332. return nullptr;
  3333. // Get compiler tool.
  3334. const Tool *T = TC.SelectTool(*CJ);
  3335. if (!T)
  3336. return nullptr;
  3337. // When using -fembed-bitcode, it is required to have the same tool (clang)
  3338. // for both CompilerJA and BackendJA. Otherwise, combine two stages.
  3339. if (EmbedBitcode) {
  3340. const Tool *BT = TC.SelectTool(*BJ);
  3341. if (BT == T)
  3342. return nullptr;
  3343. }
  3344. if (!T->hasIntegratedAssembler())
  3345. return nullptr;
  3346. Inputs = CJ->getInputs();
  3347. AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
  3348. /*NumElements=*/3);
  3349. return T;
  3350. }
  3351. const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
  3352. ActionList &Inputs,
  3353. ActionList &CollapsedOffloadAction) {
  3354. if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
  3355. return nullptr;
  3356. auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
  3357. auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
  3358. if (!AJ || !BJ)
  3359. return nullptr;
  3360. // Get backend tool.
  3361. const Tool *T = TC.SelectTool(*BJ);
  3362. if (!T)
  3363. return nullptr;
  3364. if (!T->hasIntegratedAssembler())
  3365. return nullptr;
  3366. Inputs = BJ->getInputs();
  3367. AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
  3368. /*NumElements=*/2);
  3369. return T;
  3370. }
  3371. const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
  3372. ActionList &Inputs,
  3373. ActionList &CollapsedOffloadAction) {
  3374. if (ActionInfo.size() < 2)
  3375. return nullptr;
  3376. auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
  3377. auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
  3378. if (!BJ || !CJ)
  3379. return nullptr;
  3380. // Check if the initial input (to the compile job or its predessor if one
  3381. // exists) is LLVM bitcode. In that case, no preprocessor step is required
  3382. // and we can still collapse the compile and backend jobs when we have
  3383. // -save-temps. I.e. there is no need for a separate compile job just to
  3384. // emit unoptimized bitcode.
  3385. bool InputIsBitcode = true;
  3386. for (size_t i = 1; i < ActionInfo.size(); i++)
  3387. if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
  3388. ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
  3389. InputIsBitcode = false;
  3390. break;
  3391. }
  3392. if (!InputIsBitcode && !canCollapsePreprocessorAction())
  3393. return nullptr;
  3394. // Get compiler tool.
  3395. const Tool *T = TC.SelectTool(*CJ);
  3396. if (!T)
  3397. return nullptr;
  3398. if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
  3399. return nullptr;
  3400. Inputs = CJ->getInputs();
  3401. AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
  3402. /*NumElements=*/2);
  3403. return T;
  3404. }
  3405. /// Updates the inputs if the obtained tool supports combining with
  3406. /// preprocessor action, and the current input is indeed a preprocessor
  3407. /// action. If combining results in the collapse of offloading actions, those
  3408. /// are appended to \a CollapsedOffloadAction.
  3409. void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
  3410. ActionList &CollapsedOffloadAction) {
  3411. if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
  3412. return;
  3413. // Attempt to get a preprocessor action dependence.
  3414. ActionList PreprocessJobOffloadActions;
  3415. ActionList NewInputs;
  3416. for (Action *A : Inputs) {
  3417. auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
  3418. if (!PJ || !isa<PreprocessJobAction>(PJ)) {
  3419. NewInputs.push_back(A);
  3420. continue;
  3421. }
  3422. // This is legal to combine. Append any offload action we found and add the
  3423. // current input to preprocessor inputs.
  3424. CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
  3425. PreprocessJobOffloadActions.end());
  3426. NewInputs.append(PJ->input_begin(), PJ->input_end());
  3427. }
  3428. Inputs = NewInputs;
  3429. }
  3430. public:
  3431. ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
  3432. const Compilation &C, bool SaveTemps, bool EmbedBitcode)
  3433. : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
  3434. EmbedBitcode(EmbedBitcode) {
  3435. assert(BaseAction && "Invalid base action.");
  3436. IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
  3437. }
  3438. /// Check if a chain of actions can be combined and return the tool that can
  3439. /// handle the combination of actions. The pointer to the current inputs \a
  3440. /// Inputs and the list of offload actions \a CollapsedOffloadActions
  3441. /// connected to collapsed actions are updated accordingly. The latter enables
  3442. /// the caller of the selector to process them afterwards instead of just
  3443. /// dropping them. If no suitable tool is found, null will be returned.
  3444. const Tool *getTool(ActionList &Inputs,
  3445. ActionList &CollapsedOffloadAction) {
  3446. //
  3447. // Get the largest chain of actions that we could combine.
  3448. //
  3449. SmallVector<JobActionInfo, 5> ActionChain(1);
  3450. ActionChain.back().JA = BaseAction;
  3451. while (ActionChain.back().JA) {
  3452. const Action *CurAction = ActionChain.back().JA;
  3453. // Grow the chain by one element.
  3454. ActionChain.resize(ActionChain.size() + 1);
  3455. JobActionInfo &AI = ActionChain.back();
  3456. // Attempt to fill it with the
  3457. AI.JA =
  3458. getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
  3459. }
  3460. // Pop the last action info as it could not be filled.
  3461. ActionChain.pop_back();
  3462. //
  3463. // Attempt to combine actions. If all combining attempts failed, just return
  3464. // the tool of the provided action. At the end we attempt to combine the
  3465. // action with any preprocessor action it may depend on.
  3466. //
  3467. const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
  3468. CollapsedOffloadAction);
  3469. if (!T)
  3470. T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
  3471. if (!T)
  3472. T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
  3473. if (!T) {
  3474. Inputs = BaseAction->getInputs();
  3475. T = TC.SelectTool(*BaseAction);
  3476. }
  3477. combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
  3478. return T;
  3479. }
  3480. };
  3481. }
  3482. /// Return a string that uniquely identifies the result of a job. The bound arch
  3483. /// is not necessarily represented in the toolchain's triple -- for example,
  3484. /// armv7 and armv7s both map to the same triple -- so we need both in our map.
  3485. /// Also, we need to add the offloading device kind, as the same tool chain can
  3486. /// be used for host and device for some programming models, e.g. OpenMP.
  3487. static std::string GetTriplePlusArchString(const ToolChain *TC,
  3488. StringRef BoundArch,
  3489. Action::OffloadKind OffloadKind) {
  3490. std::string TriplePlusArch = TC->getTriple().normalize();
  3491. if (!BoundArch.empty()) {
  3492. TriplePlusArch += "-";
  3493. TriplePlusArch += BoundArch;
  3494. }
  3495. TriplePlusArch += "-";
  3496. TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
  3497. return TriplePlusArch;
  3498. }
  3499. InputInfo Driver::BuildJobsForAction(
  3500. Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
  3501. bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
  3502. std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
  3503. Action::OffloadKind TargetDeviceOffloadKind) const {
  3504. std::pair<const Action *, std::string> ActionTC = {
  3505. A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
  3506. auto CachedResult = CachedResults.find(ActionTC);
  3507. if (CachedResult != CachedResults.end()) {
  3508. return CachedResult->second;
  3509. }
  3510. InputInfo Result = BuildJobsForActionNoCache(
  3511. C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
  3512. CachedResults, TargetDeviceOffloadKind);
  3513. CachedResults[ActionTC] = Result;
  3514. return Result;
  3515. }
  3516. InputInfo Driver::BuildJobsForActionNoCache(
  3517. Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
  3518. bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
  3519. std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
  3520. Action::OffloadKind TargetDeviceOffloadKind) const {
  3521. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  3522. InputInfoList OffloadDependencesInputInfo;
  3523. bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
  3524. if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
  3525. // The 'Darwin' toolchain is initialized only when its arguments are
  3526. // computed. Get the default arguments for OFK_None to ensure that
  3527. // initialization is performed before processing the offload action.
  3528. // FIXME: Remove when darwin's toolchain is initialized during construction.
  3529. C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
  3530. // The offload action is expected to be used in four different situations.
  3531. //
  3532. // a) Set a toolchain/architecture/kind for a host action:
  3533. // Host Action 1 -> OffloadAction -> Host Action 2
  3534. //
  3535. // b) Set a toolchain/architecture/kind for a device action;
  3536. // Device Action 1 -> OffloadAction -> Device Action 2
  3537. //
  3538. // c) Specify a device dependence to a host action;
  3539. // Device Action 1 _
  3540. // \
  3541. // Host Action 1 ---> OffloadAction -> Host Action 2
  3542. //
  3543. // d) Specify a host dependence to a device action.
  3544. // Host Action 1 _
  3545. // \
  3546. // Device Action 1 ---> OffloadAction -> Device Action 2
  3547. //
  3548. // For a) and b), we just return the job generated for the dependence. For
  3549. // c) and d) we override the current action with the host/device dependence
  3550. // if the current toolchain is host/device and set the offload dependences
  3551. // info with the jobs obtained from the device/host dependence(s).
  3552. // If there is a single device option, just generate the job for it.
  3553. if (OA->hasSingleDeviceDependence()) {
  3554. InputInfo DevA;
  3555. OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
  3556. const char *DepBoundArch) {
  3557. DevA =
  3558. BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
  3559. /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
  3560. CachedResults, DepA->getOffloadingDeviceKind());
  3561. });
  3562. return DevA;
  3563. }
  3564. // If 'Action 2' is host, we generate jobs for the device dependences and
  3565. // override the current action with the host dependence. Otherwise, we
  3566. // generate the host dependences and override the action with the device
  3567. // dependence. The dependences can't therefore be a top-level action.
  3568. OA->doOnEachDependence(
  3569. /*IsHostDependence=*/BuildingForOffloadDevice,
  3570. [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
  3571. OffloadDependencesInputInfo.push_back(BuildJobsForAction(
  3572. C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
  3573. /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
  3574. DepA->getOffloadingDeviceKind()));
  3575. });
  3576. A = BuildingForOffloadDevice
  3577. ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
  3578. : OA->getHostDependence();
  3579. }
  3580. if (const InputAction *IA = dyn_cast<InputAction>(A)) {
  3581. // FIXME: It would be nice to not claim this here; maybe the old scheme of
  3582. // just using Args was better?
  3583. const Arg &Input = IA->getInputArg();
  3584. Input.claim();
  3585. if (Input.getOption().matches(options::OPT_INPUT)) {
  3586. const char *Name = Input.getValue();
  3587. return InputInfo(A, Name, /* _BaseInput = */ Name);
  3588. }
  3589. return InputInfo(A, &Input, /* _BaseInput = */ "");
  3590. }
  3591. if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
  3592. const ToolChain *TC;
  3593. StringRef ArchName = BAA->getArchName();
  3594. if (!ArchName.empty())
  3595. TC = &getToolChain(C.getArgs(),
  3596. computeTargetTriple(*this, TargetTriple,
  3597. C.getArgs(), ArchName));
  3598. else
  3599. TC = &C.getDefaultToolChain();
  3600. return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
  3601. MultipleArchs, LinkingOutput, CachedResults,
  3602. TargetDeviceOffloadKind);
  3603. }
  3604. ActionList Inputs = A->getInputs();
  3605. const JobAction *JA = cast<JobAction>(A);
  3606. ActionList CollapsedOffloadActions;
  3607. ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
  3608. embedBitcodeInObject() && !isUsingLTO());
  3609. const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
  3610. if (!T)
  3611. return InputInfo();
  3612. // If we've collapsed action list that contained OffloadAction we
  3613. // need to build jobs for host/device-side inputs it may have held.
  3614. for (const auto *OA : CollapsedOffloadActions)
  3615. cast<OffloadAction>(OA)->doOnEachDependence(
  3616. /*IsHostDependence=*/BuildingForOffloadDevice,
  3617. [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
  3618. OffloadDependencesInputInfo.push_back(BuildJobsForAction(
  3619. C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
  3620. /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
  3621. DepA->getOffloadingDeviceKind()));
  3622. });
  3623. // Only use pipes when there is exactly one input.
  3624. InputInfoList InputInfos;
  3625. for (const Action *Input : Inputs) {
  3626. // Treat dsymutil and verify sub-jobs as being at the top-level too, they
  3627. // shouldn't get temporary output names.
  3628. // FIXME: Clean this up.
  3629. bool SubJobAtTopLevel =
  3630. AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
  3631. InputInfos.push_back(BuildJobsForAction(
  3632. C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
  3633. CachedResults, A->getOffloadingDeviceKind()));
  3634. }
  3635. // Always use the first input as the base input.
  3636. const char *BaseInput = InputInfos[0].getBaseInput();
  3637. // ... except dsymutil actions, which use their actual input as the base
  3638. // input.
  3639. if (JA->getType() == types::TY_dSYM)
  3640. BaseInput = InputInfos[0].getFilename();
  3641. // ... and in header module compilations, which use the module name.
  3642. if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
  3643. BaseInput = ModuleJA->getModuleName();
  3644. // Append outputs of offload device jobs to the input list
  3645. if (!OffloadDependencesInputInfo.empty())
  3646. InputInfos.append(OffloadDependencesInputInfo.begin(),
  3647. OffloadDependencesInputInfo.end());
  3648. // Set the effective triple of the toolchain for the duration of this job.
  3649. llvm::Triple EffectiveTriple;
  3650. const ToolChain &ToolTC = T->getToolChain();
  3651. const ArgList &Args =
  3652. C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
  3653. if (InputInfos.size() != 1) {
  3654. EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
  3655. } else {
  3656. // Pass along the input type if it can be unambiguously determined.
  3657. EffectiveTriple = llvm::Triple(
  3658. ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
  3659. }
  3660. RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
  3661. // Determine the place to write output to, if any.
  3662. InputInfo Result;
  3663. InputInfoList UnbundlingResults;
  3664. if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
  3665. // If we have an unbundling job, we need to create results for all the
  3666. // outputs. We also update the results cache so that other actions using
  3667. // this unbundling action can get the right results.
  3668. for (auto &UI : UA->getDependentActionsInfo()) {
  3669. assert(UI.DependentOffloadKind != Action::OFK_None &&
  3670. "Unbundling with no offloading??");
  3671. // Unbundling actions are never at the top level. When we generate the
  3672. // offloading prefix, we also do that for the host file because the
  3673. // unbundling action does not change the type of the output which can
  3674. // cause a overwrite.
  3675. std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
  3676. UI.DependentOffloadKind,
  3677. UI.DependentToolChain->getTriple().normalize(),
  3678. /*CreatePrefixForHost=*/true);
  3679. auto CurI = InputInfo(
  3680. UA,
  3681. GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
  3682. /*AtTopLevel=*/false,
  3683. MultipleArchs ||
  3684. UI.DependentOffloadKind == Action::OFK_HIP,
  3685. OffloadingPrefix),
  3686. BaseInput);
  3687. // Save the unbundling result.
  3688. UnbundlingResults.push_back(CurI);
  3689. // Get the unique string identifier for this dependence and cache the
  3690. // result.
  3691. StringRef Arch;
  3692. if (TargetDeviceOffloadKind == Action::OFK_HIP) {
  3693. if (UI.DependentOffloadKind == Action::OFK_Host)
  3694. Arch = StringRef();
  3695. else
  3696. Arch = UI.DependentBoundArch;
  3697. } else
  3698. Arch = BoundArch;
  3699. CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
  3700. UI.DependentOffloadKind)}] =
  3701. CurI;
  3702. }
  3703. // Now that we have all the results generated, select the one that should be
  3704. // returned for the current depending action.
  3705. std::pair<const Action *, std::string> ActionTC = {
  3706. A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
  3707. assert(CachedResults.find(ActionTC) != CachedResults.end() &&
  3708. "Result does not exist??");
  3709. Result = CachedResults[ActionTC];
  3710. } else if (JA->getType() == types::TY_Nothing)
  3711. Result = InputInfo(A, BaseInput);
  3712. else {
  3713. // We only have to generate a prefix for the host if this is not a top-level
  3714. // action.
  3715. std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
  3716. A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
  3717. /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
  3718. !AtTopLevel);
  3719. if (isa<OffloadWrapperJobAction>(JA)) {
  3720. OffloadingPrefix += "-wrapper";
  3721. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
  3722. BaseInput = FinalOutput->getValue();
  3723. else
  3724. BaseInput = getDefaultImageName();
  3725. }
  3726. Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
  3727. AtTopLevel, MultipleArchs,
  3728. OffloadingPrefix),
  3729. BaseInput);
  3730. }
  3731. if (CCCPrintBindings && !CCGenDiagnostics) {
  3732. llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
  3733. << " - \"" << T->getName() << "\", inputs: [";
  3734. for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
  3735. llvm::errs() << InputInfos[i].getAsString();
  3736. if (i + 1 != e)
  3737. llvm::errs() << ", ";
  3738. }
  3739. if (UnbundlingResults.empty())
  3740. llvm::errs() << "], output: " << Result.getAsString() << "\n";
  3741. else {
  3742. llvm::errs() << "], outputs: [";
  3743. for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
  3744. llvm::errs() << UnbundlingResults[i].getAsString();
  3745. if (i + 1 != e)
  3746. llvm::errs() << ", ";
  3747. }
  3748. llvm::errs() << "] \n";
  3749. }
  3750. } else {
  3751. if (UnbundlingResults.empty())
  3752. T->ConstructJob(
  3753. C, *JA, Result, InputInfos,
  3754. C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
  3755. LinkingOutput);
  3756. else
  3757. T->ConstructJobMultipleOutputs(
  3758. C, *JA, UnbundlingResults, InputInfos,
  3759. C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
  3760. LinkingOutput);
  3761. }
  3762. return Result;
  3763. }
  3764. const char *Driver::getDefaultImageName() const {
  3765. llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
  3766. return Target.isOSWindows() ? "a.exe" : "a.out";
  3767. }
  3768. /// Create output filename based on ArgValue, which could either be a
  3769. /// full filename, filename without extension, or a directory. If ArgValue
  3770. /// does not provide a filename, then use BaseName, and use the extension
  3771. /// suitable for FileType.
  3772. static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
  3773. StringRef BaseName,
  3774. types::ID FileType) {
  3775. SmallString<128> Filename = ArgValue;
  3776. if (ArgValue.empty()) {
  3777. // If the argument is empty, output to BaseName in the current dir.
  3778. Filename = BaseName;
  3779. } else if (llvm::sys::path::is_separator(Filename.back())) {
  3780. // If the argument is a directory, output to BaseName in that dir.
  3781. llvm::sys::path::append(Filename, BaseName);
  3782. }
  3783. if (!llvm::sys::path::has_extension(ArgValue)) {
  3784. // If the argument didn't provide an extension, then set it.
  3785. const char *Extension = types::getTypeTempSuffix(FileType, true);
  3786. if (FileType == types::TY_Image &&
  3787. Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
  3788. // The output file is a dll.
  3789. Extension = "dll";
  3790. }
  3791. llvm::sys::path::replace_extension(Filename, Extension);
  3792. }
  3793. return Args.MakeArgString(Filename.c_str());
  3794. }
  3795. const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
  3796. const char *BaseInput,
  3797. StringRef BoundArch, bool AtTopLevel,
  3798. bool MultipleArchs,
  3799. StringRef OffloadingPrefix) const {
  3800. llvm::PrettyStackTraceString CrashInfo("Computing output path");
  3801. // Output to a user requested destination?
  3802. if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
  3803. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
  3804. return C.addResultFile(FinalOutput->getValue(), &JA);
  3805. }
  3806. // For /P, preprocess to file named after BaseInput.
  3807. if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
  3808. assert(AtTopLevel && isa<PreprocessJobAction>(JA));
  3809. StringRef BaseName = llvm::sys::path::filename(BaseInput);
  3810. StringRef NameArg;
  3811. if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
  3812. NameArg = A->getValue();
  3813. return C.addResultFile(
  3814. MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
  3815. &JA);
  3816. }
  3817. // Default to writing to stdout?
  3818. if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
  3819. return "-";
  3820. // Is this the assembly listing for /FA?
  3821. if (JA.getType() == types::TY_PP_Asm &&
  3822. (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
  3823. C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
  3824. // Use /Fa and the input filename to determine the asm file name.
  3825. StringRef BaseName = llvm::sys::path::filename(BaseInput);
  3826. StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
  3827. return C.addResultFile(
  3828. MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
  3829. &JA);
  3830. }
  3831. // Output to a temporary file?
  3832. if ((!AtTopLevel && !isSaveTempsEnabled() &&
  3833. !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
  3834. CCGenDiagnostics) {
  3835. StringRef Name = llvm::sys::path::filename(BaseInput);
  3836. std::pair<StringRef, StringRef> Split = Name.split('.');
  3837. SmallString<128> TmpName;
  3838. const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
  3839. Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
  3840. if (CCGenDiagnostics && A) {
  3841. SmallString<128> CrashDirectory(A->getValue());
  3842. if (!getVFS().exists(CrashDirectory))
  3843. llvm::sys::fs::create_directories(CrashDirectory);
  3844. llvm::sys::path::append(CrashDirectory, Split.first);
  3845. const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
  3846. std::error_code EC = llvm::sys::fs::createUniqueFile(
  3847. CrashDirectory + Middle + Suffix, TmpName);
  3848. if (EC) {
  3849. Diag(clang::diag::err_unable_to_make_temp) << EC.message();
  3850. return "";
  3851. }
  3852. } else {
  3853. TmpName = GetTemporaryPath(Split.first, Suffix);
  3854. }
  3855. return C.addTempFile(C.getArgs().MakeArgString(TmpName));
  3856. }
  3857. SmallString<128> BasePath(BaseInput);
  3858. StringRef BaseName;
  3859. // Dsymutil actions should use the full path.
  3860. if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
  3861. BaseName = BasePath;
  3862. else
  3863. BaseName = llvm::sys::path::filename(BasePath);
  3864. // Determine what the derived output name should be.
  3865. const char *NamedOutput;
  3866. if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
  3867. C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
  3868. // The /Fo or /o flag decides the object filename.
  3869. StringRef Val =
  3870. C.getArgs()
  3871. .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
  3872. ->getValue();
  3873. NamedOutput =
  3874. MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
  3875. } else if (JA.getType() == types::TY_Image &&
  3876. C.getArgs().hasArg(options::OPT__SLASH_Fe,
  3877. options::OPT__SLASH_o)) {
  3878. // The /Fe or /o flag names the linked file.
  3879. StringRef Val =
  3880. C.getArgs()
  3881. .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
  3882. ->getValue();
  3883. NamedOutput =
  3884. MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
  3885. } else if (JA.getType() == types::TY_Image) {
  3886. if (IsCLMode()) {
  3887. // clang-cl uses BaseName for the executable name.
  3888. NamedOutput =
  3889. MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
  3890. } else {
  3891. SmallString<128> Output(getDefaultImageName());
  3892. // HIP image for device compilation with -fno-gpu-rdc is per compilation
  3893. // unit.
  3894. bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
  3895. !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
  3896. options::OPT_fno_gpu_rdc, false);
  3897. if (IsHIPNoRDC) {
  3898. Output = BaseName;
  3899. llvm::sys::path::replace_extension(Output, "");
  3900. }
  3901. Output += OffloadingPrefix;
  3902. if (MultipleArchs && !BoundArch.empty()) {
  3903. Output += "-";
  3904. Output.append(BoundArch);
  3905. }
  3906. if (IsHIPNoRDC)
  3907. Output += ".out";
  3908. NamedOutput = C.getArgs().MakeArgString(Output.c_str());
  3909. }
  3910. } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
  3911. NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
  3912. } else {
  3913. const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
  3914. assert(Suffix && "All types used for output should have a suffix.");
  3915. std::string::size_type End = std::string::npos;
  3916. if (!types::appendSuffixForType(JA.getType()))
  3917. End = BaseName.rfind('.');
  3918. SmallString<128> Suffixed(BaseName.substr(0, End));
  3919. Suffixed += OffloadingPrefix;
  3920. if (MultipleArchs && !BoundArch.empty()) {
  3921. Suffixed += "-";
  3922. Suffixed.append(BoundArch);
  3923. }
  3924. // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
  3925. // the unoptimized bitcode so that it does not get overwritten by the ".bc"
  3926. // optimized bitcode output.
  3927. if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
  3928. JA.getType() == types::TY_LLVM_BC)
  3929. Suffixed += ".tmp";
  3930. Suffixed += '.';
  3931. Suffixed += Suffix;
  3932. NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
  3933. }
  3934. // Prepend object file path if -save-temps=obj
  3935. if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
  3936. JA.getType() != types::TY_PCH) {
  3937. Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
  3938. SmallString<128> TempPath(FinalOutput->getValue());
  3939. llvm::sys::path::remove_filename(TempPath);
  3940. StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
  3941. llvm::sys::path::append(TempPath, OutputFileName);
  3942. NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
  3943. }
  3944. // If we're saving temps and the temp file conflicts with the input file,
  3945. // then avoid overwriting input file.
  3946. if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
  3947. bool SameFile = false;
  3948. SmallString<256> Result;
  3949. llvm::sys::fs::current_path(Result);
  3950. llvm::sys::path::append(Result, BaseName);
  3951. llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
  3952. // Must share the same path to conflict.
  3953. if (SameFile) {
  3954. StringRef Name = llvm::sys::path::filename(BaseInput);
  3955. std::pair<StringRef, StringRef> Split = Name.split('.');
  3956. std::string TmpName = GetTemporaryPath(
  3957. Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
  3958. return C.addTempFile(C.getArgs().MakeArgString(TmpName));
  3959. }
  3960. }
  3961. // As an annoying special case, PCH generation doesn't strip the pathname.
  3962. if (JA.getType() == types::TY_PCH && !IsCLMode()) {
  3963. llvm::sys::path::remove_filename(BasePath);
  3964. if (BasePath.empty())
  3965. BasePath = NamedOutput;
  3966. else
  3967. llvm::sys::path::append(BasePath, NamedOutput);
  3968. return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
  3969. } else {
  3970. return C.addResultFile(NamedOutput, &JA);
  3971. }
  3972. }
  3973. std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
  3974. // Search for Name in a list of paths.
  3975. auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
  3976. -> llvm::Optional<std::string> {
  3977. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  3978. // attempting to use this prefix when looking for file paths.
  3979. for (const auto &Dir : P) {
  3980. if (Dir.empty())
  3981. continue;
  3982. SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
  3983. llvm::sys::path::append(P, Name);
  3984. if (llvm::sys::fs::exists(Twine(P)))
  3985. return P.str().str();
  3986. }
  3987. return None;
  3988. };
  3989. if (auto P = SearchPaths(PrefixDirs))
  3990. return *P;
  3991. SmallString<128> R(ResourceDir);
  3992. llvm::sys::path::append(R, Name);
  3993. if (llvm::sys::fs::exists(Twine(R)))
  3994. return R.str();
  3995. SmallString<128> P(TC.getCompilerRTPath());
  3996. llvm::sys::path::append(P, Name);
  3997. if (llvm::sys::fs::exists(Twine(P)))
  3998. return P.str();
  3999. SmallString<128> D(Dir);
  4000. llvm::sys::path::append(D, "..", Name);
  4001. if (llvm::sys::fs::exists(Twine(D)))
  4002. return D.str();
  4003. if (auto P = SearchPaths(TC.getLibraryPaths()))
  4004. return *P;
  4005. if (auto P = SearchPaths(TC.getFilePaths()))
  4006. return *P;
  4007. return Name;
  4008. }
  4009. void Driver::generatePrefixedToolNames(
  4010. StringRef Tool, const ToolChain &TC,
  4011. SmallVectorImpl<std::string> &Names) const {
  4012. // FIXME: Needs a better variable than TargetTriple
  4013. Names.emplace_back((TargetTriple + "-" + Tool).str());
  4014. Names.emplace_back(Tool);
  4015. // Allow the discovery of tools prefixed with LLVM's default target triple.
  4016. std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
  4017. if (DefaultTargetTriple != TargetTriple)
  4018. Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
  4019. }
  4020. static bool ScanDirForExecutable(SmallString<128> &Dir,
  4021. ArrayRef<std::string> Names) {
  4022. for (const auto &Name : Names) {
  4023. llvm::sys::path::append(Dir, Name);
  4024. if (llvm::sys::fs::can_execute(Twine(Dir)))
  4025. return true;
  4026. llvm::sys::path::remove_filename(Dir);
  4027. }
  4028. return false;
  4029. }
  4030. std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
  4031. SmallVector<std::string, 2> TargetSpecificExecutables;
  4032. generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
  4033. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  4034. // attempting to use this prefix when looking for program paths.
  4035. for (const auto &PrefixDir : PrefixDirs) {
  4036. if (llvm::sys::fs::is_directory(PrefixDir)) {
  4037. SmallString<128> P(PrefixDir);
  4038. if (ScanDirForExecutable(P, TargetSpecificExecutables))
  4039. return P.str();
  4040. } else {
  4041. SmallString<128> P((PrefixDir + Name).str());
  4042. if (llvm::sys::fs::can_execute(Twine(P)))
  4043. return P.str();
  4044. }
  4045. }
  4046. const ToolChain::path_list &List = TC.getProgramPaths();
  4047. for (const auto &Path : List) {
  4048. SmallString<128> P(Path);
  4049. if (ScanDirForExecutable(P, TargetSpecificExecutables))
  4050. return P.str();
  4051. }
  4052. // If all else failed, search the path.
  4053. for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
  4054. if (llvm::ErrorOr<std::string> P =
  4055. llvm::sys::findProgramByName(TargetSpecificExecutable))
  4056. return *P;
  4057. return Name;
  4058. }
  4059. std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
  4060. SmallString<128> Path;
  4061. std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
  4062. if (EC) {
  4063. Diag(clang::diag::err_unable_to_make_temp) << EC.message();
  4064. return "";
  4065. }
  4066. return Path.str();
  4067. }
  4068. std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
  4069. SmallString<128> Path;
  4070. std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
  4071. if (EC) {
  4072. Diag(clang::diag::err_unable_to_make_temp) << EC.message();
  4073. return "";
  4074. }
  4075. return Path.str();
  4076. }
  4077. std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
  4078. SmallString<128> Output;
  4079. if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
  4080. // FIXME: If anybody needs it, implement this obscure rule:
  4081. // "If you specify a directory without a file name, the default file name
  4082. // is VCx0.pch., where x is the major version of Visual C++ in use."
  4083. Output = FpArg->getValue();
  4084. // "If you do not specify an extension as part of the path name, an
  4085. // extension of .pch is assumed. "
  4086. if (!llvm::sys::path::has_extension(Output))
  4087. Output += ".pch";
  4088. } else {
  4089. if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
  4090. Output = YcArg->getValue();
  4091. if (Output.empty())
  4092. Output = BaseName;
  4093. llvm::sys::path::replace_extension(Output, ".pch");
  4094. }
  4095. return Output.str();
  4096. }
  4097. const ToolChain &Driver::getToolChain(const ArgList &Args,
  4098. const llvm::Triple &Target) const {
  4099. auto &TC = ToolChains[Target.str()];
  4100. if (!TC) {
  4101. switch (Target.getOS()) {
  4102. case llvm::Triple::Haiku:
  4103. TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
  4104. break;
  4105. case llvm::Triple::Ananas:
  4106. TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
  4107. break;
  4108. case llvm::Triple::CloudABI:
  4109. TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
  4110. break;
  4111. case llvm::Triple::Darwin:
  4112. case llvm::Triple::MacOSX:
  4113. case llvm::Triple::IOS:
  4114. case llvm::Triple::TvOS:
  4115. case llvm::Triple::WatchOS:
  4116. TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
  4117. break;
  4118. case llvm::Triple::DragonFly:
  4119. TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
  4120. break;
  4121. case llvm::Triple::OpenBSD:
  4122. TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
  4123. break;
  4124. case llvm::Triple::NetBSD:
  4125. TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
  4126. break;
  4127. case llvm::Triple::FreeBSD:
  4128. TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
  4129. break;
  4130. case llvm::Triple::Minix:
  4131. TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
  4132. break;
  4133. case llvm::Triple::Linux:
  4134. case llvm::Triple::ELFIAMCU:
  4135. if (Target.getArch() == llvm::Triple::hexagon)
  4136. TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
  4137. Args);
  4138. else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
  4139. !Target.hasEnvironment())
  4140. TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
  4141. Args);
  4142. else if (Target.getArch() == llvm::Triple::ppc ||
  4143. Target.getArch() == llvm::Triple::ppc64 ||
  4144. Target.getArch() == llvm::Triple::ppc64le)
  4145. TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
  4146. Args);
  4147. else
  4148. TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
  4149. break;
  4150. case llvm::Triple::NaCl:
  4151. TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
  4152. break;
  4153. case llvm::Triple::Fuchsia:
  4154. TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
  4155. break;
  4156. case llvm::Triple::Solaris:
  4157. TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
  4158. break;
  4159. case llvm::Triple::AMDHSA:
  4160. case llvm::Triple::AMDPAL:
  4161. case llvm::Triple::Mesa3D:
  4162. TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
  4163. break;
  4164. case llvm::Triple::Win32:
  4165. switch (Target.getEnvironment()) {
  4166. default:
  4167. if (Target.isOSBinFormatELF())
  4168. TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
  4169. else if (Target.isOSBinFormatMachO())
  4170. TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
  4171. else
  4172. TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
  4173. break;
  4174. case llvm::Triple::GNU:
  4175. TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
  4176. break;
  4177. case llvm::Triple::Itanium:
  4178. TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
  4179. Args);
  4180. break;
  4181. case llvm::Triple::MSVC:
  4182. case llvm::Triple::UnknownEnvironment:
  4183. if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
  4184. .startswith_lower("bfd"))
  4185. TC = std::make_unique<toolchains::CrossWindowsToolChain>(
  4186. *this, Target, Args);
  4187. else
  4188. TC =
  4189. std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
  4190. break;
  4191. }
  4192. break;
  4193. case llvm::Triple::PS4:
  4194. TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
  4195. break;
  4196. case llvm::Triple::Contiki:
  4197. TC = std::make_unique<toolchains::Contiki>(*this, Target, Args);
  4198. break;
  4199. case llvm::Triple::Hurd:
  4200. TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
  4201. break;
  4202. default:
  4203. // Of these targets, Hexagon is the only one that might have
  4204. // an OS of Linux, in which case it got handled above already.
  4205. switch (Target.getArch()) {
  4206. case llvm::Triple::tce:
  4207. TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
  4208. break;
  4209. case llvm::Triple::tcele:
  4210. TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
  4211. break;
  4212. case llvm::Triple::hexagon:
  4213. TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
  4214. Args);
  4215. break;
  4216. case llvm::Triple::lanai:
  4217. TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
  4218. break;
  4219. case llvm::Triple::xcore:
  4220. TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
  4221. break;
  4222. case llvm::Triple::wasm32:
  4223. case llvm::Triple::wasm64:
  4224. TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
  4225. break;
  4226. case llvm::Triple::avr:
  4227. TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
  4228. break;
  4229. case llvm::Triple::msp430:
  4230. TC =
  4231. std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
  4232. break;
  4233. case llvm::Triple::riscv32:
  4234. case llvm::Triple::riscv64:
  4235. TC = std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
  4236. break;
  4237. default:
  4238. if (Target.getVendor() == llvm::Triple::Myriad)
  4239. TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target,
  4240. Args);
  4241. else if (toolchains::BareMetal::handlesTarget(Target))
  4242. TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
  4243. else if (Target.isOSBinFormatELF())
  4244. TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
  4245. else if (Target.isOSBinFormatMachO())
  4246. TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
  4247. else
  4248. TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
  4249. }
  4250. }
  4251. }
  4252. // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
  4253. // compiles always need two toolchains, the CUDA toolchain and the host
  4254. // toolchain. So the only valid way to create a CUDA toolchain is via
  4255. // CreateOffloadingDeviceToolChains.
  4256. return *TC;
  4257. }
  4258. bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
  4259. // Say "no" if there is not exactly one input of a type clang understands.
  4260. if (JA.size() != 1 ||
  4261. !types::isAcceptedByClang((*JA.input_begin())->getType()))
  4262. return false;
  4263. // And say "no" if this is not a kind of action clang understands.
  4264. if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
  4265. !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
  4266. return false;
  4267. return true;
  4268. }
  4269. /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
  4270. /// grouped values as integers. Numbers which are not provided are set to 0.
  4271. ///
  4272. /// \return True if the entire string was parsed (9.2), or all groups were
  4273. /// parsed (10.3.5extrastuff).
  4274. bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
  4275. unsigned &Micro, bool &HadExtra) {
  4276. HadExtra = false;
  4277. Major = Minor = Micro = 0;
  4278. if (Str.empty())
  4279. return false;
  4280. if (Str.consumeInteger(10, Major))
  4281. return false;
  4282. if (Str.empty())
  4283. return true;
  4284. if (Str[0] != '.')
  4285. return false;
  4286. Str = Str.drop_front(1);
  4287. if (Str.consumeInteger(10, Minor))
  4288. return false;
  4289. if (Str.empty())
  4290. return true;
  4291. if (Str[0] != '.')
  4292. return false;
  4293. Str = Str.drop_front(1);
  4294. if (Str.consumeInteger(10, Micro))
  4295. return false;
  4296. if (!Str.empty())
  4297. HadExtra = true;
  4298. return true;
  4299. }
  4300. /// Parse digits from a string \p Str and fulfill \p Digits with
  4301. /// the parsed numbers. This method assumes that the max number of
  4302. /// digits to look for is equal to Digits.size().
  4303. ///
  4304. /// \return True if the entire string was parsed and there are
  4305. /// no extra characters remaining at the end.
  4306. bool Driver::GetReleaseVersion(StringRef Str,
  4307. MutableArrayRef<unsigned> Digits) {
  4308. if (Str.empty())
  4309. return false;
  4310. unsigned CurDigit = 0;
  4311. while (CurDigit < Digits.size()) {
  4312. unsigned Digit;
  4313. if (Str.consumeInteger(10, Digit))
  4314. return false;
  4315. Digits[CurDigit] = Digit;
  4316. if (Str.empty())
  4317. return true;
  4318. if (Str[0] != '.')
  4319. return false;
  4320. Str = Str.drop_front(1);
  4321. CurDigit++;
  4322. }
  4323. // More digits than requested, bail out...
  4324. return false;
  4325. }
  4326. std::pair<unsigned, unsigned>
  4327. Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
  4328. unsigned IncludedFlagsBitmask = 0;
  4329. unsigned ExcludedFlagsBitmask = options::NoDriverOption;
  4330. if (IsClCompatMode) {
  4331. // Include CL and Core options.
  4332. IncludedFlagsBitmask |= options::CLOption;
  4333. IncludedFlagsBitmask |= options::CoreOption;
  4334. } else {
  4335. ExcludedFlagsBitmask |= options::CLOption;
  4336. }
  4337. return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
  4338. }
  4339. bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
  4340. return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
  4341. }