Driver.cpp 181 KB

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