Driver.cpp 185 KB

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