Driver.cpp 183 KB

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