CodeGenModule.cpp 208 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
  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. //
  9. // This coordinates the per-module state used while generating code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenModule.h"
  13. #include "CGBlocks.h"
  14. #include "CGCUDARuntime.h"
  15. #include "CGCXXABI.h"
  16. #include "CGCall.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGObjCRuntime.h"
  19. #include "CGOpenCLRuntime.h"
  20. #include "CGOpenMPRuntime.h"
  21. #include "CGOpenMPRuntimeNVPTX.h"
  22. #include "CodeGenFunction.h"
  23. #include "CodeGenPGO.h"
  24. #include "ConstantEmitter.h"
  25. #include "CoverageMappingGen.h"
  26. #include "TargetInfo.h"
  27. #include "clang/AST/ASTContext.h"
  28. #include "clang/AST/CharUnits.h"
  29. #include "clang/AST/DeclCXX.h"
  30. #include "clang/AST/DeclObjC.h"
  31. #include "clang/AST/DeclTemplate.h"
  32. #include "clang/AST/Mangle.h"
  33. #include "clang/AST/RecordLayout.h"
  34. #include "clang/AST/RecursiveASTVisitor.h"
  35. #include "clang/AST/StmtVisitor.h"
  36. #include "clang/Basic/Builtins.h"
  37. #include "clang/Basic/CharInfo.h"
  38. #include "clang/Basic/CodeGenOptions.h"
  39. #include "clang/Basic/Diagnostic.h"
  40. #include "clang/Basic/Module.h"
  41. #include "clang/Basic/SourceManager.h"
  42. #include "clang/Basic/TargetInfo.h"
  43. #include "clang/Basic/Version.h"
  44. #include "clang/CodeGen/ConstantInitBuilder.h"
  45. #include "clang/Frontend/FrontendDiagnostic.h"
  46. #include "llvm/ADT/StringSwitch.h"
  47. #include "llvm/ADT/Triple.h"
  48. #include "llvm/Analysis/TargetLibraryInfo.h"
  49. #include "llvm/IR/CallingConv.h"
  50. #include "llvm/IR/DataLayout.h"
  51. #include "llvm/IR/Intrinsics.h"
  52. #include "llvm/IR/LLVMContext.h"
  53. #include "llvm/IR/Module.h"
  54. #include "llvm/ProfileData/InstrProfReader.h"
  55. #include "llvm/Support/CodeGen.h"
  56. #include "llvm/Support/ConvertUTF.h"
  57. #include "llvm/Support/ErrorHandling.h"
  58. #include "llvm/Support/MD5.h"
  59. using namespace clang;
  60. using namespace CodeGen;
  61. static llvm::cl::opt<bool> LimitedCoverage(
  62. "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
  63. llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
  64. llvm::cl::init(false));
  65. static const char AnnotationSection[] = "llvm.metadata";
  66. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  67. switch (CGM.getTarget().getCXXABI().getKind()) {
  68. case TargetCXXABI::GenericAArch64:
  69. case TargetCXXABI::GenericARM:
  70. case TargetCXXABI::iOS:
  71. case TargetCXXABI::iOS64:
  72. case TargetCXXABI::WatchOS:
  73. case TargetCXXABI::GenericMIPS:
  74. case TargetCXXABI::GenericItanium:
  75. case TargetCXXABI::WebAssembly:
  76. return CreateItaniumCXXABI(CGM);
  77. case TargetCXXABI::Microsoft:
  78. return CreateMicrosoftCXXABI(CGM);
  79. }
  80. llvm_unreachable("invalid C++ ABI kind");
  81. }
  82. CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
  83. const PreprocessorOptions &PPO,
  84. const CodeGenOptions &CGO, llvm::Module &M,
  85. DiagnosticsEngine &diags,
  86. CoverageSourceInfo *CoverageInfo)
  87. : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
  88. PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
  89. Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
  90. VMContext(M.getContext()), Types(*this), VTables(*this),
  91. SanitizerMD(new SanitizerMetadata(*this)) {
  92. // Initialize the type cache.
  93. llvm::LLVMContext &LLVMContext = M.getContext();
  94. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  95. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  96. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  97. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  98. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  99. HalfTy = llvm::Type::getHalfTy(LLVMContext);
  100. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  101. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  102. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  103. PointerAlignInBytes =
  104. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  105. SizeSizeInBytes =
  106. C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
  107. IntAlignInBytes =
  108. C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
  109. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  110. IntPtrTy = llvm::IntegerType::get(LLVMContext,
  111. C.getTargetInfo().getMaxPointerWidth());
  112. Int8PtrTy = Int8Ty->getPointerTo(0);
  113. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  114. AllocaInt8PtrTy = Int8Ty->getPointerTo(
  115. M.getDataLayout().getAllocaAddrSpace());
  116. ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
  117. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  118. if (LangOpts.ObjC)
  119. createObjCRuntime();
  120. if (LangOpts.OpenCL)
  121. createOpenCLRuntime();
  122. if (LangOpts.OpenMP)
  123. createOpenMPRuntime();
  124. if (LangOpts.CUDA)
  125. createCUDARuntime();
  126. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  127. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  128. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  129. TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
  130. getCXXABI().getMangleContext()));
  131. // If debug info or coverage generation is enabled, create the CGDebugInfo
  132. // object.
  133. if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
  134. CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
  135. DebugInfo.reset(new CGDebugInfo(*this));
  136. Block.GlobalUniqueCount = 0;
  137. if (C.getLangOpts().ObjC)
  138. ObjCData.reset(new ObjCEntrypoints());
  139. if (CodeGenOpts.hasProfileClangUse()) {
  140. auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
  141. CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
  142. if (auto E = ReaderOrErr.takeError()) {
  143. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  144. "Could not read profile %0: %1");
  145. llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
  146. getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
  147. << EI.message();
  148. });
  149. } else
  150. PGOReader = std::move(ReaderOrErr.get());
  151. }
  152. // If coverage mapping generation is enabled, create the
  153. // CoverageMappingModuleGen object.
  154. if (CodeGenOpts.CoverageMapping)
  155. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  156. }
  157. CodeGenModule::~CodeGenModule() {}
  158. void CodeGenModule::createObjCRuntime() {
  159. // This is just isGNUFamily(), but we want to force implementors of
  160. // new ABIs to decide how best to do this.
  161. switch (LangOpts.ObjCRuntime.getKind()) {
  162. case ObjCRuntime::GNUstep:
  163. case ObjCRuntime::GCC:
  164. case ObjCRuntime::ObjFW:
  165. ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
  166. return;
  167. case ObjCRuntime::FragileMacOSX:
  168. case ObjCRuntime::MacOSX:
  169. case ObjCRuntime::iOS:
  170. case ObjCRuntime::WatchOS:
  171. ObjCRuntime.reset(CreateMacObjCRuntime(*this));
  172. return;
  173. }
  174. llvm_unreachable("bad runtime kind");
  175. }
  176. void CodeGenModule::createOpenCLRuntime() {
  177. OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
  178. }
  179. void CodeGenModule::createOpenMPRuntime() {
  180. // Select a specialized code generation class based on the target, if any.
  181. // If it does not exist use the default implementation.
  182. switch (getTriple().getArch()) {
  183. case llvm::Triple::nvptx:
  184. case llvm::Triple::nvptx64:
  185. assert(getLangOpts().OpenMPIsDevice &&
  186. "OpenMP NVPTX is only prepared to deal with device code.");
  187. OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
  188. break;
  189. default:
  190. if (LangOpts.OpenMPSimd)
  191. OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
  192. else
  193. OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
  194. break;
  195. }
  196. }
  197. void CodeGenModule::createCUDARuntime() {
  198. CUDARuntime.reset(CreateNVCUDARuntime(*this));
  199. }
  200. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  201. Replacements[Name] = C;
  202. }
  203. void CodeGenModule::applyReplacements() {
  204. for (auto &I : Replacements) {
  205. StringRef MangledName = I.first();
  206. llvm::Constant *Replacement = I.second;
  207. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  208. if (!Entry)
  209. continue;
  210. auto *OldF = cast<llvm::Function>(Entry);
  211. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  212. if (!NewF) {
  213. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  214. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  215. } else {
  216. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  217. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  218. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  219. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  220. }
  221. }
  222. // Replace old with new, but keep the old order.
  223. OldF->replaceAllUsesWith(Replacement);
  224. if (NewF) {
  225. NewF->removeFromParent();
  226. OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
  227. NewF);
  228. }
  229. OldF->eraseFromParent();
  230. }
  231. }
  232. void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
  233. GlobalValReplacements.push_back(std::make_pair(GV, C));
  234. }
  235. void CodeGenModule::applyGlobalValReplacements() {
  236. for (auto &I : GlobalValReplacements) {
  237. llvm::GlobalValue *GV = I.first;
  238. llvm::Constant *C = I.second;
  239. GV->replaceAllUsesWith(C);
  240. GV->eraseFromParent();
  241. }
  242. }
  243. // This is only used in aliases that we created and we know they have a
  244. // linear structure.
  245. static const llvm::GlobalObject *getAliasedGlobal(
  246. const llvm::GlobalIndirectSymbol &GIS) {
  247. llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
  248. const llvm::Constant *C = &GIS;
  249. for (;;) {
  250. C = C->stripPointerCasts();
  251. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  252. return GO;
  253. // stripPointerCasts will not walk over weak aliases.
  254. auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
  255. if (!GIS2)
  256. return nullptr;
  257. if (!Visited.insert(GIS2).second)
  258. return nullptr;
  259. C = GIS2->getIndirectSymbol();
  260. }
  261. }
  262. void CodeGenModule::checkAliases() {
  263. // Check if the constructed aliases are well formed. It is really unfortunate
  264. // that we have to do this in CodeGen, but we only construct mangled names
  265. // and aliases during codegen.
  266. bool Error = false;
  267. DiagnosticsEngine &Diags = getDiags();
  268. for (const GlobalDecl &GD : Aliases) {
  269. const auto *D = cast<ValueDecl>(GD.getDecl());
  270. SourceLocation Location;
  271. bool IsIFunc = D->hasAttr<IFuncAttr>();
  272. if (const Attr *A = D->getDefiningAttr())
  273. Location = A->getLocation();
  274. else
  275. llvm_unreachable("Not an alias or ifunc?");
  276. StringRef MangledName = getMangledName(GD);
  277. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  278. auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
  279. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  280. if (!GV) {
  281. Error = true;
  282. Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
  283. } else if (GV->isDeclaration()) {
  284. Error = true;
  285. Diags.Report(Location, diag::err_alias_to_undefined)
  286. << IsIFunc << IsIFunc;
  287. } else if (IsIFunc) {
  288. // Check resolver function type.
  289. llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
  290. GV->getType()->getPointerElementType());
  291. assert(FTy);
  292. if (!FTy->getReturnType()->isPointerTy())
  293. Diags.Report(Location, diag::err_ifunc_resolver_return);
  294. }
  295. llvm::Constant *Aliasee = Alias->getIndirectSymbol();
  296. llvm::GlobalValue *AliaseeGV;
  297. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  298. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  299. else
  300. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  301. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  302. StringRef AliasSection = SA->getName();
  303. if (AliasSection != AliaseeGV->getSection())
  304. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  305. << AliasSection << IsIFunc << IsIFunc;
  306. }
  307. // We have to handle alias to weak aliases in here. LLVM itself disallows
  308. // this since the object semantics would not match the IL one. For
  309. // compatibility with gcc we implement it by just pointing the alias
  310. // to its aliasee's aliasee. We also warn, since the user is probably
  311. // expecting the link to be weak.
  312. if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
  313. if (GA->isInterposable()) {
  314. Diags.Report(Location, diag::warn_alias_to_weak_alias)
  315. << GV->getName() << GA->getName() << IsIFunc;
  316. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  317. GA->getIndirectSymbol(), Alias->getType());
  318. Alias->setIndirectSymbol(Aliasee);
  319. }
  320. }
  321. }
  322. if (!Error)
  323. return;
  324. for (const GlobalDecl &GD : Aliases) {
  325. StringRef MangledName = getMangledName(GD);
  326. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  327. auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
  328. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  329. Alias->eraseFromParent();
  330. }
  331. }
  332. void CodeGenModule::clear() {
  333. DeferredDeclsToEmit.clear();
  334. if (OpenMPRuntime)
  335. OpenMPRuntime->clear();
  336. }
  337. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  338. StringRef MainFile) {
  339. if (!hasDiagnostics())
  340. return;
  341. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  342. if (MainFile.empty())
  343. MainFile = "<stdin>";
  344. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  345. } else {
  346. if (Mismatched > 0)
  347. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
  348. if (Missing > 0)
  349. Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
  350. }
  351. }
  352. void CodeGenModule::Release() {
  353. EmitDeferred();
  354. EmitVTablesOpportunistically();
  355. applyGlobalValReplacements();
  356. applyReplacements();
  357. checkAliases();
  358. emitMultiVersionFunctions();
  359. EmitCXXGlobalInitFunc();
  360. EmitCXXGlobalDtorFunc();
  361. registerGlobalDtorsWithAtExit();
  362. EmitCXXThreadLocalInitFunc();
  363. if (ObjCRuntime)
  364. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  365. AddGlobalCtor(ObjCInitFunction);
  366. if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
  367. CUDARuntime) {
  368. if (llvm::Function *CudaCtorFunction =
  369. CUDARuntime->makeModuleCtorFunction())
  370. AddGlobalCtor(CudaCtorFunction);
  371. }
  372. if (OpenMPRuntime) {
  373. if (llvm::Function *OpenMPRegistrationFunction =
  374. OpenMPRuntime->emitRegistrationFunction()) {
  375. auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
  376. OpenMPRegistrationFunction : nullptr;
  377. AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
  378. }
  379. OpenMPRuntime->clear();
  380. }
  381. if (PGOReader) {
  382. getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
  383. if (PGOStats.hasDiagnostics())
  384. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  385. }
  386. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  387. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  388. EmitGlobalAnnotations();
  389. EmitStaticExternCAliases();
  390. EmitDeferredUnusedCoverageMappings();
  391. if (CoverageMapping)
  392. CoverageMapping->emit();
  393. if (CodeGenOpts.SanitizeCfiCrossDso) {
  394. CodeGenFunction(*this).EmitCfiCheckFail();
  395. CodeGenFunction(*this).EmitCfiCheckStub();
  396. }
  397. emitAtAvailableLinkGuard();
  398. emitLLVMUsed();
  399. if (SanStats)
  400. SanStats->finish();
  401. if (CodeGenOpts.Autolink &&
  402. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  403. EmitModuleLinkOptions();
  404. }
  405. // Record mregparm value now so it is visible through rest of codegen.
  406. if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
  407. getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
  408. CodeGenOpts.NumRegisterParameters);
  409. if (CodeGenOpts.DwarfVersion) {
  410. // We actually want the latest version when there are conflicts.
  411. // We can change from Warning to Latest if such mode is supported.
  412. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  413. CodeGenOpts.DwarfVersion);
  414. }
  415. if (CodeGenOpts.EmitCodeView) {
  416. // Indicate that we want CodeView in the metadata.
  417. getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
  418. }
  419. if (CodeGenOpts.CodeViewGHash) {
  420. getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
  421. }
  422. if (CodeGenOpts.ControlFlowGuard) {
  423. // We want function ID tables for Control Flow Guard.
  424. getModule().addModuleFlag(llvm::Module::Warning, "cfguardtable", 1);
  425. }
  426. if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
  427. // We don't support LTO with 2 with different StrictVTablePointers
  428. // FIXME: we could support it by stripping all the information introduced
  429. // by StrictVTablePointers.
  430. getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
  431. llvm::Metadata *Ops[2] = {
  432. llvm::MDString::get(VMContext, "StrictVTablePointers"),
  433. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  434. llvm::Type::getInt32Ty(VMContext), 1))};
  435. getModule().addModuleFlag(llvm::Module::Require,
  436. "StrictVTablePointersRequirement",
  437. llvm::MDNode::get(VMContext, Ops));
  438. }
  439. if (DebugInfo)
  440. // We support a single version in the linked module. The LLVM
  441. // parser will drop debug info with a different version number
  442. // (and warn about it, too).
  443. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  444. llvm::DEBUG_METADATA_VERSION);
  445. // We need to record the widths of enums and wchar_t, so that we can generate
  446. // the correct build attributes in the ARM backend. wchar_size is also used by
  447. // TargetLibraryInfo.
  448. uint64_t WCharWidth =
  449. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  450. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  451. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  452. if ( Arch == llvm::Triple::arm
  453. || Arch == llvm::Triple::armeb
  454. || Arch == llvm::Triple::thumb
  455. || Arch == llvm::Triple::thumbeb) {
  456. // The minimum width of an enum in bytes
  457. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  458. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  459. }
  460. if (CodeGenOpts.SanitizeCfiCrossDso) {
  461. // Indicate that we want cross-DSO control flow integrity checks.
  462. getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
  463. }
  464. if (CodeGenOpts.CFProtectionReturn &&
  465. Target.checkCFProtectionReturnSupported(getDiags())) {
  466. // Indicate that we want to instrument return control flow protection.
  467. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
  468. 1);
  469. }
  470. if (CodeGenOpts.CFProtectionBranch &&
  471. Target.checkCFProtectionBranchSupported(getDiags())) {
  472. // Indicate that we want to instrument branch control flow protection.
  473. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
  474. 1);
  475. }
  476. if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
  477. // Indicate whether __nvvm_reflect should be configured to flush denormal
  478. // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
  479. // property.)
  480. getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
  481. CodeGenOpts.FlushDenorm ? 1 : 0);
  482. }
  483. // Emit OpenCL specific module metadata: OpenCL/SPIR version.
  484. if (LangOpts.OpenCL) {
  485. EmitOpenCLMetadata();
  486. // Emit SPIR version.
  487. if (getTriple().getArch() == llvm::Triple::spir ||
  488. getTriple().getArch() == llvm::Triple::spir64) {
  489. // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
  490. // opencl.spir.version named metadata.
  491. llvm::Metadata *SPIRVerElts[] = {
  492. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  493. Int32Ty, LangOpts.OpenCLVersion / 100)),
  494. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  495. Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
  496. llvm::NamedMDNode *SPIRVerMD =
  497. TheModule.getOrInsertNamedMetadata("opencl.spir.version");
  498. llvm::LLVMContext &Ctx = TheModule.getContext();
  499. SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
  500. }
  501. }
  502. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  503. assert(PLevel < 3 && "Invalid PIC Level");
  504. getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
  505. if (Context.getLangOpts().PIE)
  506. getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
  507. }
  508. if (getCodeGenOpts().CodeModel.size() > 0) {
  509. unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
  510. .Case("tiny", llvm::CodeModel::Tiny)
  511. .Case("small", llvm::CodeModel::Small)
  512. .Case("kernel", llvm::CodeModel::Kernel)
  513. .Case("medium", llvm::CodeModel::Medium)
  514. .Case("large", llvm::CodeModel::Large)
  515. .Default(~0u);
  516. if (CM != ~0u) {
  517. llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
  518. getModule().setCodeModel(codeModel);
  519. }
  520. }
  521. if (CodeGenOpts.NoPLT)
  522. getModule().setRtLibUseGOT();
  523. SimplifyPersonality();
  524. if (getCodeGenOpts().EmitDeclMetadata)
  525. EmitDeclMetadata();
  526. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  527. EmitCoverageFile();
  528. if (DebugInfo)
  529. DebugInfo->finalize();
  530. if (getCodeGenOpts().EmitVersionIdentMetadata)
  531. EmitVersionIdentMetadata();
  532. if (!getCodeGenOpts().RecordCommandLine.empty())
  533. EmitCommandLineMetadata();
  534. EmitTargetMetadata();
  535. }
  536. void CodeGenModule::EmitOpenCLMetadata() {
  537. // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
  538. // opencl.ocl.version named metadata node.
  539. llvm::Metadata *OCLVerElts[] = {
  540. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  541. Int32Ty, LangOpts.OpenCLVersion / 100)),
  542. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  543. Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
  544. llvm::NamedMDNode *OCLVerMD =
  545. TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
  546. llvm::LLVMContext &Ctx = TheModule.getContext();
  547. OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
  548. }
  549. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  550. // Make sure that this type is translated.
  551. Types.UpdateCompletedType(TD);
  552. }
  553. void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
  554. // Make sure that this type is translated.
  555. Types.RefreshTypeCacheForClass(RD);
  556. }
  557. llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
  558. if (!TBAA)
  559. return nullptr;
  560. return TBAA->getTypeInfo(QTy);
  561. }
  562. TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
  563. if (!TBAA)
  564. return TBAAAccessInfo();
  565. return TBAA->getAccessInfo(AccessType);
  566. }
  567. TBAAAccessInfo
  568. CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
  569. if (!TBAA)
  570. return TBAAAccessInfo();
  571. return TBAA->getVTablePtrAccessInfo(VTablePtrType);
  572. }
  573. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  574. if (!TBAA)
  575. return nullptr;
  576. return TBAA->getTBAAStructInfo(QTy);
  577. }
  578. llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
  579. if (!TBAA)
  580. return nullptr;
  581. return TBAA->getBaseTypeInfo(QTy);
  582. }
  583. llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
  584. if (!TBAA)
  585. return nullptr;
  586. return TBAA->getAccessTagInfo(Info);
  587. }
  588. TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
  589. TBAAAccessInfo TargetInfo) {
  590. if (!TBAA)
  591. return TBAAAccessInfo();
  592. return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
  593. }
  594. TBAAAccessInfo
  595. CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
  596. TBAAAccessInfo InfoB) {
  597. if (!TBAA)
  598. return TBAAAccessInfo();
  599. return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
  600. }
  601. TBAAAccessInfo
  602. CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
  603. TBAAAccessInfo SrcInfo) {
  604. if (!TBAA)
  605. return TBAAAccessInfo();
  606. return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
  607. }
  608. void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  609. TBAAAccessInfo TBAAInfo) {
  610. if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
  611. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
  612. }
  613. void CodeGenModule::DecorateInstructionWithInvariantGroup(
  614. llvm::Instruction *I, const CXXRecordDecl *RD) {
  615. I->setMetadata(llvm::LLVMContext::MD_invariant_group,
  616. llvm::MDNode::get(getLLVMContext(), {}));
  617. }
  618. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  619. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  620. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  621. }
  622. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  623. /// specified stmt yet.
  624. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  625. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  626. "cannot compile this %0 yet");
  627. std::string Msg = Type;
  628. getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
  629. << Msg << S->getSourceRange();
  630. }
  631. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  632. /// specified decl yet.
  633. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  634. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  635. "cannot compile this %0 yet");
  636. std::string Msg = Type;
  637. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  638. }
  639. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  640. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  641. }
  642. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  643. const NamedDecl *D) const {
  644. if (GV->hasDLLImportStorageClass())
  645. return;
  646. // Internal definitions always have default visibility.
  647. if (GV->hasLocalLinkage()) {
  648. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  649. return;
  650. }
  651. if (!D)
  652. return;
  653. // Set visibility for definitions, and for declarations if requested globally
  654. // or set explicitly.
  655. LinkageInfo LV = D->getLinkageAndVisibility();
  656. if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
  657. !GV->isDeclarationForLinker())
  658. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  659. }
  660. static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
  661. llvm::GlobalValue *GV) {
  662. if (GV->hasLocalLinkage())
  663. return true;
  664. if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
  665. return true;
  666. // DLLImport explicitly marks the GV as external.
  667. if (GV->hasDLLImportStorageClass())
  668. return false;
  669. const llvm::Triple &TT = CGM.getTriple();
  670. if (TT.isWindowsGNUEnvironment()) {
  671. // In MinGW, variables without DLLImport can still be automatically
  672. // imported from a DLL by the linker; don't mark variables that
  673. // potentially could come from another DLL as DSO local.
  674. if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
  675. !GV->isThreadLocal())
  676. return false;
  677. }
  678. // Every other GV is local on COFF.
  679. // Make an exception for windows OS in the triple: Some firmware builds use
  680. // *-win32-macho triples. This (accidentally?) produced windows relocations
  681. // without GOT tables in older clang versions; Keep this behaviour.
  682. // FIXME: even thread local variables?
  683. if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
  684. return true;
  685. // Only handle COFF and ELF for now.
  686. if (!TT.isOSBinFormatELF())
  687. return false;
  688. // If this is not an executable, don't assume anything is local.
  689. const auto &CGOpts = CGM.getCodeGenOpts();
  690. llvm::Reloc::Model RM = CGOpts.RelocationModel;
  691. const auto &LOpts = CGM.getLangOpts();
  692. if (RM != llvm::Reloc::Static && !LOpts.PIE)
  693. return false;
  694. // A definition cannot be preempted from an executable.
  695. if (!GV->isDeclarationForLinker())
  696. return true;
  697. // Most PIC code sequences that assume that a symbol is local cannot produce a
  698. // 0 if it turns out the symbol is undefined. While this is ABI and relocation
  699. // depended, it seems worth it to handle it here.
  700. if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
  701. return false;
  702. // PPC has no copy relocations and cannot use a plt entry as a symbol address.
  703. llvm::Triple::ArchType Arch = TT.getArch();
  704. if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  705. Arch == llvm::Triple::ppc64le)
  706. return false;
  707. // If we can use copy relocations we can assume it is local.
  708. if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
  709. if (!Var->isThreadLocal() &&
  710. (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
  711. return true;
  712. // If we can use a plt entry as the symbol address we can assume it
  713. // is local.
  714. // FIXME: This should work for PIE, but the gold linker doesn't support it.
  715. if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
  716. return true;
  717. // Otherwise don't assue it is local.
  718. return false;
  719. }
  720. void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
  721. GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
  722. }
  723. void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
  724. GlobalDecl GD) const {
  725. const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
  726. // C++ destructors have a few C++ ABI specific special cases.
  727. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
  728. getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
  729. return;
  730. }
  731. setDLLImportDLLExport(GV, D);
  732. }
  733. void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
  734. const NamedDecl *D) const {
  735. if (D && D->isExternallyVisible()) {
  736. if (D->hasAttr<DLLImportAttr>())
  737. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  738. else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
  739. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  740. }
  741. }
  742. void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
  743. GlobalDecl GD) const {
  744. setDLLImportDLLExport(GV, GD);
  745. setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
  746. }
  747. void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
  748. const NamedDecl *D) const {
  749. setDLLImportDLLExport(GV, D);
  750. setGlobalVisibilityAndLocal(GV, D);
  751. }
  752. void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
  753. const NamedDecl *D) const {
  754. setGlobalVisibility(GV, D);
  755. setDSOLocal(GV);
  756. }
  757. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  758. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  759. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  760. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  761. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  762. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  763. }
  764. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  765. CodeGenOptions::TLSModel M) {
  766. switch (M) {
  767. case CodeGenOptions::GeneralDynamicTLSModel:
  768. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  769. case CodeGenOptions::LocalDynamicTLSModel:
  770. return llvm::GlobalVariable::LocalDynamicTLSModel;
  771. case CodeGenOptions::InitialExecTLSModel:
  772. return llvm::GlobalVariable::InitialExecTLSModel;
  773. case CodeGenOptions::LocalExecTLSModel:
  774. return llvm::GlobalVariable::LocalExecTLSModel;
  775. }
  776. llvm_unreachable("Invalid TLS model!");
  777. }
  778. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  779. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  780. llvm::GlobalValue::ThreadLocalMode TLM;
  781. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  782. // Override the TLS model if it is explicitly specified.
  783. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  784. TLM = GetLLVMTLSModel(Attr->getModel());
  785. }
  786. GV->setThreadLocalMode(TLM);
  787. }
  788. static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
  789. StringRef Name) {
  790. const TargetInfo &Target = CGM.getTarget();
  791. return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
  792. }
  793. static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
  794. const CPUSpecificAttr *Attr,
  795. unsigned CPUIndex,
  796. raw_ostream &Out) {
  797. // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
  798. // supported.
  799. if (Attr)
  800. Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
  801. else if (CGM.getTarget().supportsIFunc())
  802. Out << ".resolver";
  803. }
  804. static void AppendTargetMangling(const CodeGenModule &CGM,
  805. const TargetAttr *Attr, raw_ostream &Out) {
  806. if (Attr->isDefaultVersion())
  807. return;
  808. Out << '.';
  809. const TargetInfo &Target = CGM.getTarget();
  810. TargetAttr::ParsedTargetAttr Info =
  811. Attr->parse([&Target](StringRef LHS, StringRef RHS) {
  812. // Multiversioning doesn't allow "no-${feature}", so we can
  813. // only have "+" prefixes here.
  814. assert(LHS.startswith("+") && RHS.startswith("+") &&
  815. "Features should always have a prefix.");
  816. return Target.multiVersionSortPriority(LHS.substr(1)) >
  817. Target.multiVersionSortPriority(RHS.substr(1));
  818. });
  819. bool IsFirst = true;
  820. if (!Info.Architecture.empty()) {
  821. IsFirst = false;
  822. Out << "arch_" << Info.Architecture;
  823. }
  824. for (StringRef Feat : Info.Features) {
  825. if (!IsFirst)
  826. Out << '_';
  827. IsFirst = false;
  828. Out << Feat.substr(1);
  829. }
  830. }
  831. static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
  832. const NamedDecl *ND,
  833. bool OmitMultiVersionMangling = false) {
  834. SmallString<256> Buffer;
  835. llvm::raw_svector_ostream Out(Buffer);
  836. MangleContext &MC = CGM.getCXXABI().getMangleContext();
  837. if (MC.shouldMangleDeclName(ND)) {
  838. llvm::raw_svector_ostream Out(Buffer);
  839. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  840. MC.mangleCXXCtor(D, GD.getCtorType(), Out);
  841. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  842. MC.mangleCXXDtor(D, GD.getDtorType(), Out);
  843. else
  844. MC.mangleName(ND, Out);
  845. } else {
  846. IdentifierInfo *II = ND->getIdentifier();
  847. assert(II && "Attempt to mangle unnamed decl.");
  848. const auto *FD = dyn_cast<FunctionDecl>(ND);
  849. if (FD &&
  850. FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
  851. llvm::raw_svector_ostream Out(Buffer);
  852. Out << "__regcall3__" << II->getName();
  853. } else {
  854. Out << II->getName();
  855. }
  856. }
  857. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  858. if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
  859. switch (FD->getMultiVersionKind()) {
  860. case MultiVersionKind::CPUDispatch:
  861. case MultiVersionKind::CPUSpecific:
  862. AppendCPUSpecificCPUDispatchMangling(CGM,
  863. FD->getAttr<CPUSpecificAttr>(),
  864. GD.getMultiVersionIndex(), Out);
  865. break;
  866. case MultiVersionKind::Target:
  867. AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
  868. break;
  869. case MultiVersionKind::None:
  870. llvm_unreachable("None multiversion type isn't valid here");
  871. }
  872. }
  873. return Out.str();
  874. }
  875. void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
  876. const FunctionDecl *FD) {
  877. if (!FD->isMultiVersion())
  878. return;
  879. // Get the name of what this would be without the 'target' attribute. This
  880. // allows us to lookup the version that was emitted when this wasn't a
  881. // multiversion function.
  882. std::string NonTargetName =
  883. getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
  884. GlobalDecl OtherGD;
  885. if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
  886. assert(OtherGD.getCanonicalDecl()
  887. .getDecl()
  888. ->getAsFunction()
  889. ->isMultiVersion() &&
  890. "Other GD should now be a multiversioned function");
  891. // OtherFD is the version of this function that was mangled BEFORE
  892. // becoming a MultiVersion function. It potentially needs to be updated.
  893. const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
  894. .getDecl()
  895. ->getAsFunction()
  896. ->getMostRecentDecl();
  897. std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
  898. // This is so that if the initial version was already the 'default'
  899. // version, we don't try to update it.
  900. if (OtherName != NonTargetName) {
  901. // Remove instead of erase, since others may have stored the StringRef
  902. // to this.
  903. const auto ExistingRecord = Manglings.find(NonTargetName);
  904. if (ExistingRecord != std::end(Manglings))
  905. Manglings.remove(&(*ExistingRecord));
  906. auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
  907. MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
  908. if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
  909. Entry->setName(OtherName);
  910. }
  911. }
  912. }
  913. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  914. GlobalDecl CanonicalGD = GD.getCanonicalDecl();
  915. // Some ABIs don't have constructor variants. Make sure that base and
  916. // complete constructors get mangled the same.
  917. if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
  918. if (!getTarget().getCXXABI().hasConstructorVariants()) {
  919. CXXCtorType OrigCtorType = GD.getCtorType();
  920. assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
  921. if (OrigCtorType == Ctor_Base)
  922. CanonicalGD = GlobalDecl(CD, Ctor_Complete);
  923. }
  924. }
  925. auto FoundName = MangledDeclNames.find(CanonicalGD);
  926. if (FoundName != MangledDeclNames.end())
  927. return FoundName->second;
  928. // Keep the first result in the case of a mangling collision.
  929. const auto *ND = cast<NamedDecl>(GD.getDecl());
  930. auto Result =
  931. Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
  932. return MangledDeclNames[CanonicalGD] = Result.first->first();
  933. }
  934. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  935. const BlockDecl *BD) {
  936. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  937. const Decl *D = GD.getDecl();
  938. SmallString<256> Buffer;
  939. llvm::raw_svector_ostream Out(Buffer);
  940. if (!D)
  941. MangleCtx.mangleGlobalBlock(BD,
  942. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  943. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  944. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  945. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  946. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  947. else
  948. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  949. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  950. return Result.first->first();
  951. }
  952. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  953. return getModule().getNamedValue(Name);
  954. }
  955. /// AddGlobalCtor - Add a function to the list that will be called before
  956. /// main() runs.
  957. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  958. llvm::Constant *AssociatedData) {
  959. // FIXME: Type coercion of void()* types.
  960. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  961. }
  962. /// AddGlobalDtor - Add a function to the list that will be called
  963. /// when the module is unloaded.
  964. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  965. if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
  966. DtorsUsingAtExit[Priority].push_back(Dtor);
  967. return;
  968. }
  969. // FIXME: Type coercion of void()* types.
  970. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  971. }
  972. void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
  973. if (Fns.empty()) return;
  974. // Ctor function type is void()*.
  975. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  976. llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
  977. TheModule.getDataLayout().getProgramAddressSpace());
  978. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  979. llvm::StructType *CtorStructTy = llvm::StructType::get(
  980. Int32Ty, CtorPFTy, VoidPtrTy);
  981. // Construct the constructor and destructor arrays.
  982. ConstantInitBuilder builder(*this);
  983. auto ctors = builder.beginArray(CtorStructTy);
  984. for (const auto &I : Fns) {
  985. auto ctor = ctors.beginStruct(CtorStructTy);
  986. ctor.addInt(Int32Ty, I.Priority);
  987. ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
  988. if (I.AssociatedData)
  989. ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
  990. else
  991. ctor.addNullPointer(VoidPtrTy);
  992. ctor.finishAndAddTo(ctors);
  993. }
  994. auto list =
  995. ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
  996. /*constant*/ false,
  997. llvm::GlobalValue::AppendingLinkage);
  998. // The LTO linker doesn't seem to like it when we set an alignment
  999. // on appending variables. Take it off as a workaround.
  1000. list->setAlignment(0);
  1001. Fns.clear();
  1002. }
  1003. llvm::GlobalValue::LinkageTypes
  1004. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  1005. const auto *D = cast<FunctionDecl>(GD.getDecl());
  1006. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  1007. if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
  1008. return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
  1009. if (isa<CXXConstructorDecl>(D) &&
  1010. cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
  1011. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1012. // Our approach to inheriting constructors is fundamentally different from
  1013. // that used by the MS ABI, so keep our inheriting constructor thunks
  1014. // internal rather than trying to pick an unambiguous mangling for them.
  1015. return llvm::GlobalValue::InternalLinkage;
  1016. }
  1017. return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
  1018. }
  1019. llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
  1020. llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
  1021. if (!MDS) return nullptr;
  1022. return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
  1023. }
  1024. void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
  1025. const CGFunctionInfo &Info,
  1026. llvm::Function *F) {
  1027. unsigned CallingConv;
  1028. llvm::AttributeList PAL;
  1029. ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
  1030. F->setAttributes(PAL);
  1031. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  1032. }
  1033. /// Determines whether the language options require us to model
  1034. /// unwind exceptions. We treat -fexceptions as mandating this
  1035. /// except under the fragile ObjC ABI with only ObjC exceptions
  1036. /// enabled. This means, for example, that C with -fexceptions
  1037. /// enables this.
  1038. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  1039. // If exceptions are completely disabled, obviously this is false.
  1040. if (!LangOpts.Exceptions) return false;
  1041. // If C++ exceptions are enabled, this is true.
  1042. if (LangOpts.CXXExceptions) return true;
  1043. // If ObjC exceptions are enabled, this depends on the ABI.
  1044. if (LangOpts.ObjCExceptions) {
  1045. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  1046. }
  1047. return true;
  1048. }
  1049. static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
  1050. const CXXMethodDecl *MD) {
  1051. // Check that the type metadata can ever actually be used by a call.
  1052. if (!CGM.getCodeGenOpts().LTOUnit ||
  1053. !CGM.HasHiddenLTOVisibility(MD->getParent()))
  1054. return false;
  1055. // Only functions whose address can be taken with a member function pointer
  1056. // need this sort of type metadata.
  1057. return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
  1058. !isa<CXXDestructorDecl>(MD);
  1059. }
  1060. std::vector<const CXXRecordDecl *>
  1061. CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
  1062. llvm::SetVector<const CXXRecordDecl *> MostBases;
  1063. std::function<void (const CXXRecordDecl *)> CollectMostBases;
  1064. CollectMostBases = [&](const CXXRecordDecl *RD) {
  1065. if (RD->getNumBases() == 0)
  1066. MostBases.insert(RD);
  1067. for (const CXXBaseSpecifier &B : RD->bases())
  1068. CollectMostBases(B.getType()->getAsCXXRecordDecl());
  1069. };
  1070. CollectMostBases(RD);
  1071. return MostBases.takeVector();
  1072. }
  1073. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  1074. llvm::Function *F) {
  1075. llvm::AttrBuilder B;
  1076. if (CodeGenOpts.UnwindTables)
  1077. B.addAttribute(llvm::Attribute::UWTable);
  1078. if (!hasUnwindExceptions(LangOpts))
  1079. B.addAttribute(llvm::Attribute::NoUnwind);
  1080. if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
  1081. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  1082. B.addAttribute(llvm::Attribute::StackProtect);
  1083. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  1084. B.addAttribute(llvm::Attribute::StackProtectStrong);
  1085. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  1086. B.addAttribute(llvm::Attribute::StackProtectReq);
  1087. }
  1088. if (!D) {
  1089. // If we don't have a declaration to control inlining, the function isn't
  1090. // explicitly marked as alwaysinline for semantic reasons, and inlining is
  1091. // disabled, mark the function as noinline.
  1092. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  1093. CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
  1094. B.addAttribute(llvm::Attribute::NoInline);
  1095. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  1096. return;
  1097. }
  1098. // Track whether we need to add the optnone LLVM attribute,
  1099. // starting with the default for this optimization level.
  1100. bool ShouldAddOptNone =
  1101. !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
  1102. // We can't add optnone in the following cases, it won't pass the verifier.
  1103. ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
  1104. ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
  1105. ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
  1106. if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
  1107. B.addAttribute(llvm::Attribute::OptimizeNone);
  1108. // OptimizeNone implies noinline; we should not be inlining such functions.
  1109. B.addAttribute(llvm::Attribute::NoInline);
  1110. assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  1111. "OptimizeNone and AlwaysInline on same function!");
  1112. // We still need to handle naked functions even though optnone subsumes
  1113. // much of their semantics.
  1114. if (D->hasAttr<NakedAttr>())
  1115. B.addAttribute(llvm::Attribute::Naked);
  1116. // OptimizeNone wins over OptimizeForSize and MinSize.
  1117. F->removeFnAttr(llvm::Attribute::OptimizeForSize);
  1118. F->removeFnAttr(llvm::Attribute::MinSize);
  1119. } else if (D->hasAttr<NakedAttr>()) {
  1120. // Naked implies noinline: we should not be inlining such functions.
  1121. B.addAttribute(llvm::Attribute::Naked);
  1122. B.addAttribute(llvm::Attribute::NoInline);
  1123. } else if (D->hasAttr<NoDuplicateAttr>()) {
  1124. B.addAttribute(llvm::Attribute::NoDuplicate);
  1125. } else if (D->hasAttr<NoInlineAttr>()) {
  1126. B.addAttribute(llvm::Attribute::NoInline);
  1127. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  1128. !F->hasFnAttribute(llvm::Attribute::NoInline)) {
  1129. // (noinline wins over always_inline, and we can't specify both in IR)
  1130. B.addAttribute(llvm::Attribute::AlwaysInline);
  1131. } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
  1132. // If we're not inlining, then force everything that isn't always_inline to
  1133. // carry an explicit noinline attribute.
  1134. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
  1135. B.addAttribute(llvm::Attribute::NoInline);
  1136. } else {
  1137. // Otherwise, propagate the inline hint attribute and potentially use its
  1138. // absence to mark things as noinline.
  1139. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  1140. // Search function and template pattern redeclarations for inline.
  1141. auto CheckForInline = [](const FunctionDecl *FD) {
  1142. auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
  1143. return Redecl->isInlineSpecified();
  1144. };
  1145. if (any_of(FD->redecls(), CheckRedeclForInline))
  1146. return true;
  1147. const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
  1148. if (!Pattern)
  1149. return false;
  1150. return any_of(Pattern->redecls(), CheckRedeclForInline);
  1151. };
  1152. if (CheckForInline(FD)) {
  1153. B.addAttribute(llvm::Attribute::InlineHint);
  1154. } else if (CodeGenOpts.getInlining() ==
  1155. CodeGenOptions::OnlyHintInlining &&
  1156. !FD->isInlined() &&
  1157. !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
  1158. B.addAttribute(llvm::Attribute::NoInline);
  1159. }
  1160. }
  1161. }
  1162. // Add other optimization related attributes if we are optimizing this
  1163. // function.
  1164. if (!D->hasAttr<OptimizeNoneAttr>()) {
  1165. if (D->hasAttr<ColdAttr>()) {
  1166. if (!ShouldAddOptNone)
  1167. B.addAttribute(llvm::Attribute::OptimizeForSize);
  1168. B.addAttribute(llvm::Attribute::Cold);
  1169. }
  1170. if (D->hasAttr<MinSizeAttr>())
  1171. B.addAttribute(llvm::Attribute::MinSize);
  1172. }
  1173. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  1174. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  1175. if (alignment)
  1176. F->setAlignment(alignment);
  1177. if (!D->hasAttr<AlignedAttr>())
  1178. if (LangOpts.FunctionAlignment)
  1179. F->setAlignment(1 << LangOpts.FunctionAlignment);
  1180. // Some C++ ABIs require 2-byte alignment for member functions, in order to
  1181. // reserve a bit for differentiating between virtual and non-virtual member
  1182. // functions. If the current target's C++ ABI requires this and this is a
  1183. // member function, set its alignment accordingly.
  1184. if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
  1185. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  1186. F->setAlignment(2);
  1187. }
  1188. // In the cross-dso CFI mode, we want !type attributes on definitions only.
  1189. if (CodeGenOpts.SanitizeCfiCrossDso)
  1190. if (auto *FD = dyn_cast<FunctionDecl>(D))
  1191. CreateFunctionTypeMetadataForIcall(FD, F);
  1192. // Emit type metadata on member functions for member function pointer checks.
  1193. // These are only ever necessary on definitions; we're guaranteed that the
  1194. // definition will be present in the LTO unit as a result of LTO visibility.
  1195. auto *MD = dyn_cast<CXXMethodDecl>(D);
  1196. if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
  1197. for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
  1198. llvm::Metadata *Id =
  1199. CreateMetadataIdentifierForType(Context.getMemberPointerType(
  1200. MD->getType(), Context.getRecordType(Base).getTypePtr()));
  1201. F->addTypeMetadata(0, Id);
  1202. }
  1203. }
  1204. }
  1205. void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
  1206. const Decl *D = GD.getDecl();
  1207. if (dyn_cast_or_null<NamedDecl>(D))
  1208. setGVProperties(GV, GD);
  1209. else
  1210. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  1211. if (D && D->hasAttr<UsedAttr>())
  1212. addUsedGlobal(GV);
  1213. if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
  1214. const auto *VD = cast<VarDecl>(D);
  1215. if (VD->getType().isConstQualified() &&
  1216. VD->getStorageDuration() == SD_Static)
  1217. addUsedGlobal(GV);
  1218. }
  1219. }
  1220. bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
  1221. llvm::AttrBuilder &Attrs) {
  1222. // Add target-cpu and target-features attributes to functions. If
  1223. // we have a decl for the function and it has a target attribute then
  1224. // parse that and add it to the feature set.
  1225. StringRef TargetCPU = getTarget().getTargetOpts().CPU;
  1226. std::vector<std::string> Features;
  1227. const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
  1228. FD = FD ? FD->getMostRecentDecl() : FD;
  1229. const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
  1230. const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
  1231. bool AddedAttr = false;
  1232. if (TD || SD) {
  1233. llvm::StringMap<bool> FeatureMap;
  1234. getFunctionFeatureMap(FeatureMap, GD);
  1235. // Produce the canonical string for this set of features.
  1236. for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
  1237. Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
  1238. // Now add the target-cpu and target-features to the function.
  1239. // While we populated the feature map above, we still need to
  1240. // get and parse the target attribute so we can get the cpu for
  1241. // the function.
  1242. if (TD) {
  1243. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  1244. if (ParsedAttr.Architecture != "" &&
  1245. getTarget().isValidCPUName(ParsedAttr.Architecture))
  1246. TargetCPU = ParsedAttr.Architecture;
  1247. }
  1248. } else {
  1249. // Otherwise just add the existing target cpu and target features to the
  1250. // function.
  1251. Features = getTarget().getTargetOpts().Features;
  1252. }
  1253. if (TargetCPU != "") {
  1254. Attrs.addAttribute("target-cpu", TargetCPU);
  1255. AddedAttr = true;
  1256. }
  1257. if (!Features.empty()) {
  1258. llvm::sort(Features);
  1259. Attrs.addAttribute("target-features", llvm::join(Features, ","));
  1260. AddedAttr = true;
  1261. }
  1262. return AddedAttr;
  1263. }
  1264. void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
  1265. llvm::GlobalObject *GO) {
  1266. const Decl *D = GD.getDecl();
  1267. SetCommonAttributes(GD, GO);
  1268. if (D) {
  1269. if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
  1270. if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
  1271. GV->addAttribute("bss-section", SA->getName());
  1272. if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
  1273. GV->addAttribute("data-section", SA->getName());
  1274. if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
  1275. GV->addAttribute("rodata-section", SA->getName());
  1276. }
  1277. if (auto *F = dyn_cast<llvm::Function>(GO)) {
  1278. if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
  1279. if (!D->getAttr<SectionAttr>())
  1280. F->addFnAttr("implicit-section-name", SA->getName());
  1281. llvm::AttrBuilder Attrs;
  1282. if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
  1283. // We know that GetCPUAndFeaturesAttributes will always have the
  1284. // newest set, since it has the newest possible FunctionDecl, so the
  1285. // new ones should replace the old.
  1286. F->removeFnAttr("target-cpu");
  1287. F->removeFnAttr("target-features");
  1288. F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
  1289. }
  1290. }
  1291. if (const auto *CSA = D->getAttr<CodeSegAttr>())
  1292. GO->setSection(CSA->getName());
  1293. else if (const auto *SA = D->getAttr<SectionAttr>())
  1294. GO->setSection(SA->getName());
  1295. }
  1296. getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
  1297. }
  1298. void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
  1299. llvm::Function *F,
  1300. const CGFunctionInfo &FI) {
  1301. const Decl *D = GD.getDecl();
  1302. SetLLVMFunctionAttributes(GD, FI, F);
  1303. SetLLVMFunctionAttributesForDefinition(D, F);
  1304. F->setLinkage(llvm::Function::InternalLinkage);
  1305. setNonAliasAttributes(GD, F);
  1306. }
  1307. static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
  1308. // Set linkage and visibility in case we never see a definition.
  1309. LinkageInfo LV = ND->getLinkageAndVisibility();
  1310. // Don't set internal linkage on declarations.
  1311. // "extern_weak" is overloaded in LLVM; we probably should have
  1312. // separate linkage types for this.
  1313. if (isExternallyVisible(LV.getLinkage()) &&
  1314. (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
  1315. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1316. }
  1317. void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
  1318. llvm::Function *F) {
  1319. // Only if we are checking indirect calls.
  1320. if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
  1321. return;
  1322. // Non-static class methods are handled via vtable or member function pointer
  1323. // checks elsewhere.
  1324. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  1325. return;
  1326. // Additionally, if building with cross-DSO support...
  1327. if (CodeGenOpts.SanitizeCfiCrossDso) {
  1328. // Skip available_externally functions. They won't be codegen'ed in the
  1329. // current module anyway.
  1330. if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
  1331. return;
  1332. }
  1333. llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
  1334. F->addTypeMetadata(0, MD);
  1335. F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
  1336. // Emit a hash-based bit set entry for cross-DSO calls.
  1337. if (CodeGenOpts.SanitizeCfiCrossDso)
  1338. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  1339. F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  1340. }
  1341. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  1342. bool IsIncompleteFunction,
  1343. bool IsThunk) {
  1344. if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
  1345. // If this is an intrinsic function, set the function's attributes
  1346. // to the intrinsic's attributes.
  1347. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
  1348. return;
  1349. }
  1350. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  1351. if (!IsIncompleteFunction) {
  1352. SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
  1353. // Setup target-specific attributes.
  1354. if (F->isDeclaration())
  1355. getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
  1356. }
  1357. // Add the Returned attribute for "this", except for iOS 5 and earlier
  1358. // where substantial code, including the libstdc++ dylib, was compiled with
  1359. // GCC and does not actually return "this".
  1360. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  1361. !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
  1362. assert(!F->arg_empty() &&
  1363. F->arg_begin()->getType()
  1364. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  1365. "unexpected this return");
  1366. F->addAttribute(1, llvm::Attribute::Returned);
  1367. }
  1368. // Only a few attributes are set on declarations; these may later be
  1369. // overridden by a definition.
  1370. setLinkageForGV(F, FD);
  1371. setGVProperties(F, FD);
  1372. if (const auto *CSA = FD->getAttr<CodeSegAttr>())
  1373. F->setSection(CSA->getName());
  1374. else if (const auto *SA = FD->getAttr<SectionAttr>())
  1375. F->setSection(SA->getName());
  1376. if (FD->isReplaceableGlobalAllocationFunction()) {
  1377. // A replaceable global allocation function does not act like a builtin by
  1378. // default, only if it is invoked by a new-expression or delete-expression.
  1379. F->addAttribute(llvm::AttributeList::FunctionIndex,
  1380. llvm::Attribute::NoBuiltin);
  1381. // A sane operator new returns a non-aliasing pointer.
  1382. // FIXME: Also add NonNull attribute to the return value
  1383. // for the non-nothrow forms?
  1384. auto Kind = FD->getDeclName().getCXXOverloadedOperator();
  1385. if (getCodeGenOpts().AssumeSaneOperatorNew &&
  1386. (Kind == OO_New || Kind == OO_Array_New))
  1387. F->addAttribute(llvm::AttributeList::ReturnIndex,
  1388. llvm::Attribute::NoAlias);
  1389. }
  1390. if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
  1391. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1392. else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  1393. if (MD->isVirtual())
  1394. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1395. // Don't emit entries for function declarations in the cross-DSO mode. This
  1396. // is handled with better precision by the receiving DSO.
  1397. if (!CodeGenOpts.SanitizeCfiCrossDso)
  1398. CreateFunctionTypeMetadataForIcall(FD, F);
  1399. if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
  1400. getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
  1401. if (const auto *CB = FD->getAttr<CallbackAttr>()) {
  1402. // Annotate the callback behavior as metadata:
  1403. // - The callback callee (as argument number).
  1404. // - The callback payloads (as argument numbers).
  1405. llvm::LLVMContext &Ctx = F->getContext();
  1406. llvm::MDBuilder MDB(Ctx);
  1407. // The payload indices are all but the first one in the encoding. The first
  1408. // identifies the callback callee.
  1409. int CalleeIdx = *CB->encoding_begin();
  1410. ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
  1411. F->addMetadata(llvm::LLVMContext::MD_callback,
  1412. *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
  1413. CalleeIdx, PayloadIndices,
  1414. /* VarArgsArePassed */ false)}));
  1415. }
  1416. }
  1417. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  1418. assert(!GV->isDeclaration() &&
  1419. "Only globals with definition can force usage.");
  1420. LLVMUsed.emplace_back(GV);
  1421. }
  1422. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  1423. assert(!GV->isDeclaration() &&
  1424. "Only globals with definition can force usage.");
  1425. LLVMCompilerUsed.emplace_back(GV);
  1426. }
  1427. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  1428. std::vector<llvm::WeakTrackingVH> &List) {
  1429. // Don't create llvm.used if there is no need.
  1430. if (List.empty())
  1431. return;
  1432. // Convert List to what ConstantArray needs.
  1433. SmallVector<llvm::Constant*, 8> UsedArray;
  1434. UsedArray.resize(List.size());
  1435. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  1436. UsedArray[i] =
  1437. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  1438. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  1439. }
  1440. if (UsedArray.empty())
  1441. return;
  1442. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  1443. auto *GV = new llvm::GlobalVariable(
  1444. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  1445. llvm::ConstantArray::get(ATy, UsedArray), Name);
  1446. GV->setSection("llvm.metadata");
  1447. }
  1448. void CodeGenModule::emitLLVMUsed() {
  1449. emitUsed(*this, "llvm.used", LLVMUsed);
  1450. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  1451. }
  1452. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  1453. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  1454. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1455. }
  1456. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  1457. llvm::SmallString<32> Opt;
  1458. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  1459. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1460. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1461. }
  1462. void CodeGenModule::AddELFLibDirective(StringRef Lib) {
  1463. auto &C = getLLVMContext();
  1464. LinkerOptionsMetadata.push_back(llvm::MDNode::get(
  1465. C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
  1466. }
  1467. void CodeGenModule::AddDependentLib(StringRef Lib) {
  1468. llvm::SmallString<24> Opt;
  1469. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  1470. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1471. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1472. }
  1473. /// Add link options implied by the given module, including modules
  1474. /// it depends on, using a postorder walk.
  1475. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  1476. SmallVectorImpl<llvm::MDNode *> &Metadata,
  1477. llvm::SmallPtrSet<Module *, 16> &Visited) {
  1478. // Import this module's parent.
  1479. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  1480. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  1481. }
  1482. // Import this module's dependencies.
  1483. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  1484. if (Visited.insert(Mod->Imports[I - 1]).second)
  1485. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  1486. }
  1487. // Add linker options to link against the libraries/frameworks
  1488. // described by this module.
  1489. llvm::LLVMContext &Context = CGM.getLLVMContext();
  1490. bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
  1491. bool IsPS4 = CGM.getTarget().getTriple().isPS4();
  1492. // For modules that use export_as for linking, use that module
  1493. // name instead.
  1494. if (Mod->UseExportAsModuleLinkName)
  1495. return;
  1496. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  1497. // Link against a framework. Frameworks are currently Darwin only, so we
  1498. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  1499. if (Mod->LinkLibraries[I-1].IsFramework) {
  1500. llvm::Metadata *Args[2] = {
  1501. llvm::MDString::get(Context, "-framework"),
  1502. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
  1503. Metadata.push_back(llvm::MDNode::get(Context, Args));
  1504. continue;
  1505. }
  1506. // Link against a library.
  1507. if (IsELF && !IsPS4) {
  1508. llvm::Metadata *Args[2] = {
  1509. llvm::MDString::get(Context, "lib"),
  1510. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
  1511. };
  1512. Metadata.push_back(llvm::MDNode::get(Context, Args));
  1513. } else {
  1514. llvm::SmallString<24> Opt;
  1515. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  1516. Mod->LinkLibraries[I - 1].Library, Opt);
  1517. auto *OptString = llvm::MDString::get(Context, Opt);
  1518. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  1519. }
  1520. }
  1521. }
  1522. void CodeGenModule::EmitModuleLinkOptions() {
  1523. // Collect the set of all of the modules we want to visit to emit link
  1524. // options, which is essentially the imported modules and all of their
  1525. // non-explicit child modules.
  1526. llvm::SetVector<clang::Module *> LinkModules;
  1527. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  1528. SmallVector<clang::Module *, 16> Stack;
  1529. // Seed the stack with imported modules.
  1530. for (Module *M : ImportedModules) {
  1531. // Do not add any link flags when an implementation TU of a module imports
  1532. // a header of that same module.
  1533. if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  1534. !getLangOpts().isCompilingModule())
  1535. continue;
  1536. if (Visited.insert(M).second)
  1537. Stack.push_back(M);
  1538. }
  1539. // Find all of the modules to import, making a little effort to prune
  1540. // non-leaf modules.
  1541. while (!Stack.empty()) {
  1542. clang::Module *Mod = Stack.pop_back_val();
  1543. bool AnyChildren = false;
  1544. // Visit the submodules of this module.
  1545. for (const auto &SM : Mod->submodules()) {
  1546. // Skip explicit children; they need to be explicitly imported to be
  1547. // linked against.
  1548. if (SM->IsExplicit)
  1549. continue;
  1550. if (Visited.insert(SM).second) {
  1551. Stack.push_back(SM);
  1552. AnyChildren = true;
  1553. }
  1554. }
  1555. // We didn't find any children, so add this module to the list of
  1556. // modules to link against.
  1557. if (!AnyChildren) {
  1558. LinkModules.insert(Mod);
  1559. }
  1560. }
  1561. // Add link options for all of the imported modules in reverse topological
  1562. // order. We don't do anything to try to order import link flags with respect
  1563. // to linker options inserted by things like #pragma comment().
  1564. SmallVector<llvm::MDNode *, 16> MetadataArgs;
  1565. Visited.clear();
  1566. for (Module *M : LinkModules)
  1567. if (Visited.insert(M).second)
  1568. addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
  1569. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  1570. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  1571. // Add the linker options metadata flag.
  1572. auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
  1573. for (auto *MD : LinkerOptionsMetadata)
  1574. NMD->addOperand(MD);
  1575. }
  1576. void CodeGenModule::EmitDeferred() {
  1577. // Emit deferred declare target declarations.
  1578. if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
  1579. getOpenMPRuntime().emitDeferredTargetDecls();
  1580. // Emit code for any potentially referenced deferred decls. Since a
  1581. // previously unused static decl may become used during the generation of code
  1582. // for a static function, iterate until no changes are made.
  1583. if (!DeferredVTables.empty()) {
  1584. EmitDeferredVTables();
  1585. // Emitting a vtable doesn't directly cause more vtables to
  1586. // become deferred, although it can cause functions to be
  1587. // emitted that then need those vtables.
  1588. assert(DeferredVTables.empty());
  1589. }
  1590. // Stop if we're out of both deferred vtables and deferred declarations.
  1591. if (DeferredDeclsToEmit.empty())
  1592. return;
  1593. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  1594. // work, it will not interfere with this.
  1595. std::vector<GlobalDecl> CurDeclsToEmit;
  1596. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  1597. for (GlobalDecl &D : CurDeclsToEmit) {
  1598. // We should call GetAddrOfGlobal with IsForDefinition set to true in order
  1599. // to get GlobalValue with exactly the type we need, not something that
  1600. // might had been created for another decl with the same mangled name but
  1601. // different type.
  1602. llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
  1603. GetAddrOfGlobal(D, ForDefinition));
  1604. // In case of different address spaces, we may still get a cast, even with
  1605. // IsForDefinition equal to true. Query mangled names table to get
  1606. // GlobalValue.
  1607. if (!GV)
  1608. GV = GetGlobalValue(getMangledName(D));
  1609. // Make sure GetGlobalValue returned non-null.
  1610. assert(GV);
  1611. // Check to see if we've already emitted this. This is necessary
  1612. // for a couple of reasons: first, decls can end up in the
  1613. // deferred-decls queue multiple times, and second, decls can end
  1614. // up with definitions in unusual ways (e.g. by an extern inline
  1615. // function acquiring a strong function redefinition). Just
  1616. // ignore these cases.
  1617. if (!GV->isDeclaration())
  1618. continue;
  1619. // Otherwise, emit the definition and move on to the next one.
  1620. EmitGlobalDefinition(D, GV);
  1621. // If we found out that we need to emit more decls, do that recursively.
  1622. // This has the advantage that the decls are emitted in a DFS and related
  1623. // ones are close together, which is convenient for testing.
  1624. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  1625. EmitDeferred();
  1626. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  1627. }
  1628. }
  1629. }
  1630. void CodeGenModule::EmitVTablesOpportunistically() {
  1631. // Try to emit external vtables as available_externally if they have emitted
  1632. // all inlined virtual functions. It runs after EmitDeferred() and therefore
  1633. // is not allowed to create new references to things that need to be emitted
  1634. // lazily. Note that it also uses fact that we eagerly emitting RTTI.
  1635. assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
  1636. && "Only emit opportunistic vtables with optimizations");
  1637. for (const CXXRecordDecl *RD : OpportunisticVTables) {
  1638. assert(getVTables().isVTableExternal(RD) &&
  1639. "This queue should only contain external vtables");
  1640. if (getCXXABI().canSpeculativelyEmitVTable(RD))
  1641. VTables.GenerateClassData(RD);
  1642. }
  1643. OpportunisticVTables.clear();
  1644. }
  1645. void CodeGenModule::EmitGlobalAnnotations() {
  1646. if (Annotations.empty())
  1647. return;
  1648. // Create a new global variable for the ConstantStruct in the Module.
  1649. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  1650. Annotations[0]->getType(), Annotations.size()), Annotations);
  1651. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  1652. llvm::GlobalValue::AppendingLinkage,
  1653. Array, "llvm.global.annotations");
  1654. gv->setSection(AnnotationSection);
  1655. }
  1656. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  1657. llvm::Constant *&AStr = AnnotationStrings[Str];
  1658. if (AStr)
  1659. return AStr;
  1660. // Not found yet, create a new global.
  1661. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  1662. auto *gv =
  1663. new llvm::GlobalVariable(getModule(), s->getType(), true,
  1664. llvm::GlobalValue::PrivateLinkage, s, ".str");
  1665. gv->setSection(AnnotationSection);
  1666. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1667. AStr = gv;
  1668. return gv;
  1669. }
  1670. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  1671. SourceManager &SM = getContext().getSourceManager();
  1672. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  1673. if (PLoc.isValid())
  1674. return EmitAnnotationString(PLoc.getFilename());
  1675. return EmitAnnotationString(SM.getBufferName(Loc));
  1676. }
  1677. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  1678. SourceManager &SM = getContext().getSourceManager();
  1679. PresumedLoc PLoc = SM.getPresumedLoc(L);
  1680. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  1681. SM.getExpansionLineNumber(L);
  1682. return llvm::ConstantInt::get(Int32Ty, LineNo);
  1683. }
  1684. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  1685. const AnnotateAttr *AA,
  1686. SourceLocation L) {
  1687. // Get the globals for file name, annotation, and the line number.
  1688. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  1689. *UnitGV = EmitAnnotationUnit(L),
  1690. *LineNoCst = EmitAnnotationLineNo(L);
  1691. // Create the ConstantStruct for the global annotation.
  1692. llvm::Constant *Fields[4] = {
  1693. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  1694. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  1695. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  1696. LineNoCst
  1697. };
  1698. return llvm::ConstantStruct::getAnon(Fields);
  1699. }
  1700. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  1701. llvm::GlobalValue *GV) {
  1702. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1703. // Get the struct elements for these annotations.
  1704. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1705. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1706. }
  1707. bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
  1708. llvm::Function *Fn,
  1709. SourceLocation Loc) const {
  1710. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1711. // Blacklist by function name.
  1712. if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
  1713. return true;
  1714. // Blacklist by location.
  1715. if (Loc.isValid())
  1716. return SanitizerBL.isBlacklistedLocation(Kind, Loc);
  1717. // If location is unknown, this may be a compiler-generated function. Assume
  1718. // it's located in the main file.
  1719. auto &SM = Context.getSourceManager();
  1720. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1721. return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
  1722. }
  1723. return false;
  1724. }
  1725. bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
  1726. SourceLocation Loc, QualType Ty,
  1727. StringRef Category) const {
  1728. // For now globals can be blacklisted only in ASan and KASan.
  1729. const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
  1730. (SanitizerKind::Address | SanitizerKind::KernelAddress |
  1731. SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
  1732. if (!EnabledAsanMask)
  1733. return false;
  1734. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1735. if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
  1736. return true;
  1737. if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
  1738. return true;
  1739. // Check global type.
  1740. if (!Ty.isNull()) {
  1741. // Drill down the array types: if global variable of a fixed type is
  1742. // blacklisted, we also don't instrument arrays of them.
  1743. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  1744. Ty = AT->getElementType();
  1745. Ty = Ty.getCanonicalType().getUnqualifiedType();
  1746. // We allow to blacklist only record types (classes, structs etc.)
  1747. if (Ty->isRecordType()) {
  1748. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  1749. if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
  1750. return true;
  1751. }
  1752. }
  1753. return false;
  1754. }
  1755. bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
  1756. StringRef Category) const {
  1757. const auto &XRayFilter = getContext().getXRayFilter();
  1758. using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
  1759. auto Attr = ImbueAttr::NONE;
  1760. if (Loc.isValid())
  1761. Attr = XRayFilter.shouldImbueLocation(Loc, Category);
  1762. if (Attr == ImbueAttr::NONE)
  1763. Attr = XRayFilter.shouldImbueFunction(Fn->getName());
  1764. switch (Attr) {
  1765. case ImbueAttr::NONE:
  1766. return false;
  1767. case ImbueAttr::ALWAYS:
  1768. Fn->addFnAttr("function-instrument", "xray-always");
  1769. break;
  1770. case ImbueAttr::ALWAYS_ARG1:
  1771. Fn->addFnAttr("function-instrument", "xray-always");
  1772. Fn->addFnAttr("xray-log-args", "1");
  1773. break;
  1774. case ImbueAttr::NEVER:
  1775. Fn->addFnAttr("function-instrument", "xray-never");
  1776. break;
  1777. }
  1778. return true;
  1779. }
  1780. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  1781. // Never defer when EmitAllDecls is specified.
  1782. if (LangOpts.EmitAllDecls)
  1783. return true;
  1784. if (CodeGenOpts.KeepStaticConsts) {
  1785. const auto *VD = dyn_cast<VarDecl>(Global);
  1786. if (VD && VD->getType().isConstQualified() &&
  1787. VD->getStorageDuration() == SD_Static)
  1788. return true;
  1789. }
  1790. return getContext().DeclMustBeEmitted(Global);
  1791. }
  1792. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  1793. if (const auto *FD = dyn_cast<FunctionDecl>(Global))
  1794. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1795. // Implicit template instantiations may change linkage if they are later
  1796. // explicitly instantiated, so they should not be emitted eagerly.
  1797. return false;
  1798. if (const auto *VD = dyn_cast<VarDecl>(Global))
  1799. if (Context.getInlineVariableDefinitionKind(VD) ==
  1800. ASTContext::InlineVariableDefinitionKind::WeakUnknown)
  1801. // A definition of an inline constexpr static data member may change
  1802. // linkage later if it's redeclared outside the class.
  1803. return false;
  1804. // If OpenMP is enabled and threadprivates must be generated like TLS, delay
  1805. // codegen for global variables, because they may be marked as threadprivate.
  1806. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
  1807. getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
  1808. !isTypeConstant(Global->getType(), false) &&
  1809. !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
  1810. return false;
  1811. return true;
  1812. }
  1813. ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
  1814. const CXXUuidofExpr* E) {
  1815. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  1816. // well-formed.
  1817. StringRef Uuid = E->getUuidStr();
  1818. std::string Name = "_GUID_" + Uuid.lower();
  1819. std::replace(Name.begin(), Name.end(), '-', '_');
  1820. // The UUID descriptor should be pointer aligned.
  1821. CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
  1822. // Look for an existing global.
  1823. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  1824. return ConstantAddress(GV, Alignment);
  1825. llvm::Constant *Init = EmitUuidofInitializer(Uuid);
  1826. assert(Init && "failed to initialize as constant");
  1827. auto *GV = new llvm::GlobalVariable(
  1828. getModule(), Init->getType(),
  1829. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  1830. if (supportsCOMDAT())
  1831. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1832. setDSOLocal(GV);
  1833. return ConstantAddress(GV, Alignment);
  1834. }
  1835. ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  1836. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  1837. assert(AA && "No alias?");
  1838. CharUnits Alignment = getContext().getDeclAlign(VD);
  1839. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  1840. // See if there is already something with the target's name in the module.
  1841. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  1842. if (Entry) {
  1843. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  1844. auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  1845. return ConstantAddress(Ptr, Alignment);
  1846. }
  1847. llvm::Constant *Aliasee;
  1848. if (isa<llvm::FunctionType>(DeclTy))
  1849. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  1850. GlobalDecl(cast<FunctionDecl>(VD)),
  1851. /*ForVTable=*/false);
  1852. else
  1853. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1854. llvm::PointerType::getUnqual(DeclTy),
  1855. nullptr);
  1856. auto *F = cast<llvm::GlobalValue>(Aliasee);
  1857. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1858. WeakRefReferences.insert(F);
  1859. return ConstantAddress(Aliasee, Alignment);
  1860. }
  1861. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  1862. const auto *Global = cast<ValueDecl>(GD.getDecl());
  1863. // Weak references don't produce any output by themselves.
  1864. if (Global->hasAttr<WeakRefAttr>())
  1865. return;
  1866. // If this is an alias definition (which otherwise looks like a declaration)
  1867. // emit it now.
  1868. if (Global->hasAttr<AliasAttr>())
  1869. return EmitAliasDefinition(GD);
  1870. // IFunc like an alias whose value is resolved at runtime by calling resolver.
  1871. if (Global->hasAttr<IFuncAttr>())
  1872. return emitIFuncDefinition(GD);
  1873. // If this is a cpu_dispatch multiversion function, emit the resolver.
  1874. if (Global->hasAttr<CPUDispatchAttr>())
  1875. return emitCPUDispatchDefinition(GD);
  1876. // If this is CUDA, be selective about which declarations we emit.
  1877. if (LangOpts.CUDA) {
  1878. if (LangOpts.CUDAIsDevice) {
  1879. if (!Global->hasAttr<CUDADeviceAttr>() &&
  1880. !Global->hasAttr<CUDAGlobalAttr>() &&
  1881. !Global->hasAttr<CUDAConstantAttr>() &&
  1882. !Global->hasAttr<CUDASharedAttr>())
  1883. return;
  1884. } else {
  1885. // We need to emit host-side 'shadows' for all global
  1886. // device-side variables because the CUDA runtime needs their
  1887. // size and host-side address in order to provide access to
  1888. // their device-side incarnations.
  1889. // So device-only functions are the only things we skip.
  1890. if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
  1891. Global->hasAttr<CUDADeviceAttr>())
  1892. return;
  1893. assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
  1894. "Expected Variable or Function");
  1895. }
  1896. }
  1897. if (LangOpts.OpenMP) {
  1898. // If this is OpenMP device, check if it is legal to emit this global
  1899. // normally.
  1900. if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
  1901. return;
  1902. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
  1903. if (MustBeEmitted(Global))
  1904. EmitOMPDeclareReduction(DRD);
  1905. return;
  1906. } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
  1907. if (MustBeEmitted(Global))
  1908. EmitOMPDeclareMapper(DMD);
  1909. return;
  1910. }
  1911. }
  1912. // Ignore declarations, they will be emitted on their first use.
  1913. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  1914. // Forward declarations are emitted lazily on first use.
  1915. if (!FD->doesThisDeclarationHaveABody()) {
  1916. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  1917. return;
  1918. StringRef MangledName = getMangledName(GD);
  1919. // Compute the function info and LLVM type.
  1920. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1921. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  1922. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  1923. /*DontDefer=*/false);
  1924. return;
  1925. }
  1926. } else {
  1927. const auto *VD = cast<VarDecl>(Global);
  1928. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  1929. if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  1930. !Context.isMSStaticDataMemberInlineDefinition(VD)) {
  1931. if (LangOpts.OpenMP) {
  1932. // Emit declaration of the must-be-emitted declare target variable.
  1933. if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  1934. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  1935. if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
  1936. (void)GetAddrOfGlobalVar(VD);
  1937. } else {
  1938. assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
  1939. "link claue expected.");
  1940. (void)getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
  1941. }
  1942. return;
  1943. }
  1944. }
  1945. // If this declaration may have caused an inline variable definition to
  1946. // change linkage, make sure that it's emitted.
  1947. if (Context.getInlineVariableDefinitionKind(VD) ==
  1948. ASTContext::InlineVariableDefinitionKind::Strong)
  1949. GetAddrOfGlobalVar(VD);
  1950. return;
  1951. }
  1952. }
  1953. // Defer code generation to first use when possible, e.g. if this is an inline
  1954. // function. If the global must always be emitted, do it eagerly if possible
  1955. // to benefit from cache locality.
  1956. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  1957. // Emit the definition if it can't be deferred.
  1958. EmitGlobalDefinition(GD);
  1959. return;
  1960. }
  1961. // If we're deferring emission of a C++ variable with an
  1962. // initializer, remember the order in which it appeared in the file.
  1963. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1964. cast<VarDecl>(Global)->hasInit()) {
  1965. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1966. CXXGlobalInits.push_back(nullptr);
  1967. }
  1968. StringRef MangledName = getMangledName(GD);
  1969. if (GetGlobalValue(MangledName) != nullptr) {
  1970. // The value has already been used and should therefore be emitted.
  1971. addDeferredDeclToEmit(GD);
  1972. } else if (MustBeEmitted(Global)) {
  1973. // The value must be emitted, but cannot be emitted eagerly.
  1974. assert(!MayBeEmittedEagerly(Global));
  1975. addDeferredDeclToEmit(GD);
  1976. } else {
  1977. // Otherwise, remember that we saw a deferred decl with this name. The
  1978. // first use of the mangled name will cause it to move into
  1979. // DeferredDeclsToEmit.
  1980. DeferredDecls[MangledName] = GD;
  1981. }
  1982. }
  1983. // Check if T is a class type with a destructor that's not dllimport.
  1984. static bool HasNonDllImportDtor(QualType T) {
  1985. if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
  1986. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1987. if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
  1988. return true;
  1989. return false;
  1990. }
  1991. namespace {
  1992. struct FunctionIsDirectlyRecursive
  1993. : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
  1994. const StringRef Name;
  1995. const Builtin::Context &BI;
  1996. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
  1997. : Name(N), BI(C) {}
  1998. bool VisitCallExpr(const CallExpr *E) {
  1999. const FunctionDecl *FD = E->getDirectCallee();
  2000. if (!FD)
  2001. return false;
  2002. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  2003. if (Attr && Name == Attr->getLabel())
  2004. return true;
  2005. unsigned BuiltinID = FD->getBuiltinID();
  2006. if (!BuiltinID || !BI.isLibFunction(BuiltinID))
  2007. return false;
  2008. StringRef BuiltinName = BI.getName(BuiltinID);
  2009. if (BuiltinName.startswith("__builtin_") &&
  2010. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  2011. return true;
  2012. }
  2013. return false;
  2014. }
  2015. bool VisitStmt(const Stmt *S) {
  2016. for (const Stmt *Child : S->children())
  2017. if (Child && this->Visit(Child))
  2018. return true;
  2019. return false;
  2020. }
  2021. };
  2022. // Make sure we're not referencing non-imported vars or functions.
  2023. struct DLLImportFunctionVisitor
  2024. : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
  2025. bool SafeToInline = true;
  2026. bool shouldVisitImplicitCode() const { return true; }
  2027. bool VisitVarDecl(VarDecl *VD) {
  2028. if (VD->getTLSKind()) {
  2029. // A thread-local variable cannot be imported.
  2030. SafeToInline = false;
  2031. return SafeToInline;
  2032. }
  2033. // A variable definition might imply a destructor call.
  2034. if (VD->isThisDeclarationADefinition())
  2035. SafeToInline = !HasNonDllImportDtor(VD->getType());
  2036. return SafeToInline;
  2037. }
  2038. bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  2039. if (const auto *D = E->getTemporary()->getDestructor())
  2040. SafeToInline = D->hasAttr<DLLImportAttr>();
  2041. return SafeToInline;
  2042. }
  2043. bool VisitDeclRefExpr(DeclRefExpr *E) {
  2044. ValueDecl *VD = E->getDecl();
  2045. if (isa<FunctionDecl>(VD))
  2046. SafeToInline = VD->hasAttr<DLLImportAttr>();
  2047. else if (VarDecl *V = dyn_cast<VarDecl>(VD))
  2048. SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
  2049. return SafeToInline;
  2050. }
  2051. bool VisitCXXConstructExpr(CXXConstructExpr *E) {
  2052. SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
  2053. return SafeToInline;
  2054. }
  2055. bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  2056. CXXMethodDecl *M = E->getMethodDecl();
  2057. if (!M) {
  2058. // Call through a pointer to member function. This is safe to inline.
  2059. SafeToInline = true;
  2060. } else {
  2061. SafeToInline = M->hasAttr<DLLImportAttr>();
  2062. }
  2063. return SafeToInline;
  2064. }
  2065. bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  2066. SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
  2067. return SafeToInline;
  2068. }
  2069. bool VisitCXXNewExpr(CXXNewExpr *E) {
  2070. SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
  2071. return SafeToInline;
  2072. }
  2073. };
  2074. }
  2075. // isTriviallyRecursive - Check if this function calls another
  2076. // decl that, because of the asm attribute or the other decl being a builtin,
  2077. // ends up pointing to itself.
  2078. bool
  2079. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  2080. StringRef Name;
  2081. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  2082. // asm labels are a special kind of mangling we have to support.
  2083. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  2084. if (!Attr)
  2085. return false;
  2086. Name = Attr->getLabel();
  2087. } else {
  2088. Name = FD->getName();
  2089. }
  2090. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  2091. const Stmt *Body = FD->getBody();
  2092. return Body ? Walker.Visit(Body) : false;
  2093. }
  2094. bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  2095. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  2096. return true;
  2097. const auto *F = cast<FunctionDecl>(GD.getDecl());
  2098. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  2099. return false;
  2100. if (F->hasAttr<DLLImportAttr>()) {
  2101. // Check whether it would be safe to inline this dllimport function.
  2102. DLLImportFunctionVisitor Visitor;
  2103. Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
  2104. if (!Visitor.SafeToInline)
  2105. return false;
  2106. if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
  2107. // Implicit destructor invocations aren't captured in the AST, so the
  2108. // check above can't see them. Check for them manually here.
  2109. for (const Decl *Member : Dtor->getParent()->decls())
  2110. if (isa<FieldDecl>(Member))
  2111. if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
  2112. return false;
  2113. for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
  2114. if (HasNonDllImportDtor(B.getType()))
  2115. return false;
  2116. }
  2117. }
  2118. // PR9614. Avoid cases where the source code is lying to us. An available
  2119. // externally function should have an equivalent function somewhere else,
  2120. // but a function that calls itself is clearly not equivalent to the real
  2121. // implementation.
  2122. // This happens in glibc's btowc and in some configure checks.
  2123. return !isTriviallyRecursive(F);
  2124. }
  2125. bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
  2126. return CodeGenOpts.OptimizationLevel > 0;
  2127. }
  2128. void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
  2129. llvm::GlobalValue *GV) {
  2130. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2131. if (FD->isCPUSpecificMultiVersion()) {
  2132. auto *Spec = FD->getAttr<CPUSpecificAttr>();
  2133. for (unsigned I = 0; I < Spec->cpus_size(); ++I)
  2134. EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
  2135. // Requires multiple emits.
  2136. } else
  2137. EmitGlobalFunctionDefinition(GD, GV);
  2138. }
  2139. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  2140. const auto *D = cast<ValueDecl>(GD.getDecl());
  2141. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  2142. Context.getSourceManager(),
  2143. "Generating code for declaration");
  2144. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2145. // At -O0, don't generate IR for functions with available_externally
  2146. // linkage.
  2147. if (!shouldEmitFunction(GD))
  2148. return;
  2149. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  2150. // Make sure to emit the definition(s) before we emit the thunks.
  2151. // This is necessary for the generation of certain thunks.
  2152. if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
  2153. ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
  2154. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
  2155. ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
  2156. else if (FD->isMultiVersion())
  2157. EmitMultiVersionFunctionDefinition(GD, GV);
  2158. else
  2159. EmitGlobalFunctionDefinition(GD, GV);
  2160. if (Method->isVirtual())
  2161. getVTables().EmitThunks(GD);
  2162. return;
  2163. }
  2164. if (FD->isMultiVersion())
  2165. return EmitMultiVersionFunctionDefinition(GD, GV);
  2166. return EmitGlobalFunctionDefinition(GD, GV);
  2167. }
  2168. if (const auto *VD = dyn_cast<VarDecl>(D))
  2169. return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
  2170. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  2171. }
  2172. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  2173. llvm::Function *NewFn);
  2174. static unsigned
  2175. TargetMVPriority(const TargetInfo &TI,
  2176. const CodeGenFunction::MultiVersionResolverOption &RO) {
  2177. unsigned Priority = 0;
  2178. for (StringRef Feat : RO.Conditions.Features)
  2179. Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
  2180. if (!RO.Conditions.Architecture.empty())
  2181. Priority = std::max(
  2182. Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
  2183. return Priority;
  2184. }
  2185. void CodeGenModule::emitMultiVersionFunctions() {
  2186. for (GlobalDecl GD : MultiVersionFuncs) {
  2187. SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
  2188. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  2189. getContext().forEachMultiversionedFunctionVersion(
  2190. FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
  2191. GlobalDecl CurGD{
  2192. (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
  2193. StringRef MangledName = getMangledName(CurGD);
  2194. llvm::Constant *Func = GetGlobalValue(MangledName);
  2195. if (!Func) {
  2196. if (CurFD->isDefined()) {
  2197. EmitGlobalFunctionDefinition(CurGD, nullptr);
  2198. Func = GetGlobalValue(MangledName);
  2199. } else {
  2200. const CGFunctionInfo &FI =
  2201. getTypes().arrangeGlobalDeclaration(GD);
  2202. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2203. Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
  2204. /*DontDefer=*/false, ForDefinition);
  2205. }
  2206. assert(Func && "This should have just been created");
  2207. }
  2208. const auto *TA = CurFD->getAttr<TargetAttr>();
  2209. llvm::SmallVector<StringRef, 8> Feats;
  2210. TA->getAddedFeatures(Feats);
  2211. Options.emplace_back(cast<llvm::Function>(Func),
  2212. TA->getArchitecture(), Feats);
  2213. });
  2214. llvm::Function *ResolverFunc;
  2215. const TargetInfo &TI = getTarget();
  2216. if (TI.supportsIFunc() || FD->isTargetMultiVersion())
  2217. ResolverFunc = cast<llvm::Function>(
  2218. GetGlobalValue((getMangledName(GD) + ".resolver").str()));
  2219. else
  2220. ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
  2221. if (supportsCOMDAT())
  2222. ResolverFunc->setComdat(
  2223. getModule().getOrInsertComdat(ResolverFunc->getName()));
  2224. std::stable_sort(
  2225. Options.begin(), Options.end(),
  2226. [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
  2227. const CodeGenFunction::MultiVersionResolverOption &RHS) {
  2228. return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
  2229. });
  2230. CodeGenFunction CGF(*this);
  2231. CGF.EmitMultiVersionResolver(ResolverFunc, Options);
  2232. }
  2233. }
  2234. void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
  2235. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2236. assert(FD && "Not a FunctionDecl?");
  2237. const auto *DD = FD->getAttr<CPUDispatchAttr>();
  2238. assert(DD && "Not a cpu_dispatch Function?");
  2239. llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
  2240. if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
  2241. const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
  2242. DeclTy = getTypes().GetFunctionType(FInfo);
  2243. }
  2244. StringRef ResolverName = getMangledName(GD);
  2245. llvm::Type *ResolverType;
  2246. GlobalDecl ResolverGD;
  2247. if (getTarget().supportsIFunc())
  2248. ResolverType = llvm::FunctionType::get(
  2249. llvm::PointerType::get(DeclTy,
  2250. Context.getTargetAddressSpace(FD->getType())),
  2251. false);
  2252. else {
  2253. ResolverType = DeclTy;
  2254. ResolverGD = GD;
  2255. }
  2256. auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
  2257. ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
  2258. SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
  2259. const TargetInfo &Target = getTarget();
  2260. unsigned Index = 0;
  2261. for (const IdentifierInfo *II : DD->cpus()) {
  2262. // Get the name of the target function so we can look it up/create it.
  2263. std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
  2264. getCPUSpecificMangling(*this, II->getName());
  2265. llvm::Constant *Func = GetGlobalValue(MangledName);
  2266. if (!Func) {
  2267. GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
  2268. if (ExistingDecl.getDecl() &&
  2269. ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
  2270. EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
  2271. Func = GetGlobalValue(MangledName);
  2272. } else {
  2273. if (!ExistingDecl.getDecl())
  2274. ExistingDecl = GD.getWithMultiVersionIndex(Index);
  2275. Func = GetOrCreateLLVMFunction(
  2276. MangledName, DeclTy, ExistingDecl,
  2277. /*ForVTable=*/false, /*DontDefer=*/true,
  2278. /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
  2279. }
  2280. }
  2281. llvm::SmallVector<StringRef, 32> Features;
  2282. Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
  2283. llvm::transform(Features, Features.begin(),
  2284. [](StringRef Str) { return Str.substr(1); });
  2285. Features.erase(std::remove_if(
  2286. Features.begin(), Features.end(), [&Target](StringRef Feat) {
  2287. return !Target.validateCpuSupports(Feat);
  2288. }), Features.end());
  2289. Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
  2290. ++Index;
  2291. }
  2292. llvm::sort(
  2293. Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
  2294. const CodeGenFunction::MultiVersionResolverOption &RHS) {
  2295. return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
  2296. CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
  2297. });
  2298. // If the list contains multiple 'default' versions, such as when it contains
  2299. // 'pentium' and 'generic', don't emit the call to the generic one (since we
  2300. // always run on at least a 'pentium'). We do this by deleting the 'least
  2301. // advanced' (read, lowest mangling letter).
  2302. while (Options.size() > 1 &&
  2303. CodeGenFunction::GetX86CpuSupportsMask(
  2304. (Options.end() - 2)->Conditions.Features) == 0) {
  2305. StringRef LHSName = (Options.end() - 2)->Function->getName();
  2306. StringRef RHSName = (Options.end() - 1)->Function->getName();
  2307. if (LHSName.compare(RHSName) < 0)
  2308. Options.erase(Options.end() - 2);
  2309. else
  2310. Options.erase(Options.end() - 1);
  2311. }
  2312. CodeGenFunction CGF(*this);
  2313. CGF.EmitMultiVersionResolver(ResolverFunc, Options);
  2314. }
  2315. /// If a dispatcher for the specified mangled name is not in the module, create
  2316. /// and return an llvm Function with the specified type.
  2317. llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
  2318. GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
  2319. std::string MangledName =
  2320. getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
  2321. // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
  2322. // a separate resolver).
  2323. std::string ResolverName = MangledName;
  2324. if (getTarget().supportsIFunc())
  2325. ResolverName += ".ifunc";
  2326. else if (FD->isTargetMultiVersion())
  2327. ResolverName += ".resolver";
  2328. // If this already exists, just return that one.
  2329. if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
  2330. return ResolverGV;
  2331. // Since this is the first time we've created this IFunc, make sure
  2332. // that we put this multiversioned function into the list to be
  2333. // replaced later if necessary (target multiversioning only).
  2334. if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
  2335. MultiVersionFuncs.push_back(GD);
  2336. if (getTarget().supportsIFunc()) {
  2337. llvm::Type *ResolverType = llvm::FunctionType::get(
  2338. llvm::PointerType::get(
  2339. DeclTy, getContext().getTargetAddressSpace(FD->getType())),
  2340. false);
  2341. llvm::Constant *Resolver = GetOrCreateLLVMFunction(
  2342. MangledName + ".resolver", ResolverType, GlobalDecl{},
  2343. /*ForVTable=*/false);
  2344. llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
  2345. DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
  2346. GIF->setName(ResolverName);
  2347. SetCommonAttributes(FD, GIF);
  2348. return GIF;
  2349. }
  2350. llvm::Constant *Resolver = GetOrCreateLLVMFunction(
  2351. ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
  2352. assert(isa<llvm::GlobalValue>(Resolver) &&
  2353. "Resolver should be created for the first time");
  2354. SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
  2355. return Resolver;
  2356. }
  2357. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  2358. /// module, create and return an llvm Function with the specified type. If there
  2359. /// is something in the module with the specified name, return it potentially
  2360. /// bitcasted to the right type.
  2361. ///
  2362. /// If D is non-null, it specifies a decl that correspond to this. This is used
  2363. /// to set the attributes on the function when it is first created.
  2364. llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
  2365. StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
  2366. bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
  2367. ForDefinition_t IsForDefinition) {
  2368. const Decl *D = GD.getDecl();
  2369. // Any attempts to use a MultiVersion function should result in retrieving
  2370. // the iFunc instead. Name Mangling will handle the rest of the changes.
  2371. if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
  2372. // For the device mark the function as one that should be emitted.
  2373. if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
  2374. !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
  2375. !DontDefer && !IsForDefinition) {
  2376. if (const FunctionDecl *FDDef = FD->getDefinition()) {
  2377. GlobalDecl GDDef;
  2378. if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
  2379. GDDef = GlobalDecl(CD, GD.getCtorType());
  2380. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
  2381. GDDef = GlobalDecl(DD, GD.getDtorType());
  2382. else
  2383. GDDef = GlobalDecl(FDDef);
  2384. EmitGlobal(GDDef);
  2385. }
  2386. }
  2387. if (FD->isMultiVersion()) {
  2388. const auto *TA = FD->getAttr<TargetAttr>();
  2389. if (TA && TA->isDefaultVersion())
  2390. UpdateMultiVersionNames(GD, FD);
  2391. if (!IsForDefinition)
  2392. return GetOrCreateMultiVersionResolver(GD, Ty, FD);
  2393. }
  2394. }
  2395. // Lookup the entry, lazily creating it if necessary.
  2396. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2397. if (Entry) {
  2398. if (WeakRefReferences.erase(Entry)) {
  2399. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  2400. if (FD && !FD->hasAttr<WeakAttr>())
  2401. Entry->setLinkage(llvm::Function::ExternalLinkage);
  2402. }
  2403. // Handle dropped DLL attributes.
  2404. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
  2405. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  2406. setDSOLocal(Entry);
  2407. }
  2408. // If there are two attempts to define the same mangled name, issue an
  2409. // error.
  2410. if (IsForDefinition && !Entry->isDeclaration()) {
  2411. GlobalDecl OtherGD;
  2412. // Check that GD is not yet in DiagnosedConflictingDefinitions is required
  2413. // to make sure that we issue an error only once.
  2414. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  2415. (GD.getCanonicalDecl().getDecl() !=
  2416. OtherGD.getCanonicalDecl().getDecl()) &&
  2417. DiagnosedConflictingDefinitions.insert(GD).second) {
  2418. getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
  2419. << MangledName;
  2420. getDiags().Report(OtherGD.getDecl()->getLocation(),
  2421. diag::note_previous_definition);
  2422. }
  2423. }
  2424. if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
  2425. (Entry->getType()->getElementType() == Ty)) {
  2426. return Entry;
  2427. }
  2428. // Make sure the result is of the correct type.
  2429. // (If function is requested for a definition, we always need to create a new
  2430. // function, not just return a bitcast.)
  2431. if (!IsForDefinition)
  2432. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  2433. }
  2434. // This function doesn't have a complete type (for example, the return
  2435. // type is an incomplete struct). Use a fake type instead, and make
  2436. // sure not to try to set attributes.
  2437. bool IsIncompleteFunction = false;
  2438. llvm::FunctionType *FTy;
  2439. if (isa<llvm::FunctionType>(Ty)) {
  2440. FTy = cast<llvm::FunctionType>(Ty);
  2441. } else {
  2442. FTy = llvm::FunctionType::get(VoidTy, false);
  2443. IsIncompleteFunction = true;
  2444. }
  2445. llvm::Function *F =
  2446. llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
  2447. Entry ? StringRef() : MangledName, &getModule());
  2448. // If we already created a function with the same mangled name (but different
  2449. // type) before, take its name and add it to the list of functions to be
  2450. // replaced with F at the end of CodeGen.
  2451. //
  2452. // This happens if there is a prototype for a function (e.g. "int f()") and
  2453. // then a definition of a different type (e.g. "int f(int x)").
  2454. if (Entry) {
  2455. F->takeName(Entry);
  2456. // This might be an implementation of a function without a prototype, in
  2457. // which case, try to do special replacement of calls which match the new
  2458. // prototype. The really key thing here is that we also potentially drop
  2459. // arguments from the call site so as to make a direct call, which makes the
  2460. // inliner happier and suppresses a number of optimizer warnings (!) about
  2461. // dropping arguments.
  2462. if (!Entry->use_empty()) {
  2463. ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
  2464. Entry->removeDeadConstantUsers();
  2465. }
  2466. llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
  2467. F, Entry->getType()->getElementType()->getPointerTo());
  2468. addGlobalValReplacement(Entry, BC);
  2469. }
  2470. assert(F->getName() == MangledName && "name was uniqued!");
  2471. if (D)
  2472. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
  2473. if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
  2474. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
  2475. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  2476. }
  2477. if (!DontDefer) {
  2478. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  2479. // each other bottoming out with the base dtor. Therefore we emit non-base
  2480. // dtors on usage, even if there is no dtor definition in the TU.
  2481. if (D && isa<CXXDestructorDecl>(D) &&
  2482. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  2483. GD.getDtorType()))
  2484. addDeferredDeclToEmit(GD);
  2485. // This is the first use or definition of a mangled name. If there is a
  2486. // deferred decl with this name, remember that we need to emit it at the end
  2487. // of the file.
  2488. auto DDI = DeferredDecls.find(MangledName);
  2489. if (DDI != DeferredDecls.end()) {
  2490. // Move the potentially referenced deferred decl to the
  2491. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  2492. // don't need it anymore).
  2493. addDeferredDeclToEmit(DDI->second);
  2494. DeferredDecls.erase(DDI);
  2495. // Otherwise, there are cases we have to worry about where we're
  2496. // using a declaration for which we must emit a definition but where
  2497. // we might not find a top-level definition:
  2498. // - member functions defined inline in their classes
  2499. // - friend functions defined inline in some class
  2500. // - special member functions with implicit definitions
  2501. // If we ever change our AST traversal to walk into class methods,
  2502. // this will be unnecessary.
  2503. //
  2504. // We also don't emit a definition for a function if it's going to be an
  2505. // entry in a vtable, unless it's already marked as used.
  2506. } else if (getLangOpts().CPlusPlus && D) {
  2507. // Look for a declaration that's lexically in a record.
  2508. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  2509. FD = FD->getPreviousDecl()) {
  2510. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  2511. if (FD->doesThisDeclarationHaveABody()) {
  2512. addDeferredDeclToEmit(GD.getWithDecl(FD));
  2513. break;
  2514. }
  2515. }
  2516. }
  2517. }
  2518. }
  2519. // Make sure the result is of the requested type.
  2520. if (!IsIncompleteFunction) {
  2521. assert(F->getType()->getElementType() == Ty);
  2522. return F;
  2523. }
  2524. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  2525. return llvm::ConstantExpr::getBitCast(F, PTy);
  2526. }
  2527. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  2528. /// non-null, then this function will use the specified type if it has to
  2529. /// create it (this occurs when we see a definition of the function).
  2530. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  2531. llvm::Type *Ty,
  2532. bool ForVTable,
  2533. bool DontDefer,
  2534. ForDefinition_t IsForDefinition) {
  2535. // If there was no specific requested type, just convert it now.
  2536. if (!Ty) {
  2537. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2538. Ty = getTypes().ConvertType(FD->getType());
  2539. }
  2540. // Devirtualized destructor calls may come through here instead of via
  2541. // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
  2542. // of the complete destructor when necessary.
  2543. if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
  2544. if (getTarget().getCXXABI().isMicrosoft() &&
  2545. GD.getDtorType() == Dtor_Complete &&
  2546. DD->getParent()->getNumVBases() == 0)
  2547. GD = GlobalDecl(DD, Dtor_Base);
  2548. }
  2549. StringRef MangledName = getMangledName(GD);
  2550. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
  2551. /*IsThunk=*/false, llvm::AttributeList(),
  2552. IsForDefinition);
  2553. }
  2554. static const FunctionDecl *
  2555. GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
  2556. TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
  2557. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  2558. IdentifierInfo &CII = C.Idents.get(Name);
  2559. for (const auto &Result : DC->lookup(&CII))
  2560. if (const auto FD = dyn_cast<FunctionDecl>(Result))
  2561. return FD;
  2562. if (!C.getLangOpts().CPlusPlus)
  2563. return nullptr;
  2564. // Demangle the premangled name from getTerminateFn()
  2565. IdentifierInfo &CXXII =
  2566. (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
  2567. ? C.Idents.get("terminate")
  2568. : C.Idents.get(Name);
  2569. for (const auto &N : {"__cxxabiv1", "std"}) {
  2570. IdentifierInfo &NS = C.Idents.get(N);
  2571. for (const auto &Result : DC->lookup(&NS)) {
  2572. NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
  2573. if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
  2574. for (const auto &Result : LSD->lookup(&NS))
  2575. if ((ND = dyn_cast<NamespaceDecl>(Result)))
  2576. break;
  2577. if (ND)
  2578. for (const auto &Result : ND->lookup(&CXXII))
  2579. if (const auto *FD = dyn_cast<FunctionDecl>(Result))
  2580. return FD;
  2581. }
  2582. }
  2583. return nullptr;
  2584. }
  2585. /// CreateRuntimeFunction - Create a new runtime function with the specified
  2586. /// type and name.
  2587. llvm::FunctionCallee
  2588. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
  2589. llvm::AttributeList ExtraAttrs,
  2590. bool Local) {
  2591. llvm::Constant *C =
  2592. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  2593. /*DontDefer=*/false, /*IsThunk=*/false,
  2594. ExtraAttrs);
  2595. if (auto *F = dyn_cast<llvm::Function>(C)) {
  2596. if (F->empty()) {
  2597. F->setCallingConv(getRuntimeCC());
  2598. if (!Local && getTriple().isOSBinFormatCOFF() &&
  2599. !getCodeGenOpts().LTOVisibilityPublicStd &&
  2600. !getTriple().isWindowsGNUEnvironment()) {
  2601. const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
  2602. if (!FD || FD->hasAttr<DLLImportAttr>()) {
  2603. F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  2604. F->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2605. }
  2606. }
  2607. setDSOLocal(F);
  2608. }
  2609. }
  2610. return {FTy, C};
  2611. }
  2612. /// isTypeConstant - Determine whether an object of this type can be emitted
  2613. /// as a constant.
  2614. ///
  2615. /// If ExcludeCtor is true, the duration when the object's constructor runs
  2616. /// will not be considered. The caller will need to verify that the object is
  2617. /// not written to during its construction.
  2618. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  2619. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  2620. return false;
  2621. if (Context.getLangOpts().CPlusPlus) {
  2622. if (const CXXRecordDecl *Record
  2623. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  2624. return ExcludeCtor && !Record->hasMutableFields() &&
  2625. Record->hasTrivialDestructor();
  2626. }
  2627. return true;
  2628. }
  2629. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  2630. /// create and return an llvm GlobalVariable with the specified type. If there
  2631. /// is something in the module with the specified name, return it potentially
  2632. /// bitcasted to the right type.
  2633. ///
  2634. /// If D is non-null, it specifies a decl that correspond to this. This is used
  2635. /// to set the attributes on the global when it is first created.
  2636. ///
  2637. /// If IsForDefinition is true, it is guaranteed that an actual global with
  2638. /// type Ty will be returned, not conversion of a variable with the same
  2639. /// mangled name but some other type.
  2640. llvm::Constant *
  2641. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  2642. llvm::PointerType *Ty,
  2643. const VarDecl *D,
  2644. ForDefinition_t IsForDefinition) {
  2645. // Lookup the entry, lazily creating it if necessary.
  2646. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2647. if (Entry) {
  2648. if (WeakRefReferences.erase(Entry)) {
  2649. if (D && !D->hasAttr<WeakAttr>())
  2650. Entry->setLinkage(llvm::Function::ExternalLinkage);
  2651. }
  2652. // Handle dropped DLL attributes.
  2653. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  2654. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  2655. if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
  2656. getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
  2657. if (Entry->getType() == Ty)
  2658. return Entry;
  2659. // If there are two attempts to define the same mangled name, issue an
  2660. // error.
  2661. if (IsForDefinition && !Entry->isDeclaration()) {
  2662. GlobalDecl OtherGD;
  2663. const VarDecl *OtherD;
  2664. // Check that D is not yet in DiagnosedConflictingDefinitions is required
  2665. // to make sure that we issue an error only once.
  2666. if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
  2667. (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
  2668. (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
  2669. OtherD->hasInit() &&
  2670. DiagnosedConflictingDefinitions.insert(D).second) {
  2671. getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
  2672. << MangledName;
  2673. getDiags().Report(OtherGD.getDecl()->getLocation(),
  2674. diag::note_previous_definition);
  2675. }
  2676. }
  2677. // Make sure the result is of the correct type.
  2678. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
  2679. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  2680. // (If global is requested for a definition, we always need to create a new
  2681. // global, not just return a bitcast.)
  2682. if (!IsForDefinition)
  2683. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  2684. }
  2685. auto AddrSpace = GetGlobalVarAddressSpace(D);
  2686. auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
  2687. auto *GV = new llvm::GlobalVariable(
  2688. getModule(), Ty->getElementType(), false,
  2689. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  2690. llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
  2691. // If we already created a global with the same mangled name (but different
  2692. // type) before, take its name and remove it from its parent.
  2693. if (Entry) {
  2694. GV->takeName(Entry);
  2695. if (!Entry->use_empty()) {
  2696. llvm::Constant *NewPtrForOldDecl =
  2697. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2698. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2699. }
  2700. Entry->eraseFromParent();
  2701. }
  2702. // This is the first use or definition of a mangled name. If there is a
  2703. // deferred decl with this name, remember that we need to emit it at the end
  2704. // of the file.
  2705. auto DDI = DeferredDecls.find(MangledName);
  2706. if (DDI != DeferredDecls.end()) {
  2707. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  2708. // list, and remove it from DeferredDecls (since we don't need it anymore).
  2709. addDeferredDeclToEmit(DDI->second);
  2710. DeferredDecls.erase(DDI);
  2711. }
  2712. // Handle things which are present even on external declarations.
  2713. if (D) {
  2714. if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
  2715. getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
  2716. // FIXME: This code is overly simple and should be merged with other global
  2717. // handling.
  2718. GV->setConstant(isTypeConstant(D->getType(), false));
  2719. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2720. setLinkageForGV(GV, D);
  2721. if (D->getTLSKind()) {
  2722. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2723. CXXThreadLocals.push_back(D);
  2724. setTLSMode(GV, *D);
  2725. }
  2726. setGVProperties(GV, D);
  2727. // If required by the ABI, treat declarations of static data members with
  2728. // inline initializers as definitions.
  2729. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  2730. EmitGlobalVarDefinition(D);
  2731. }
  2732. // Emit section information for extern variables.
  2733. if (D->hasExternalStorage()) {
  2734. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  2735. GV->setSection(SA->getName());
  2736. }
  2737. // Handle XCore specific ABI requirements.
  2738. if (getTriple().getArch() == llvm::Triple::xcore &&
  2739. D->getLanguageLinkage() == CLanguageLinkage &&
  2740. D->getType().isConstant(Context) &&
  2741. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  2742. GV->setSection(".cp.rodata");
  2743. // Check if we a have a const declaration with an initializer, we may be
  2744. // able to emit it as available_externally to expose it's value to the
  2745. // optimizer.
  2746. if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
  2747. D->getType().isConstQualified() && !GV->hasInitializer() &&
  2748. !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
  2749. const auto *Record =
  2750. Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
  2751. bool HasMutableFields = Record && Record->hasMutableFields();
  2752. if (!HasMutableFields) {
  2753. const VarDecl *InitDecl;
  2754. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  2755. if (InitExpr) {
  2756. ConstantEmitter emitter(*this);
  2757. llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
  2758. if (Init) {
  2759. auto *InitType = Init->getType();
  2760. if (GV->getType()->getElementType() != InitType) {
  2761. // The type of the initializer does not match the definition.
  2762. // This happens when an initializer has a different type from
  2763. // the type of the global (because of padding at the end of a
  2764. // structure for instance).
  2765. GV->setName(StringRef());
  2766. // Make a new global with the correct type, this is now guaranteed
  2767. // to work.
  2768. auto *NewGV = cast<llvm::GlobalVariable>(
  2769. GetAddrOfGlobalVar(D, InitType, IsForDefinition));
  2770. // Erase the old global, since it is no longer used.
  2771. GV->eraseFromParent();
  2772. GV = NewGV;
  2773. } else {
  2774. GV->setInitializer(Init);
  2775. GV->setConstant(true);
  2776. GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
  2777. }
  2778. emitter.finalize(GV);
  2779. }
  2780. }
  2781. }
  2782. }
  2783. }
  2784. LangAS ExpectedAS =
  2785. D ? D->getType().getAddressSpace()
  2786. : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
  2787. assert(getContext().getTargetAddressSpace(ExpectedAS) ==
  2788. Ty->getPointerAddressSpace());
  2789. if (AddrSpace != ExpectedAS)
  2790. return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
  2791. ExpectedAS, Ty);
  2792. if (GV->isDeclaration())
  2793. getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
  2794. return GV;
  2795. }
  2796. llvm::Constant *
  2797. CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
  2798. ForDefinition_t IsForDefinition) {
  2799. const Decl *D = GD.getDecl();
  2800. if (isa<CXXConstructorDecl>(D))
  2801. return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
  2802. getFromCtorType(GD.getCtorType()),
  2803. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  2804. /*DontDefer=*/false, IsForDefinition);
  2805. else if (isa<CXXDestructorDecl>(D))
  2806. return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
  2807. getFromDtorType(GD.getDtorType()),
  2808. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  2809. /*DontDefer=*/false, IsForDefinition);
  2810. else if (isa<CXXMethodDecl>(D)) {
  2811. auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
  2812. cast<CXXMethodDecl>(D));
  2813. auto Ty = getTypes().GetFunctionType(*FInfo);
  2814. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2815. IsForDefinition);
  2816. } else if (isa<FunctionDecl>(D)) {
  2817. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2818. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2819. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2820. IsForDefinition);
  2821. } else
  2822. return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
  2823. IsForDefinition);
  2824. }
  2825. llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
  2826. StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
  2827. unsigned Alignment) {
  2828. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  2829. llvm::GlobalVariable *OldGV = nullptr;
  2830. if (GV) {
  2831. // Check if the variable has the right type.
  2832. if (GV->getType()->getElementType() == Ty)
  2833. return GV;
  2834. // Because C++ name mangling, the only way we can end up with an already
  2835. // existing global with the same name is if it has been declared extern "C".
  2836. assert(GV->isDeclaration() && "Declaration has wrong type!");
  2837. OldGV = GV;
  2838. }
  2839. // Create a new variable.
  2840. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  2841. Linkage, nullptr, Name);
  2842. if (OldGV) {
  2843. // Replace occurrences of the old variable if needed.
  2844. GV->takeName(OldGV);
  2845. if (!OldGV->use_empty()) {
  2846. llvm::Constant *NewPtrForOldDecl =
  2847. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  2848. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  2849. }
  2850. OldGV->eraseFromParent();
  2851. }
  2852. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  2853. !GV->hasAvailableExternallyLinkage())
  2854. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  2855. GV->setAlignment(Alignment);
  2856. return GV;
  2857. }
  2858. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  2859. /// given global variable. If Ty is non-null and if the global doesn't exist,
  2860. /// then it will be created with the specified type instead of whatever the
  2861. /// normal requested type would be. If IsForDefinition is true, it is guaranteed
  2862. /// that an actual global with type Ty will be returned, not conversion of a
  2863. /// variable with the same mangled name but some other type.
  2864. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  2865. llvm::Type *Ty,
  2866. ForDefinition_t IsForDefinition) {
  2867. assert(D->hasGlobalStorage() && "Not a global variable");
  2868. QualType ASTTy = D->getType();
  2869. if (!Ty)
  2870. Ty = getTypes().ConvertTypeForMem(ASTTy);
  2871. llvm::PointerType *PTy =
  2872. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  2873. StringRef MangledName = getMangledName(D);
  2874. return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
  2875. }
  2876. /// CreateRuntimeVariable - Create a new runtime global variable with the
  2877. /// specified type and name.
  2878. llvm::Constant *
  2879. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  2880. StringRef Name) {
  2881. auto *Ret =
  2882. GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
  2883. setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
  2884. return Ret;
  2885. }
  2886. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  2887. assert(!D->getInit() && "Cannot emit definite definitions here!");
  2888. StringRef MangledName = getMangledName(D);
  2889. llvm::GlobalValue *GV = GetGlobalValue(MangledName);
  2890. // We already have a definition, not declaration, with the same mangled name.
  2891. // Emitting of declaration is not required (and actually overwrites emitted
  2892. // definition).
  2893. if (GV && !GV->isDeclaration())
  2894. return;
  2895. // If we have not seen a reference to this variable yet, place it into the
  2896. // deferred declarations table to be emitted if needed later.
  2897. if (!MustBeEmitted(D) && !GV) {
  2898. DeferredDecls[MangledName] = D;
  2899. return;
  2900. }
  2901. // The tentative definition is the only definition.
  2902. EmitGlobalVarDefinition(D);
  2903. }
  2904. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  2905. return Context.toCharUnitsFromBits(
  2906. getDataLayout().getTypeStoreSizeInBits(Ty));
  2907. }
  2908. LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
  2909. LangAS AddrSpace = LangAS::Default;
  2910. if (LangOpts.OpenCL) {
  2911. AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
  2912. assert(AddrSpace == LangAS::opencl_global ||
  2913. AddrSpace == LangAS::opencl_constant ||
  2914. AddrSpace == LangAS::opencl_local ||
  2915. AddrSpace >= LangAS::FirstTargetAddressSpace);
  2916. return AddrSpace;
  2917. }
  2918. if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  2919. if (D && D->hasAttr<CUDAConstantAttr>())
  2920. return LangAS::cuda_constant;
  2921. else if (D && D->hasAttr<CUDASharedAttr>())
  2922. return LangAS::cuda_shared;
  2923. else if (D && D->hasAttr<CUDADeviceAttr>())
  2924. return LangAS::cuda_device;
  2925. else if (D && D->getType().isConstQualified())
  2926. return LangAS::cuda_constant;
  2927. else
  2928. return LangAS::cuda_device;
  2929. }
  2930. return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
  2931. }
  2932. LangAS CodeGenModule::getStringLiteralAddressSpace() const {
  2933. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  2934. if (LangOpts.OpenCL)
  2935. return LangAS::opencl_constant;
  2936. if (auto AS = getTarget().getConstantAddressSpace())
  2937. return AS.getValue();
  2938. return LangAS::Default;
  2939. }
  2940. // In address space agnostic languages, string literals are in default address
  2941. // space in AST. However, certain targets (e.g. amdgcn) request them to be
  2942. // emitted in constant address space in LLVM IR. To be consistent with other
  2943. // parts of AST, string literal global variables in constant address space
  2944. // need to be casted to default address space before being put into address
  2945. // map and referenced by other part of CodeGen.
  2946. // In OpenCL, string literals are in constant address space in AST, therefore
  2947. // they should not be casted to default address space.
  2948. static llvm::Constant *
  2949. castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
  2950. llvm::GlobalVariable *GV) {
  2951. llvm::Constant *Cast = GV;
  2952. if (!CGM.getLangOpts().OpenCL) {
  2953. if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
  2954. if (AS != LangAS::Default)
  2955. Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
  2956. CGM, GV, AS.getValue(), LangAS::Default,
  2957. GV->getValueType()->getPointerTo(
  2958. CGM.getContext().getTargetAddressSpace(LangAS::Default)));
  2959. }
  2960. }
  2961. return Cast;
  2962. }
  2963. template<typename SomeDecl>
  2964. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  2965. llvm::GlobalValue *GV) {
  2966. if (!getLangOpts().CPlusPlus)
  2967. return;
  2968. // Must have 'used' attribute, or else inline assembly can't rely on
  2969. // the name existing.
  2970. if (!D->template hasAttr<UsedAttr>())
  2971. return;
  2972. // Must have internal linkage and an ordinary name.
  2973. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  2974. return;
  2975. // Must be in an extern "C" context. Entities declared directly within
  2976. // a record are not extern "C" even if the record is in such a context.
  2977. const SomeDecl *First = D->getFirstDecl();
  2978. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  2979. return;
  2980. // OK, this is an internal linkage entity inside an extern "C" linkage
  2981. // specification. Make a note of that so we can give it the "expected"
  2982. // mangled name if nothing else is using that name.
  2983. std::pair<StaticExternCMap::iterator, bool> R =
  2984. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  2985. // If we have multiple internal linkage entities with the same name
  2986. // in extern "C" regions, none of them gets that name.
  2987. if (!R.second)
  2988. R.first->second = nullptr;
  2989. }
  2990. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  2991. if (!CGM.supportsCOMDAT())
  2992. return false;
  2993. if (D.hasAttr<SelectAnyAttr>())
  2994. return true;
  2995. GVALinkage Linkage;
  2996. if (auto *VD = dyn_cast<VarDecl>(&D))
  2997. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  2998. else
  2999. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  3000. switch (Linkage) {
  3001. case GVA_Internal:
  3002. case GVA_AvailableExternally:
  3003. case GVA_StrongExternal:
  3004. return false;
  3005. case GVA_DiscardableODR:
  3006. case GVA_StrongODR:
  3007. return true;
  3008. }
  3009. llvm_unreachable("No such linkage");
  3010. }
  3011. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  3012. llvm::GlobalObject &GO) {
  3013. if (!shouldBeInCOMDAT(*this, D))
  3014. return;
  3015. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  3016. }
  3017. /// Pass IsTentative as true if you want to create a tentative definition.
  3018. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
  3019. bool IsTentative) {
  3020. // OpenCL global variables of sampler type are translated to function calls,
  3021. // therefore no need to be translated.
  3022. QualType ASTTy = D->getType();
  3023. if (getLangOpts().OpenCL && ASTTy->isSamplerT())
  3024. return;
  3025. // If this is OpenMP device, check if it is legal to emit this global
  3026. // normally.
  3027. if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
  3028. OpenMPRuntime->emitTargetGlobalVariable(D))
  3029. return;
  3030. llvm::Constant *Init = nullptr;
  3031. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  3032. bool NeedsGlobalCtor = false;
  3033. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  3034. const VarDecl *InitDecl;
  3035. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  3036. Optional<ConstantEmitter> emitter;
  3037. // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
  3038. // as part of their declaration." Sema has already checked for
  3039. // error cases, so we just need to set Init to UndefValue.
  3040. bool IsCUDASharedVar =
  3041. getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
  3042. // Shadows of initialized device-side global variables are also left
  3043. // undefined.
  3044. bool IsCUDAShadowVar =
  3045. !getLangOpts().CUDAIsDevice &&
  3046. (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
  3047. D->hasAttr<CUDASharedAttr>());
  3048. if (getLangOpts().CUDA && (IsCUDASharedVar || IsCUDAShadowVar))
  3049. Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
  3050. else if (!InitExpr) {
  3051. // This is a tentative definition; tentative definitions are
  3052. // implicitly initialized with { 0 }.
  3053. //
  3054. // Note that tentative definitions are only emitted at the end of
  3055. // a translation unit, so they should never have incomplete
  3056. // type. In addition, EmitTentativeDefinition makes sure that we
  3057. // never attempt to emit a tentative definition if a real one
  3058. // exists. A use may still exists, however, so we still may need
  3059. // to do a RAUW.
  3060. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  3061. Init = EmitNullConstant(D->getType());
  3062. } else {
  3063. initializedGlobalDecl = GlobalDecl(D);
  3064. emitter.emplace(*this);
  3065. Init = emitter->tryEmitForInitializer(*InitDecl);
  3066. if (!Init) {
  3067. QualType T = InitExpr->getType();
  3068. if (D->getType()->isReferenceType())
  3069. T = D->getType();
  3070. if (getLangOpts().CPlusPlus) {
  3071. Init = EmitNullConstant(T);
  3072. NeedsGlobalCtor = true;
  3073. } else {
  3074. ErrorUnsupported(D, "static initializer");
  3075. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  3076. }
  3077. } else {
  3078. // We don't need an initializer, so remove the entry for the delayed
  3079. // initializer position (just in case this entry was delayed) if we
  3080. // also don't need to register a destructor.
  3081. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  3082. DelayedCXXInitPosition.erase(D);
  3083. }
  3084. }
  3085. llvm::Type* InitType = Init->getType();
  3086. llvm::Constant *Entry =
  3087. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
  3088. // Strip off a bitcast if we got one back.
  3089. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  3090. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  3091. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  3092. // All zero index gep.
  3093. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  3094. Entry = CE->getOperand(0);
  3095. }
  3096. // Entry is now either a Function or GlobalVariable.
  3097. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  3098. // We have a definition after a declaration with the wrong type.
  3099. // We must make a new GlobalVariable* and update everything that used OldGV
  3100. // (a declaration or tentative definition) with the new GlobalVariable*
  3101. // (which will be a definition).
  3102. //
  3103. // This happens if there is a prototype for a global (e.g.
  3104. // "extern int x[];") and then a definition of a different type (e.g.
  3105. // "int x[10];"). This also happens when an initializer has a different type
  3106. // from the type of the global (this happens with unions).
  3107. if (!GV || GV->getType()->getElementType() != InitType ||
  3108. GV->getType()->getAddressSpace() !=
  3109. getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
  3110. // Move the old entry aside so that we'll create a new one.
  3111. Entry->setName(StringRef());
  3112. // Make a new global with the correct type, this is now guaranteed to work.
  3113. GV = cast<llvm::GlobalVariable>(
  3114. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
  3115. // Replace all uses of the old global with the new global
  3116. llvm::Constant *NewPtrForOldDecl =
  3117. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  3118. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  3119. // Erase the old global, since it is no longer used.
  3120. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  3121. }
  3122. MaybeHandleStaticInExternC(D, GV);
  3123. if (D->hasAttr<AnnotateAttr>())
  3124. AddGlobalAnnotations(D, GV);
  3125. // Set the llvm linkage type as appropriate.
  3126. llvm::GlobalValue::LinkageTypes Linkage =
  3127. getLLVMLinkageVarDefinition(D, GV->isConstant());
  3128. // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
  3129. // the device. [...]"
  3130. // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
  3131. // __device__, declares a variable that: [...]
  3132. // Is accessible from all the threads within the grid and from the host
  3133. // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
  3134. // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
  3135. if (GV && LangOpts.CUDA) {
  3136. if (LangOpts.CUDAIsDevice) {
  3137. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
  3138. GV->setExternallyInitialized(true);
  3139. } else {
  3140. // Host-side shadows of external declarations of device-side
  3141. // global variables become internal definitions. These have to
  3142. // be internal in order to prevent name conflicts with global
  3143. // host variables with the same name in a different TUs.
  3144. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
  3145. Linkage = llvm::GlobalValue::InternalLinkage;
  3146. // Shadow variables and their properties must be registered
  3147. // with CUDA runtime.
  3148. unsigned Flags = 0;
  3149. if (!D->hasDefinition())
  3150. Flags |= CGCUDARuntime::ExternDeviceVar;
  3151. if (D->hasAttr<CUDAConstantAttr>())
  3152. Flags |= CGCUDARuntime::ConstantDeviceVar;
  3153. // Extern global variables will be registered in the TU where they are
  3154. // defined.
  3155. if (!D->hasExternalStorage())
  3156. getCUDARuntime().registerDeviceVar(*GV, Flags);
  3157. } else if (D->hasAttr<CUDASharedAttr>())
  3158. // __shared__ variables are odd. Shadows do get created, but
  3159. // they are not registered with the CUDA runtime, so they
  3160. // can't really be used to access their device-side
  3161. // counterparts. It's not clear yet whether it's nvcc's bug or
  3162. // a feature, but we've got to do the same for compatibility.
  3163. Linkage = llvm::GlobalValue::InternalLinkage;
  3164. }
  3165. }
  3166. GV->setInitializer(Init);
  3167. if (emitter) emitter->finalize(GV);
  3168. // If it is safe to mark the global 'constant', do so now.
  3169. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  3170. isTypeConstant(D->getType(), true));
  3171. // If it is in a read-only section, mark it 'constant'.
  3172. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  3173. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  3174. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  3175. GV->setConstant(true);
  3176. }
  3177. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  3178. // On Darwin, if the normal linkage of a C++ thread_local variable is
  3179. // LinkOnce or Weak, we keep the normal linkage to prevent multiple
  3180. // copies within a linkage unit; otherwise, the backing variable has
  3181. // internal linkage and all accesses should just be calls to the
  3182. // Itanium-specified entry point, which has the normal linkage of the
  3183. // variable. This is to preserve the ability to change the implementation
  3184. // behind the scenes.
  3185. if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
  3186. Context.getTargetInfo().getTriple().isOSDarwin() &&
  3187. !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
  3188. !llvm::GlobalVariable::isWeakLinkage(Linkage))
  3189. Linkage = llvm::GlobalValue::InternalLinkage;
  3190. GV->setLinkage(Linkage);
  3191. if (D->hasAttr<DLLImportAttr>())
  3192. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  3193. else if (D->hasAttr<DLLExportAttr>())
  3194. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  3195. else
  3196. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  3197. if (Linkage == llvm::GlobalVariable::CommonLinkage) {
  3198. // common vars aren't constant even if declared const.
  3199. GV->setConstant(false);
  3200. // Tentative definition of global variables may be initialized with
  3201. // non-zero null pointers. In this case they should have weak linkage
  3202. // since common linkage must have zero initializer and must not have
  3203. // explicit section therefore cannot have non-zero initial value.
  3204. if (!GV->getInitializer()->isNullValue())
  3205. GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
  3206. }
  3207. setNonAliasAttributes(D, GV);
  3208. if (D->getTLSKind() && !GV->isThreadLocal()) {
  3209. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  3210. CXXThreadLocals.push_back(D);
  3211. setTLSMode(GV, *D);
  3212. }
  3213. maybeSetTrivialComdat(*D, *GV);
  3214. // Emit the initializer function if necessary.
  3215. if (NeedsGlobalCtor || NeedsGlobalDtor)
  3216. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  3217. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  3218. // Emit global variable debug information.
  3219. if (CGDebugInfo *DI = getModuleDebugInfo())
  3220. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  3221. DI->EmitGlobalVariable(GV, D);
  3222. }
  3223. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  3224. CodeGenModule &CGM, const VarDecl *D,
  3225. bool NoCommon) {
  3226. // Don't give variables common linkage if -fno-common was specified unless it
  3227. // was overridden by a NoCommon attribute.
  3228. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  3229. return true;
  3230. // C11 6.9.2/2:
  3231. // A declaration of an identifier for an object that has file scope without
  3232. // an initializer, and without a storage-class specifier or with the
  3233. // storage-class specifier static, constitutes a tentative definition.
  3234. if (D->getInit() || D->hasExternalStorage())
  3235. return true;
  3236. // A variable cannot be both common and exist in a section.
  3237. if (D->hasAttr<SectionAttr>())
  3238. return true;
  3239. // A variable cannot be both common and exist in a section.
  3240. // We don't try to determine which is the right section in the front-end.
  3241. // If no specialized section name is applicable, it will resort to default.
  3242. if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
  3243. D->hasAttr<PragmaClangDataSectionAttr>() ||
  3244. D->hasAttr<PragmaClangRodataSectionAttr>())
  3245. return true;
  3246. // Thread local vars aren't considered common linkage.
  3247. if (D->getTLSKind())
  3248. return true;
  3249. // Tentative definitions marked with WeakImportAttr are true definitions.
  3250. if (D->hasAttr<WeakImportAttr>())
  3251. return true;
  3252. // A variable cannot be both common and exist in a comdat.
  3253. if (shouldBeInCOMDAT(CGM, *D))
  3254. return true;
  3255. // Declarations with a required alignment do not have common linkage in MSVC
  3256. // mode.
  3257. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  3258. if (D->hasAttr<AlignedAttr>())
  3259. return true;
  3260. QualType VarType = D->getType();
  3261. if (Context.isAlignmentRequired(VarType))
  3262. return true;
  3263. if (const auto *RT = VarType->getAs<RecordType>()) {
  3264. const RecordDecl *RD = RT->getDecl();
  3265. for (const FieldDecl *FD : RD->fields()) {
  3266. if (FD->isBitField())
  3267. continue;
  3268. if (FD->hasAttr<AlignedAttr>())
  3269. return true;
  3270. if (Context.isAlignmentRequired(FD->getType()))
  3271. return true;
  3272. }
  3273. }
  3274. }
  3275. // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
  3276. // common symbols, so symbols with greater alignment requirements cannot be
  3277. // common.
  3278. // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
  3279. // alignments for common symbols via the aligncomm directive, so this
  3280. // restriction only applies to MSVC environments.
  3281. if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
  3282. Context.getTypeAlignIfKnown(D->getType()) >
  3283. Context.toBits(CharUnits::fromQuantity(32)))
  3284. return true;
  3285. return false;
  3286. }
  3287. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  3288. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  3289. if (Linkage == GVA_Internal)
  3290. return llvm::Function::InternalLinkage;
  3291. if (D->hasAttr<WeakAttr>()) {
  3292. if (IsConstantVariable)
  3293. return llvm::GlobalVariable::WeakODRLinkage;
  3294. else
  3295. return llvm::GlobalVariable::WeakAnyLinkage;
  3296. }
  3297. if (const auto *FD = D->getAsFunction())
  3298. if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
  3299. return llvm::GlobalVariable::LinkOnceAnyLinkage;
  3300. // We are guaranteed to have a strong definition somewhere else,
  3301. // so we can use available_externally linkage.
  3302. if (Linkage == GVA_AvailableExternally)
  3303. return llvm::GlobalValue::AvailableExternallyLinkage;
  3304. // Note that Apple's kernel linker doesn't support symbol
  3305. // coalescing, so we need to avoid linkonce and weak linkages there.
  3306. // Normally, this means we just map to internal, but for explicit
  3307. // instantiations we'll map to external.
  3308. // In C++, the compiler has to emit a definition in every translation unit
  3309. // that references the function. We should use linkonce_odr because
  3310. // a) if all references in this translation unit are optimized away, we
  3311. // don't need to codegen it. b) if the function persists, it needs to be
  3312. // merged with other definitions. c) C++ has the ODR, so we know the
  3313. // definition is dependable.
  3314. if (Linkage == GVA_DiscardableODR)
  3315. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  3316. : llvm::Function::InternalLinkage;
  3317. // An explicit instantiation of a template has weak linkage, since
  3318. // explicit instantiations can occur in multiple translation units
  3319. // and must all be equivalent. However, we are not allowed to
  3320. // throw away these explicit instantiations.
  3321. //
  3322. // We don't currently support CUDA device code spread out across multiple TUs,
  3323. // so say that CUDA templates are either external (for kernels) or internal.
  3324. // This lets llvm perform aggressive inter-procedural optimizations.
  3325. if (Linkage == GVA_StrongODR) {
  3326. if (Context.getLangOpts().AppleKext)
  3327. return llvm::Function::ExternalLinkage;
  3328. if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
  3329. return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
  3330. : llvm::Function::InternalLinkage;
  3331. return llvm::Function::WeakODRLinkage;
  3332. }
  3333. // C++ doesn't have tentative definitions and thus cannot have common
  3334. // linkage.
  3335. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  3336. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  3337. CodeGenOpts.NoCommon))
  3338. return llvm::GlobalVariable::CommonLinkage;
  3339. // selectany symbols are externally visible, so use weak instead of
  3340. // linkonce. MSVC optimizes away references to const selectany globals, so
  3341. // all definitions should be the same and ODR linkage should be used.
  3342. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  3343. if (D->hasAttr<SelectAnyAttr>())
  3344. return llvm::GlobalVariable::WeakODRLinkage;
  3345. // Otherwise, we have strong external linkage.
  3346. assert(Linkage == GVA_StrongExternal);
  3347. return llvm::GlobalVariable::ExternalLinkage;
  3348. }
  3349. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  3350. const VarDecl *VD, bool IsConstant) {
  3351. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  3352. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  3353. }
  3354. /// Replace the uses of a function that was declared with a non-proto type.
  3355. /// We want to silently drop extra arguments from call sites
  3356. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  3357. llvm::Function *newFn) {
  3358. // Fast path.
  3359. if (old->use_empty()) return;
  3360. llvm::Type *newRetTy = newFn->getReturnType();
  3361. SmallVector<llvm::Value*, 4> newArgs;
  3362. SmallVector<llvm::OperandBundleDef, 1> newBundles;
  3363. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  3364. ui != ue; ) {
  3365. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  3366. llvm::User *user = use->getUser();
  3367. // Recognize and replace uses of bitcasts. Most calls to
  3368. // unprototyped functions will use bitcasts.
  3369. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  3370. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  3371. replaceUsesOfNonProtoConstant(bitcast, newFn);
  3372. continue;
  3373. }
  3374. // Recognize calls to the function.
  3375. llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
  3376. if (!callSite) continue;
  3377. if (!callSite->isCallee(&*use))
  3378. continue;
  3379. // If the return types don't match exactly, then we can't
  3380. // transform this call unless it's dead.
  3381. if (callSite->getType() != newRetTy && !callSite->use_empty())
  3382. continue;
  3383. // Get the call site's attribute list.
  3384. SmallVector<llvm::AttributeSet, 8> newArgAttrs;
  3385. llvm::AttributeList oldAttrs = callSite->getAttributes();
  3386. // If the function was passed too few arguments, don't transform.
  3387. unsigned newNumArgs = newFn->arg_size();
  3388. if (callSite->arg_size() < newNumArgs)
  3389. continue;
  3390. // If extra arguments were passed, we silently drop them.
  3391. // If any of the types mismatch, we don't transform.
  3392. unsigned argNo = 0;
  3393. bool dontTransform = false;
  3394. for (llvm::Argument &A : newFn->args()) {
  3395. if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
  3396. dontTransform = true;
  3397. break;
  3398. }
  3399. // Add any parameter attributes.
  3400. newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
  3401. argNo++;
  3402. }
  3403. if (dontTransform)
  3404. continue;
  3405. // Okay, we can transform this. Create the new call instruction and copy
  3406. // over the required information.
  3407. newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
  3408. // Copy over any operand bundles.
  3409. callSite->getOperandBundlesAsDefs(newBundles);
  3410. llvm::CallBase *newCall;
  3411. if (dyn_cast<llvm::CallInst>(callSite)) {
  3412. newCall =
  3413. llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
  3414. } else {
  3415. auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
  3416. newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
  3417. oldInvoke->getUnwindDest(), newArgs,
  3418. newBundles, "", callSite);
  3419. }
  3420. newArgs.clear(); // for the next iteration
  3421. if (!newCall->getType()->isVoidTy())
  3422. newCall->takeName(callSite);
  3423. newCall->setAttributes(llvm::AttributeList::get(
  3424. newFn->getContext(), oldAttrs.getFnAttributes(),
  3425. oldAttrs.getRetAttributes(), newArgAttrs));
  3426. newCall->setCallingConv(callSite->getCallingConv());
  3427. // Finally, remove the old call, replacing any uses with the new one.
  3428. if (!callSite->use_empty())
  3429. callSite->replaceAllUsesWith(newCall);
  3430. // Copy debug location attached to CI.
  3431. if (callSite->getDebugLoc())
  3432. newCall->setDebugLoc(callSite->getDebugLoc());
  3433. callSite->eraseFromParent();
  3434. }
  3435. }
  3436. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  3437. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  3438. /// existing call uses of the old function in the module, this adjusts them to
  3439. /// call the new function directly.
  3440. ///
  3441. /// This is not just a cleanup: the always_inline pass requires direct calls to
  3442. /// functions to be able to inline them. If there is a bitcast in the way, it
  3443. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  3444. /// run at -O0.
  3445. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  3446. llvm::Function *NewFn) {
  3447. // If we're redefining a global as a function, don't transform it.
  3448. if (!isa<llvm::Function>(Old)) return;
  3449. replaceUsesOfNonProtoConstant(Old, NewFn);
  3450. }
  3451. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  3452. auto DK = VD->isThisDeclarationADefinition();
  3453. if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
  3454. return;
  3455. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  3456. // If we have a definition, this might be a deferred decl. If the
  3457. // instantiation is explicit, make sure we emit it at the end.
  3458. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  3459. GetAddrOfGlobalVar(VD);
  3460. EmitTopLevelDecl(VD);
  3461. }
  3462. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  3463. llvm::GlobalValue *GV) {
  3464. const auto *D = cast<FunctionDecl>(GD.getDecl());
  3465. // Compute the function info and LLVM type.
  3466. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  3467. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  3468. // Get or create the prototype for the function.
  3469. if (!GV || (GV->getType()->getElementType() != Ty))
  3470. GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
  3471. /*DontDefer=*/true,
  3472. ForDefinition));
  3473. // Already emitted.
  3474. if (!GV->isDeclaration())
  3475. return;
  3476. // We need to set linkage and visibility on the function before
  3477. // generating code for it because various parts of IR generation
  3478. // want to propagate this information down (e.g. to local static
  3479. // declarations).
  3480. auto *Fn = cast<llvm::Function>(GV);
  3481. setFunctionLinkage(GD, Fn);
  3482. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  3483. setGVProperties(Fn, GD);
  3484. MaybeHandleStaticInExternC(D, Fn);
  3485. maybeSetTrivialComdat(*D, *Fn);
  3486. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  3487. setNonAliasAttributes(GD, Fn);
  3488. SetLLVMFunctionAttributesForDefinition(D, Fn);
  3489. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  3490. AddGlobalCtor(Fn, CA->getPriority());
  3491. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  3492. AddGlobalDtor(Fn, DA->getPriority());
  3493. if (D->hasAttr<AnnotateAttr>())
  3494. AddGlobalAnnotations(D, Fn);
  3495. }
  3496. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  3497. const auto *D = cast<ValueDecl>(GD.getDecl());
  3498. const AliasAttr *AA = D->getAttr<AliasAttr>();
  3499. assert(AA && "Not an alias?");
  3500. StringRef MangledName = getMangledName(GD);
  3501. if (AA->getAliasee() == MangledName) {
  3502. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  3503. return;
  3504. }
  3505. // If there is a definition in the module, then it wins over the alias.
  3506. // This is dubious, but allow it to be safe. Just ignore the alias.
  3507. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3508. if (Entry && !Entry->isDeclaration())
  3509. return;
  3510. Aliases.push_back(GD);
  3511. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  3512. // Create a reference to the named value. This ensures that it is emitted
  3513. // if a deferred decl.
  3514. llvm::Constant *Aliasee;
  3515. if (isa<llvm::FunctionType>(DeclTy))
  3516. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  3517. /*ForVTable=*/false);
  3518. else
  3519. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  3520. llvm::PointerType::getUnqual(DeclTy),
  3521. /*D=*/nullptr);
  3522. // Create the new alias itself, but don't set a name yet.
  3523. auto *GA = llvm::GlobalAlias::create(
  3524. DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
  3525. if (Entry) {
  3526. if (GA->getAliasee() == Entry) {
  3527. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  3528. return;
  3529. }
  3530. assert(Entry->isDeclaration());
  3531. // If there is a declaration in the module, then we had an extern followed
  3532. // by the alias, as in:
  3533. // extern int test6();
  3534. // ...
  3535. // int test6() __attribute__((alias("test7")));
  3536. //
  3537. // Remove it and replace uses of it with the alias.
  3538. GA->takeName(Entry);
  3539. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  3540. Entry->getType()));
  3541. Entry->eraseFromParent();
  3542. } else {
  3543. GA->setName(MangledName);
  3544. }
  3545. // Set attributes which are particular to an alias; this is a
  3546. // specialization of the attributes which may be set on a global
  3547. // variable/function.
  3548. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  3549. D->isWeakImported()) {
  3550. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  3551. }
  3552. if (const auto *VD = dyn_cast<VarDecl>(D))
  3553. if (VD->getTLSKind())
  3554. setTLSMode(GA, *VD);
  3555. SetCommonAttributes(GD, GA);
  3556. }
  3557. void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
  3558. const auto *D = cast<ValueDecl>(GD.getDecl());
  3559. const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
  3560. assert(IFA && "Not an ifunc?");
  3561. StringRef MangledName = getMangledName(GD);
  3562. if (IFA->getResolver() == MangledName) {
  3563. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  3564. return;
  3565. }
  3566. // Report an error if some definition overrides ifunc.
  3567. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3568. if (Entry && !Entry->isDeclaration()) {
  3569. GlobalDecl OtherGD;
  3570. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  3571. DiagnosedConflictingDefinitions.insert(GD).second) {
  3572. Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
  3573. << MangledName;
  3574. Diags.Report(OtherGD.getDecl()->getLocation(),
  3575. diag::note_previous_definition);
  3576. }
  3577. return;
  3578. }
  3579. Aliases.push_back(GD);
  3580. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  3581. llvm::Constant *Resolver =
  3582. GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
  3583. /*ForVTable=*/false);
  3584. llvm::GlobalIFunc *GIF =
  3585. llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
  3586. "", Resolver, &getModule());
  3587. if (Entry) {
  3588. if (GIF->getResolver() == Entry) {
  3589. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  3590. return;
  3591. }
  3592. assert(Entry->isDeclaration());
  3593. // If there is a declaration in the module, then we had an extern followed
  3594. // by the ifunc, as in:
  3595. // extern int test();
  3596. // ...
  3597. // int test() __attribute__((ifunc("resolver")));
  3598. //
  3599. // Remove it and replace uses of it with the ifunc.
  3600. GIF->takeName(Entry);
  3601. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
  3602. Entry->getType()));
  3603. Entry->eraseFromParent();
  3604. } else
  3605. GIF->setName(MangledName);
  3606. SetCommonAttributes(GD, GIF);
  3607. }
  3608. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  3609. ArrayRef<llvm::Type*> Tys) {
  3610. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  3611. Tys);
  3612. }
  3613. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  3614. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  3615. const StringLiteral *Literal, bool TargetIsLSB,
  3616. bool &IsUTF16, unsigned &StringLength) {
  3617. StringRef String = Literal->getString();
  3618. unsigned NumBytes = String.size();
  3619. // Check for simple case.
  3620. if (!Literal->containsNonAsciiOrNull()) {
  3621. StringLength = NumBytes;
  3622. return *Map.insert(std::make_pair(String, nullptr)).first;
  3623. }
  3624. // Otherwise, convert the UTF8 literals into a string of shorts.
  3625. IsUTF16 = true;
  3626. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  3627. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  3628. llvm::UTF16 *ToPtr = &ToBuf[0];
  3629. (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  3630. ToPtr + NumBytes, llvm::strictConversion);
  3631. // ConvertUTF8toUTF16 returns the length in ToPtr.
  3632. StringLength = ToPtr - &ToBuf[0];
  3633. // Add an explicit null.
  3634. *ToPtr = 0;
  3635. return *Map.insert(std::make_pair(
  3636. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  3637. (StringLength + 1) * 2),
  3638. nullptr)).first;
  3639. }
  3640. ConstantAddress
  3641. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  3642. unsigned StringLength = 0;
  3643. bool isUTF16 = false;
  3644. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  3645. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  3646. getDataLayout().isLittleEndian(), isUTF16,
  3647. StringLength);
  3648. if (auto *C = Entry.second)
  3649. return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
  3650. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  3651. llvm::Constant *Zeros[] = { Zero, Zero };
  3652. const ASTContext &Context = getContext();
  3653. const llvm::Triple &Triple = getTriple();
  3654. const auto CFRuntime = getLangOpts().CFRuntime;
  3655. const bool IsSwiftABI =
  3656. static_cast<unsigned>(CFRuntime) >=
  3657. static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
  3658. const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
  3659. // If we don't already have it, get __CFConstantStringClassReference.
  3660. if (!CFConstantStringClassRef) {
  3661. const char *CFConstantStringClassName = "__CFConstantStringClassReference";
  3662. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  3663. Ty = llvm::ArrayType::get(Ty, 0);
  3664. switch (CFRuntime) {
  3665. default: break;
  3666. case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
  3667. case LangOptions::CoreFoundationABI::Swift5_0:
  3668. CFConstantStringClassName =
  3669. Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
  3670. : "$s10Foundation19_NSCFConstantStringCN";
  3671. Ty = IntPtrTy;
  3672. break;
  3673. case LangOptions::CoreFoundationABI::Swift4_2:
  3674. CFConstantStringClassName =
  3675. Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
  3676. : "$S10Foundation19_NSCFConstantStringCN";
  3677. Ty = IntPtrTy;
  3678. break;
  3679. case LangOptions::CoreFoundationABI::Swift4_1:
  3680. CFConstantStringClassName =
  3681. Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
  3682. : "__T010Foundation19_NSCFConstantStringCN";
  3683. Ty = IntPtrTy;
  3684. break;
  3685. }
  3686. llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
  3687. if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
  3688. llvm::GlobalValue *GV = nullptr;
  3689. if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
  3690. IdentifierInfo &II = Context.Idents.get(GV->getName());
  3691. TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
  3692. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  3693. const VarDecl *VD = nullptr;
  3694. for (const auto &Result : DC->lookup(&II))
  3695. if ((VD = dyn_cast<VarDecl>(Result)))
  3696. break;
  3697. if (Triple.isOSBinFormatELF()) {
  3698. if (!VD)
  3699. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3700. } else {
  3701. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3702. if (!VD || !VD->hasAttr<DLLExportAttr>())
  3703. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  3704. else
  3705. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  3706. }
  3707. setDSOLocal(GV);
  3708. }
  3709. }
  3710. // Decay array -> ptr
  3711. CFConstantStringClassRef =
  3712. IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
  3713. : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
  3714. }
  3715. QualType CFTy = Context.getCFConstantStringType();
  3716. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  3717. ConstantInitBuilder Builder(*this);
  3718. auto Fields = Builder.beginStruct(STy);
  3719. // Class pointer.
  3720. Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
  3721. // Flags.
  3722. if (IsSwiftABI) {
  3723. Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
  3724. Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
  3725. } else {
  3726. Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
  3727. }
  3728. // String pointer.
  3729. llvm::Constant *C = nullptr;
  3730. if (isUTF16) {
  3731. auto Arr = llvm::makeArrayRef(
  3732. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  3733. Entry.first().size() / 2);
  3734. C = llvm::ConstantDataArray::get(VMContext, Arr);
  3735. } else {
  3736. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  3737. }
  3738. // Note: -fwritable-strings doesn't make the backing store strings of
  3739. // CFStrings writable. (See <rdar://problem/10657500>)
  3740. auto *GV =
  3741. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  3742. llvm::GlobalValue::PrivateLinkage, C, ".str");
  3743. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3744. // Don't enforce the target's minimum global alignment, since the only use
  3745. // of the string is via this class initializer.
  3746. CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
  3747. : Context.getTypeAlignInChars(Context.CharTy);
  3748. GV->setAlignment(Align.getQuantity());
  3749. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
  3750. // Without it LLVM can merge the string with a non unnamed_addr one during
  3751. // LTO. Doing that changes the section it ends in, which surprises ld64.
  3752. if (Triple.isOSBinFormatMachO())
  3753. GV->setSection(isUTF16 ? "__TEXT,__ustring"
  3754. : "__TEXT,__cstring,cstring_literals");
  3755. // Make sure the literal ends up in .rodata to allow for safe ICF and for
  3756. // the static linker to adjust permissions to read-only later on.
  3757. else if (Triple.isOSBinFormatELF())
  3758. GV->setSection(".rodata");
  3759. // String.
  3760. llvm::Constant *Str =
  3761. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  3762. if (isUTF16)
  3763. // Cast the UTF16 string to the correct type.
  3764. Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
  3765. Fields.add(Str);
  3766. // String length.
  3767. llvm::IntegerType *LengthTy =
  3768. llvm::IntegerType::get(getModule().getContext(),
  3769. Context.getTargetInfo().getLongWidth());
  3770. if (IsSwiftABI) {
  3771. if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
  3772. CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
  3773. LengthTy = Int32Ty;
  3774. else
  3775. LengthTy = IntPtrTy;
  3776. }
  3777. Fields.addInt(LengthTy, StringLength);
  3778. CharUnits Alignment = getPointerAlign();
  3779. // The struct.
  3780. GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
  3781. /*isConstant=*/false,
  3782. llvm::GlobalVariable::PrivateLinkage);
  3783. switch (Triple.getObjectFormat()) {
  3784. case llvm::Triple::UnknownObjectFormat:
  3785. llvm_unreachable("unknown file format");
  3786. case llvm::Triple::COFF:
  3787. case llvm::Triple::ELF:
  3788. case llvm::Triple::Wasm:
  3789. GV->setSection("cfstring");
  3790. break;
  3791. case llvm::Triple::MachO:
  3792. GV->setSection("__DATA,__cfstring");
  3793. break;
  3794. }
  3795. Entry.second = GV;
  3796. return ConstantAddress(GV, Alignment);
  3797. }
  3798. bool CodeGenModule::getExpressionLocationsEnabled() const {
  3799. return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
  3800. }
  3801. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  3802. if (ObjCFastEnumerationStateType.isNull()) {
  3803. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  3804. D->startDefinition();
  3805. QualType FieldTypes[] = {
  3806. Context.UnsignedLongTy,
  3807. Context.getPointerType(Context.getObjCIdType()),
  3808. Context.getPointerType(Context.UnsignedLongTy),
  3809. Context.getConstantArrayType(Context.UnsignedLongTy,
  3810. llvm::APInt(32, 5), ArrayType::Normal, 0)
  3811. };
  3812. for (size_t i = 0; i < 4; ++i) {
  3813. FieldDecl *Field = FieldDecl::Create(Context,
  3814. D,
  3815. SourceLocation(),
  3816. SourceLocation(), nullptr,
  3817. FieldTypes[i], /*TInfo=*/nullptr,
  3818. /*BitWidth=*/nullptr,
  3819. /*Mutable=*/false,
  3820. ICIS_NoInit);
  3821. Field->setAccess(AS_public);
  3822. D->addDecl(Field);
  3823. }
  3824. D->completeDefinition();
  3825. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  3826. }
  3827. return ObjCFastEnumerationStateType;
  3828. }
  3829. llvm::Constant *
  3830. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  3831. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  3832. // Don't emit it as the address of the string, emit the string data itself
  3833. // as an inline array.
  3834. if (E->getCharByteWidth() == 1) {
  3835. SmallString<64> Str(E->getString());
  3836. // Resize the string to the right size, which is indicated by its type.
  3837. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  3838. Str.resize(CAT->getSize().getZExtValue());
  3839. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  3840. }
  3841. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  3842. llvm::Type *ElemTy = AType->getElementType();
  3843. unsigned NumElements = AType->getNumElements();
  3844. // Wide strings have either 2-byte or 4-byte elements.
  3845. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  3846. SmallVector<uint16_t, 32> Elements;
  3847. Elements.reserve(NumElements);
  3848. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  3849. Elements.push_back(E->getCodeUnit(i));
  3850. Elements.resize(NumElements);
  3851. return llvm::ConstantDataArray::get(VMContext, Elements);
  3852. }
  3853. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  3854. SmallVector<uint32_t, 32> Elements;
  3855. Elements.reserve(NumElements);
  3856. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  3857. Elements.push_back(E->getCodeUnit(i));
  3858. Elements.resize(NumElements);
  3859. return llvm::ConstantDataArray::get(VMContext, Elements);
  3860. }
  3861. static llvm::GlobalVariable *
  3862. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  3863. CodeGenModule &CGM, StringRef GlobalName,
  3864. CharUnits Alignment) {
  3865. unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
  3866. CGM.getStringLiteralAddressSpace());
  3867. llvm::Module &M = CGM.getModule();
  3868. // Create a global variable for this string
  3869. auto *GV = new llvm::GlobalVariable(
  3870. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  3871. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  3872. GV->setAlignment(Alignment.getQuantity());
  3873. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3874. if (GV->isWeakForLinker()) {
  3875. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  3876. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  3877. }
  3878. CGM.setDSOLocal(GV);
  3879. return GV;
  3880. }
  3881. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  3882. /// constant array for the given string literal.
  3883. ConstantAddress
  3884. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  3885. StringRef Name) {
  3886. CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
  3887. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  3888. llvm::GlobalVariable **Entry = nullptr;
  3889. if (!LangOpts.WritableStrings) {
  3890. Entry = &ConstantStringMap[C];
  3891. if (auto GV = *Entry) {
  3892. if (Alignment.getQuantity() > GV->getAlignment())
  3893. GV->setAlignment(Alignment.getQuantity());
  3894. return ConstantAddress(GV, Alignment);
  3895. }
  3896. }
  3897. SmallString<256> MangledNameBuffer;
  3898. StringRef GlobalVariableName;
  3899. llvm::GlobalValue::LinkageTypes LT;
  3900. // Mangle the string literal if that's how the ABI merges duplicate strings.
  3901. // Don't do it if they are writable, since we don't want writes in one TU to
  3902. // affect strings in another.
  3903. if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
  3904. !LangOpts.WritableStrings) {
  3905. llvm::raw_svector_ostream Out(MangledNameBuffer);
  3906. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  3907. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  3908. GlobalVariableName = MangledNameBuffer;
  3909. } else {
  3910. LT = llvm::GlobalValue::PrivateLinkage;
  3911. GlobalVariableName = Name;
  3912. }
  3913. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  3914. if (Entry)
  3915. *Entry = GV;
  3916. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  3917. QualType());
  3918. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  3919. Alignment);
  3920. }
  3921. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  3922. /// array for the given ObjCEncodeExpr node.
  3923. ConstantAddress
  3924. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  3925. std::string Str;
  3926. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  3927. return GetAddrOfConstantCString(Str);
  3928. }
  3929. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  3930. /// the literal and a terminating '\0' character.
  3931. /// The result has pointer to array type.
  3932. ConstantAddress CodeGenModule::GetAddrOfConstantCString(
  3933. const std::string &Str, const char *GlobalName) {
  3934. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  3935. CharUnits Alignment =
  3936. getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
  3937. llvm::Constant *C =
  3938. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  3939. // Don't share any string literals if strings aren't constant.
  3940. llvm::GlobalVariable **Entry = nullptr;
  3941. if (!LangOpts.WritableStrings) {
  3942. Entry = &ConstantStringMap[C];
  3943. if (auto GV = *Entry) {
  3944. if (Alignment.getQuantity() > GV->getAlignment())
  3945. GV->setAlignment(Alignment.getQuantity());
  3946. return ConstantAddress(GV, Alignment);
  3947. }
  3948. }
  3949. // Get the default prefix if a name wasn't specified.
  3950. if (!GlobalName)
  3951. GlobalName = ".str";
  3952. // Create a global variable for this.
  3953. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  3954. GlobalName, Alignment);
  3955. if (Entry)
  3956. *Entry = GV;
  3957. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  3958. Alignment);
  3959. }
  3960. ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
  3961. const MaterializeTemporaryExpr *E, const Expr *Init) {
  3962. assert((E->getStorageDuration() == SD_Static ||
  3963. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  3964. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  3965. // If we're not materializing a subobject of the temporary, keep the
  3966. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  3967. QualType MaterializedType = Init->getType();
  3968. if (Init == E->GetTemporaryExpr())
  3969. MaterializedType = E->getType();
  3970. CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
  3971. if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
  3972. return ConstantAddress(Slot, Align);
  3973. // FIXME: If an externally-visible declaration extends multiple temporaries,
  3974. // we need to give each temporary the same name in every translation unit (and
  3975. // we also need to make the temporaries externally-visible).
  3976. SmallString<256> Name;
  3977. llvm::raw_svector_ostream Out(Name);
  3978. getCXXABI().getMangleContext().mangleReferenceTemporary(
  3979. VD, E->getManglingNumber(), Out);
  3980. APValue *Value = nullptr;
  3981. if (E->getStorageDuration() == SD_Static) {
  3982. // We might have a cached constant initializer for this temporary. Note
  3983. // that this might have a different value from the value computed by
  3984. // evaluating the initializer if the surrounding constant expression
  3985. // modifies the temporary.
  3986. Value = getContext().getMaterializedTemporaryValue(E, false);
  3987. if (Value && Value->isUninit())
  3988. Value = nullptr;
  3989. }
  3990. // Try evaluating it now, it might have a constant initializer.
  3991. Expr::EvalResult EvalResult;
  3992. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  3993. !EvalResult.hasSideEffects())
  3994. Value = &EvalResult.Val;
  3995. LangAS AddrSpace =
  3996. VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
  3997. Optional<ConstantEmitter> emitter;
  3998. llvm::Constant *InitialValue = nullptr;
  3999. bool Constant = false;
  4000. llvm::Type *Type;
  4001. if (Value) {
  4002. // The temporary has a constant initializer, use it.
  4003. emitter.emplace(*this);
  4004. InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
  4005. MaterializedType);
  4006. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  4007. Type = InitialValue->getType();
  4008. } else {
  4009. // No initializer, the initialization will be provided when we
  4010. // initialize the declaration which performed lifetime extension.
  4011. Type = getTypes().ConvertTypeForMem(MaterializedType);
  4012. }
  4013. // Create a global variable for this lifetime-extended temporary.
  4014. llvm::GlobalValue::LinkageTypes Linkage =
  4015. getLLVMLinkageVarDefinition(VD, Constant);
  4016. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  4017. const VarDecl *InitVD;
  4018. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  4019. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  4020. // Temporaries defined inside a class get linkonce_odr linkage because the
  4021. // class can be defined in multiple translation units.
  4022. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  4023. } else {
  4024. // There is no need for this temporary to have external linkage if the
  4025. // VarDecl has external linkage.
  4026. Linkage = llvm::GlobalVariable::InternalLinkage;
  4027. }
  4028. }
  4029. auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
  4030. auto *GV = new llvm::GlobalVariable(
  4031. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  4032. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
  4033. if (emitter) emitter->finalize(GV);
  4034. setGVProperties(GV, VD);
  4035. GV->setAlignment(Align.getQuantity());
  4036. if (supportsCOMDAT() && GV->isWeakForLinker())
  4037. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  4038. if (VD->getTLSKind())
  4039. setTLSMode(GV, *VD);
  4040. llvm::Constant *CV = GV;
  4041. if (AddrSpace != LangAS::Default)
  4042. CV = getTargetCodeGenInfo().performAddrSpaceCast(
  4043. *this, GV, AddrSpace, LangAS::Default,
  4044. Type->getPointerTo(
  4045. getContext().getTargetAddressSpace(LangAS::Default)));
  4046. MaterializedGlobalTemporaryMap[E] = CV;
  4047. return ConstantAddress(CV, Align);
  4048. }
  4049. /// EmitObjCPropertyImplementations - Emit information for synthesized
  4050. /// properties for an implementation.
  4051. void CodeGenModule::EmitObjCPropertyImplementations(const
  4052. ObjCImplementationDecl *D) {
  4053. for (const auto *PID : D->property_impls()) {
  4054. // Dynamic is just for type-checking.
  4055. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  4056. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  4057. // Determine which methods need to be implemented, some may have
  4058. // been overridden. Note that ::isPropertyAccessor is not the method
  4059. // we want, that just indicates if the decl came from a
  4060. // property. What we want to know is if the method is defined in
  4061. // this implementation.
  4062. if (!D->getInstanceMethod(PD->getGetterName()))
  4063. CodeGenFunction(*this).GenerateObjCGetter(
  4064. const_cast<ObjCImplementationDecl *>(D), PID);
  4065. if (!PD->isReadOnly() &&
  4066. !D->getInstanceMethod(PD->getSetterName()))
  4067. CodeGenFunction(*this).GenerateObjCSetter(
  4068. const_cast<ObjCImplementationDecl *>(D), PID);
  4069. }
  4070. }
  4071. }
  4072. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  4073. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  4074. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  4075. ivar; ivar = ivar->getNextIvar())
  4076. if (ivar->getType().isDestructedType())
  4077. return true;
  4078. return false;
  4079. }
  4080. static bool AllTrivialInitializers(CodeGenModule &CGM,
  4081. ObjCImplementationDecl *D) {
  4082. CodeGenFunction CGF(CGM);
  4083. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  4084. E = D->init_end(); B != E; ++B) {
  4085. CXXCtorInitializer *CtorInitExp = *B;
  4086. Expr *Init = CtorInitExp->getInit();
  4087. if (!CGF.isTrivialInitializer(Init))
  4088. return false;
  4089. }
  4090. return true;
  4091. }
  4092. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  4093. /// for an implementation.
  4094. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  4095. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  4096. if (needsDestructMethod(D)) {
  4097. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  4098. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  4099. ObjCMethodDecl *DTORMethod =
  4100. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  4101. cxxSelector, getContext().VoidTy, nullptr, D,
  4102. /*isInstance=*/true, /*isVariadic=*/false,
  4103. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  4104. /*isDefined=*/false, ObjCMethodDecl::Required);
  4105. D->addInstanceMethod(DTORMethod);
  4106. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  4107. D->setHasDestructors(true);
  4108. }
  4109. // If the implementation doesn't have any ivar initializers, we don't need
  4110. // a .cxx_construct.
  4111. if (D->getNumIvarInitializers() == 0 ||
  4112. AllTrivialInitializers(*this, D))
  4113. return;
  4114. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  4115. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  4116. // The constructor returns 'self'.
  4117. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  4118. D->getLocation(),
  4119. D->getLocation(),
  4120. cxxSelector,
  4121. getContext().getObjCIdType(),
  4122. nullptr, D, /*isInstance=*/true,
  4123. /*isVariadic=*/false,
  4124. /*isPropertyAccessor=*/true,
  4125. /*isImplicitlyDeclared=*/true,
  4126. /*isDefined=*/false,
  4127. ObjCMethodDecl::Required);
  4128. D->addInstanceMethod(CTORMethod);
  4129. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  4130. D->setHasNonZeroConstructors(true);
  4131. }
  4132. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  4133. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  4134. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  4135. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  4136. ErrorUnsupported(LSD, "linkage spec");
  4137. return;
  4138. }
  4139. EmitDeclContext(LSD);
  4140. }
  4141. void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
  4142. for (auto *I : DC->decls()) {
  4143. // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
  4144. // are themselves considered "top-level", so EmitTopLevelDecl on an
  4145. // ObjCImplDecl does not recursively visit them. We need to do that in
  4146. // case they're nested inside another construct (LinkageSpecDecl /
  4147. // ExportDecl) that does stop them from being considered "top-level".
  4148. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  4149. for (auto *M : OID->methods())
  4150. EmitTopLevelDecl(M);
  4151. }
  4152. EmitTopLevelDecl(I);
  4153. }
  4154. }
  4155. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  4156. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  4157. // Ignore dependent declarations.
  4158. if (D->isTemplated())
  4159. return;
  4160. switch (D->getKind()) {
  4161. case Decl::CXXConversion:
  4162. case Decl::CXXMethod:
  4163. case Decl::Function:
  4164. EmitGlobal(cast<FunctionDecl>(D));
  4165. // Always provide some coverage mapping
  4166. // even for the functions that aren't emitted.
  4167. AddDeferredUnusedCoverageMapping(D);
  4168. break;
  4169. case Decl::CXXDeductionGuide:
  4170. // Function-like, but does not result in code emission.
  4171. break;
  4172. case Decl::Var:
  4173. case Decl::Decomposition:
  4174. case Decl::VarTemplateSpecialization:
  4175. EmitGlobal(cast<VarDecl>(D));
  4176. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  4177. for (auto *B : DD->bindings())
  4178. if (auto *HD = B->getHoldingVar())
  4179. EmitGlobal(HD);
  4180. break;
  4181. // Indirect fields from global anonymous structs and unions can be
  4182. // ignored; only the actual variable requires IR gen support.
  4183. case Decl::IndirectField:
  4184. break;
  4185. // C++ Decls
  4186. case Decl::Namespace:
  4187. EmitDeclContext(cast<NamespaceDecl>(D));
  4188. break;
  4189. case Decl::ClassTemplateSpecialization: {
  4190. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  4191. if (DebugInfo &&
  4192. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
  4193. Spec->hasDefinition())
  4194. DebugInfo->completeTemplateDefinition(*Spec);
  4195. } LLVM_FALLTHROUGH;
  4196. case Decl::CXXRecord:
  4197. if (DebugInfo) {
  4198. if (auto *ES = D->getASTContext().getExternalSource())
  4199. if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
  4200. DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
  4201. }
  4202. // Emit any static data members, they may be definitions.
  4203. for (auto *I : cast<CXXRecordDecl>(D)->decls())
  4204. if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
  4205. EmitTopLevelDecl(I);
  4206. break;
  4207. // No code generation needed.
  4208. case Decl::UsingShadow:
  4209. case Decl::ClassTemplate:
  4210. case Decl::VarTemplate:
  4211. case Decl::VarTemplatePartialSpecialization:
  4212. case Decl::FunctionTemplate:
  4213. case Decl::TypeAliasTemplate:
  4214. case Decl::Block:
  4215. case Decl::Empty:
  4216. case Decl::Binding:
  4217. break;
  4218. case Decl::Using: // using X; [C++]
  4219. if (CGDebugInfo *DI = getModuleDebugInfo())
  4220. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  4221. return;
  4222. case Decl::NamespaceAlias:
  4223. if (CGDebugInfo *DI = getModuleDebugInfo())
  4224. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  4225. return;
  4226. case Decl::UsingDirective: // using namespace X; [C++]
  4227. if (CGDebugInfo *DI = getModuleDebugInfo())
  4228. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  4229. return;
  4230. case Decl::CXXConstructor:
  4231. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  4232. break;
  4233. case Decl::CXXDestructor:
  4234. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  4235. break;
  4236. case Decl::StaticAssert:
  4237. // Nothing to do.
  4238. break;
  4239. // Objective-C Decls
  4240. // Forward declarations, no (immediate) code generation.
  4241. case Decl::ObjCInterface:
  4242. case Decl::ObjCCategory:
  4243. break;
  4244. case Decl::ObjCProtocol: {
  4245. auto *Proto = cast<ObjCProtocolDecl>(D);
  4246. if (Proto->isThisDeclarationADefinition())
  4247. ObjCRuntime->GenerateProtocol(Proto);
  4248. break;
  4249. }
  4250. case Decl::ObjCCategoryImpl:
  4251. // Categories have properties but don't support synthesize so we
  4252. // can ignore them here.
  4253. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  4254. break;
  4255. case Decl::ObjCImplementation: {
  4256. auto *OMD = cast<ObjCImplementationDecl>(D);
  4257. EmitObjCPropertyImplementations(OMD);
  4258. EmitObjCIvarInitializations(OMD);
  4259. ObjCRuntime->GenerateClass(OMD);
  4260. // Emit global variable debug information.
  4261. if (CGDebugInfo *DI = getModuleDebugInfo())
  4262. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  4263. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  4264. OMD->getClassInterface()), OMD->getLocation());
  4265. break;
  4266. }
  4267. case Decl::ObjCMethod: {
  4268. auto *OMD = cast<ObjCMethodDecl>(D);
  4269. // If this is not a prototype, emit the body.
  4270. if (OMD->getBody())
  4271. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  4272. break;
  4273. }
  4274. case Decl::ObjCCompatibleAlias:
  4275. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  4276. break;
  4277. case Decl::PragmaComment: {
  4278. const auto *PCD = cast<PragmaCommentDecl>(D);
  4279. switch (PCD->getCommentKind()) {
  4280. case PCK_Unknown:
  4281. llvm_unreachable("unexpected pragma comment kind");
  4282. case PCK_Linker:
  4283. AppendLinkerOptions(PCD->getArg());
  4284. break;
  4285. case PCK_Lib:
  4286. if (getTarget().getTriple().isOSBinFormatELF() &&
  4287. !getTarget().getTriple().isPS4())
  4288. AddELFLibDirective(PCD->getArg());
  4289. else
  4290. AddDependentLib(PCD->getArg());
  4291. break;
  4292. case PCK_Compiler:
  4293. case PCK_ExeStr:
  4294. case PCK_User:
  4295. break; // We ignore all of these.
  4296. }
  4297. break;
  4298. }
  4299. case Decl::PragmaDetectMismatch: {
  4300. const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
  4301. AddDetectMismatch(PDMD->getName(), PDMD->getValue());
  4302. break;
  4303. }
  4304. case Decl::LinkageSpec:
  4305. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  4306. break;
  4307. case Decl::FileScopeAsm: {
  4308. // File-scope asm is ignored during device-side CUDA compilation.
  4309. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  4310. break;
  4311. // File-scope asm is ignored during device-side OpenMP compilation.
  4312. if (LangOpts.OpenMPIsDevice)
  4313. break;
  4314. auto *AD = cast<FileScopeAsmDecl>(D);
  4315. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  4316. break;
  4317. }
  4318. case Decl::Import: {
  4319. auto *Import = cast<ImportDecl>(D);
  4320. // If we've already imported this module, we're done.
  4321. if (!ImportedModules.insert(Import->getImportedModule()))
  4322. break;
  4323. // Emit debug information for direct imports.
  4324. if (!Import->getImportedOwningModule()) {
  4325. if (CGDebugInfo *DI = getModuleDebugInfo())
  4326. DI->EmitImportDecl(*Import);
  4327. }
  4328. // Find all of the submodules and emit the module initializers.
  4329. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  4330. SmallVector<clang::Module *, 16> Stack;
  4331. Visited.insert(Import->getImportedModule());
  4332. Stack.push_back(Import->getImportedModule());
  4333. while (!Stack.empty()) {
  4334. clang::Module *Mod = Stack.pop_back_val();
  4335. if (!EmittedModuleInitializers.insert(Mod).second)
  4336. continue;
  4337. for (auto *D : Context.getModuleInitializers(Mod))
  4338. EmitTopLevelDecl(D);
  4339. // Visit the submodules of this module.
  4340. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  4341. SubEnd = Mod->submodule_end();
  4342. Sub != SubEnd; ++Sub) {
  4343. // Skip explicit children; they need to be explicitly imported to emit
  4344. // the initializers.
  4345. if ((*Sub)->IsExplicit)
  4346. continue;
  4347. if (Visited.insert(*Sub).second)
  4348. Stack.push_back(*Sub);
  4349. }
  4350. }
  4351. break;
  4352. }
  4353. case Decl::Export:
  4354. EmitDeclContext(cast<ExportDecl>(D));
  4355. break;
  4356. case Decl::OMPThreadPrivate:
  4357. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  4358. break;
  4359. case Decl::OMPDeclareReduction:
  4360. EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
  4361. break;
  4362. case Decl::OMPDeclareMapper:
  4363. EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
  4364. break;
  4365. case Decl::OMPRequires:
  4366. EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
  4367. break;
  4368. default:
  4369. // Make sure we handled everything we should, every other kind is a
  4370. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  4371. // function. Need to recode Decl::Kind to do that easily.
  4372. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  4373. break;
  4374. }
  4375. }
  4376. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  4377. // Do we need to generate coverage mapping?
  4378. if (!CodeGenOpts.CoverageMapping)
  4379. return;
  4380. switch (D->getKind()) {
  4381. case Decl::CXXConversion:
  4382. case Decl::CXXMethod:
  4383. case Decl::Function:
  4384. case Decl::ObjCMethod:
  4385. case Decl::CXXConstructor:
  4386. case Decl::CXXDestructor: {
  4387. if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
  4388. return;
  4389. SourceManager &SM = getContext().getSourceManager();
  4390. if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
  4391. return;
  4392. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  4393. if (I == DeferredEmptyCoverageMappingDecls.end())
  4394. DeferredEmptyCoverageMappingDecls[D] = true;
  4395. break;
  4396. }
  4397. default:
  4398. break;
  4399. };
  4400. }
  4401. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  4402. // Do we need to generate coverage mapping?
  4403. if (!CodeGenOpts.CoverageMapping)
  4404. return;
  4405. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  4406. if (Fn->isTemplateInstantiation())
  4407. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  4408. }
  4409. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  4410. if (I == DeferredEmptyCoverageMappingDecls.end())
  4411. DeferredEmptyCoverageMappingDecls[D] = false;
  4412. else
  4413. I->second = false;
  4414. }
  4415. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  4416. // We call takeVector() here to avoid use-after-free.
  4417. // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
  4418. // we deserialize function bodies to emit coverage info for them, and that
  4419. // deserializes more declarations. How should we handle that case?
  4420. for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
  4421. if (!Entry.second)
  4422. continue;
  4423. const Decl *D = Entry.first;
  4424. switch (D->getKind()) {
  4425. case Decl::CXXConversion:
  4426. case Decl::CXXMethod:
  4427. case Decl::Function:
  4428. case Decl::ObjCMethod: {
  4429. CodeGenPGO PGO(*this);
  4430. GlobalDecl GD(cast<FunctionDecl>(D));
  4431. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  4432. getFunctionLinkage(GD));
  4433. break;
  4434. }
  4435. case Decl::CXXConstructor: {
  4436. CodeGenPGO PGO(*this);
  4437. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  4438. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  4439. getFunctionLinkage(GD));
  4440. break;
  4441. }
  4442. case Decl::CXXDestructor: {
  4443. CodeGenPGO PGO(*this);
  4444. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  4445. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  4446. getFunctionLinkage(GD));
  4447. break;
  4448. }
  4449. default:
  4450. break;
  4451. };
  4452. }
  4453. }
  4454. /// Turns the given pointer into a constant.
  4455. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  4456. const void *Ptr) {
  4457. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  4458. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  4459. return llvm::ConstantInt::get(i64, PtrInt);
  4460. }
  4461. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  4462. llvm::NamedMDNode *&GlobalMetadata,
  4463. GlobalDecl D,
  4464. llvm::GlobalValue *Addr) {
  4465. if (!GlobalMetadata)
  4466. GlobalMetadata =
  4467. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  4468. // TODO: should we report variant information for ctors/dtors?
  4469. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  4470. llvm::ConstantAsMetadata::get(GetPointerConstant(
  4471. CGM.getLLVMContext(), D.getDecl()))};
  4472. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  4473. }
  4474. /// For each function which is declared within an extern "C" region and marked
  4475. /// as 'used', but has internal linkage, create an alias from the unmangled
  4476. /// name to the mangled name if possible. People expect to be able to refer
  4477. /// to such functions with an unmangled name from inline assembly within the
  4478. /// same translation unit.
  4479. void CodeGenModule::EmitStaticExternCAliases() {
  4480. if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
  4481. return;
  4482. for (auto &I : StaticExternCValues) {
  4483. IdentifierInfo *Name = I.first;
  4484. llvm::GlobalValue *Val = I.second;
  4485. if (Val && !getModule().getNamedValue(Name->getName()))
  4486. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  4487. }
  4488. }
  4489. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  4490. GlobalDecl &Result) const {
  4491. auto Res = Manglings.find(MangledName);
  4492. if (Res == Manglings.end())
  4493. return false;
  4494. Result = Res->getValue();
  4495. return true;
  4496. }
  4497. /// Emits metadata nodes associating all the global values in the
  4498. /// current module with the Decls they came from. This is useful for
  4499. /// projects using IR gen as a subroutine.
  4500. ///
  4501. /// Since there's currently no way to associate an MDNode directly
  4502. /// with an llvm::GlobalValue, we create a global named metadata
  4503. /// with the name 'clang.global.decl.ptrs'.
  4504. void CodeGenModule::EmitDeclMetadata() {
  4505. llvm::NamedMDNode *GlobalMetadata = nullptr;
  4506. for (auto &I : MangledDeclNames) {
  4507. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  4508. // Some mangled names don't necessarily have an associated GlobalValue
  4509. // in this module, e.g. if we mangled it for DebugInfo.
  4510. if (Addr)
  4511. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  4512. }
  4513. }
  4514. /// Emits metadata nodes for all the local variables in the current
  4515. /// function.
  4516. void CodeGenFunction::EmitDeclMetadata() {
  4517. if (LocalDeclMap.empty()) return;
  4518. llvm::LLVMContext &Context = getLLVMContext();
  4519. // Find the unique metadata ID for this name.
  4520. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  4521. llvm::NamedMDNode *GlobalMetadata = nullptr;
  4522. for (auto &I : LocalDeclMap) {
  4523. const Decl *D = I.first;
  4524. llvm::Value *Addr = I.second.getPointer();
  4525. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  4526. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  4527. Alloca->setMetadata(
  4528. DeclPtrKind, llvm::MDNode::get(
  4529. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  4530. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  4531. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  4532. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  4533. }
  4534. }
  4535. }
  4536. void CodeGenModule::EmitVersionIdentMetadata() {
  4537. llvm::NamedMDNode *IdentMetadata =
  4538. TheModule.getOrInsertNamedMetadata("llvm.ident");
  4539. std::string Version = getClangFullVersion();
  4540. llvm::LLVMContext &Ctx = TheModule.getContext();
  4541. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  4542. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  4543. }
  4544. void CodeGenModule::EmitCommandLineMetadata() {
  4545. llvm::NamedMDNode *CommandLineMetadata =
  4546. TheModule.getOrInsertNamedMetadata("llvm.commandline");
  4547. std::string CommandLine = getCodeGenOpts().RecordCommandLine;
  4548. llvm::LLVMContext &Ctx = TheModule.getContext();
  4549. llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
  4550. CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
  4551. }
  4552. void CodeGenModule::EmitTargetMetadata() {
  4553. // Warning, new MangledDeclNames may be appended within this loop.
  4554. // We rely on MapVector insertions adding new elements to the end
  4555. // of the container.
  4556. // FIXME: Move this loop into the one target that needs it, and only
  4557. // loop over those declarations for which we couldn't emit the target
  4558. // metadata when we emitted the declaration.
  4559. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  4560. auto Val = *(MangledDeclNames.begin() + I);
  4561. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  4562. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  4563. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  4564. }
  4565. }
  4566. void CodeGenModule::EmitCoverageFile() {
  4567. if (getCodeGenOpts().CoverageDataFile.empty() &&
  4568. getCodeGenOpts().CoverageNotesFile.empty())
  4569. return;
  4570. llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
  4571. if (!CUNode)
  4572. return;
  4573. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  4574. llvm::LLVMContext &Ctx = TheModule.getContext();
  4575. auto *CoverageDataFile =
  4576. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
  4577. auto *CoverageNotesFile =
  4578. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
  4579. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  4580. llvm::MDNode *CU = CUNode->getOperand(i);
  4581. llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
  4582. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  4583. }
  4584. }
  4585. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
  4586. // Sema has checked that all uuid strings are of the form
  4587. // "12345678-1234-1234-1234-1234567890ab".
  4588. assert(Uuid.size() == 36);
  4589. for (unsigned i = 0; i < 36; ++i) {
  4590. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  4591. else assert(isHexDigit(Uuid[i]));
  4592. }
  4593. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  4594. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  4595. llvm::Constant *Field3[8];
  4596. for (unsigned Idx = 0; Idx < 8; ++Idx)
  4597. Field3[Idx] = llvm::ConstantInt::get(
  4598. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  4599. llvm::Constant *Fields[4] = {
  4600. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  4601. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  4602. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  4603. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  4604. };
  4605. return llvm::ConstantStruct::getAnon(Fields);
  4606. }
  4607. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  4608. bool ForEH) {
  4609. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  4610. // FIXME: should we even be calling this method if RTTI is disabled
  4611. // and it's not for EH?
  4612. if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
  4613. return llvm::Constant::getNullValue(Int8PtrTy);
  4614. if (ForEH && Ty->isObjCObjectPointerType() &&
  4615. LangOpts.ObjCRuntime.isGNUFamily())
  4616. return ObjCRuntime->GetEHType(Ty);
  4617. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  4618. }
  4619. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  4620. // Do not emit threadprivates in simd-only mode.
  4621. if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
  4622. return;
  4623. for (auto RefExpr : D->varlists()) {
  4624. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  4625. bool PerformInit =
  4626. VD->getAnyInitializer() &&
  4627. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  4628. /*ForRef=*/false);
  4629. Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
  4630. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  4631. VD, Addr, RefExpr->getBeginLoc(), PerformInit))
  4632. CXXGlobalInits.push_back(InitFunction);
  4633. }
  4634. }
  4635. llvm::Metadata *
  4636. CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
  4637. StringRef Suffix) {
  4638. llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
  4639. if (InternalId)
  4640. return InternalId;
  4641. if (isExternallyVisible(T->getLinkage())) {
  4642. std::string OutName;
  4643. llvm::raw_string_ostream Out(OutName);
  4644. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  4645. Out << Suffix;
  4646. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  4647. } else {
  4648. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  4649. llvm::ArrayRef<llvm::Metadata *>());
  4650. }
  4651. return InternalId;
  4652. }
  4653. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
  4654. return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
  4655. }
  4656. llvm::Metadata *
  4657. CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
  4658. return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
  4659. }
  4660. // Generalize pointer types to a void pointer with the qualifiers of the
  4661. // originally pointed-to type, e.g. 'const char *' and 'char * const *'
  4662. // generalize to 'const void *' while 'char *' and 'const char **' generalize to
  4663. // 'void *'.
  4664. static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
  4665. if (!Ty->isPointerType())
  4666. return Ty;
  4667. return Ctx.getPointerType(
  4668. QualType(Ctx.VoidTy).withCVRQualifiers(
  4669. Ty->getPointeeType().getCVRQualifiers()));
  4670. }
  4671. // Apply type generalization to a FunctionType's return and argument types
  4672. static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
  4673. if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
  4674. SmallVector<QualType, 8> GeneralizedParams;
  4675. for (auto &Param : FnType->param_types())
  4676. GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
  4677. return Ctx.getFunctionType(
  4678. GeneralizeType(Ctx, FnType->getReturnType()),
  4679. GeneralizedParams, FnType->getExtProtoInfo());
  4680. }
  4681. if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
  4682. return Ctx.getFunctionNoProtoType(
  4683. GeneralizeType(Ctx, FnType->getReturnType()));
  4684. llvm_unreachable("Encountered unknown FunctionType");
  4685. }
  4686. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
  4687. return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
  4688. GeneralizedMetadataIdMap, ".generalized");
  4689. }
  4690. /// Returns whether this module needs the "all-vtables" type identifier.
  4691. bool CodeGenModule::NeedAllVtablesTypeId() const {
  4692. // Returns true if at least one of vtable-based CFI checkers is enabled and
  4693. // is not in the trapping mode.
  4694. return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
  4695. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
  4696. (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
  4697. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
  4698. (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
  4699. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
  4700. (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
  4701. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
  4702. }
  4703. void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
  4704. CharUnits Offset,
  4705. const CXXRecordDecl *RD) {
  4706. llvm::Metadata *MD =
  4707. CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  4708. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  4709. if (CodeGenOpts.SanitizeCfiCrossDso)
  4710. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  4711. VTable->addTypeMetadata(Offset.getQuantity(),
  4712. llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  4713. if (NeedAllVtablesTypeId()) {
  4714. llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
  4715. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  4716. }
  4717. }
  4718. TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
  4719. assert(TD != nullptr);
  4720. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  4721. ParsedAttr.Features.erase(
  4722. llvm::remove_if(ParsedAttr.Features,
  4723. [&](const std::string &Feat) {
  4724. return !Target.isValidFeatureName(
  4725. StringRef{Feat}.substr(1));
  4726. }),
  4727. ParsedAttr.Features.end());
  4728. return ParsedAttr;
  4729. }
  4730. // Fills in the supplied string map with the set of target features for the
  4731. // passed in function.
  4732. void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  4733. GlobalDecl GD) {
  4734. StringRef TargetCPU = Target.getTargetOpts().CPU;
  4735. const FunctionDecl *FD = GD.getDecl()->getAsFunction();
  4736. if (const auto *TD = FD->getAttr<TargetAttr>()) {
  4737. TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
  4738. // Make a copy of the features as passed on the command line into the
  4739. // beginning of the additional features from the function to override.
  4740. ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
  4741. Target.getTargetOpts().FeaturesAsWritten.begin(),
  4742. Target.getTargetOpts().FeaturesAsWritten.end());
  4743. if (ParsedAttr.Architecture != "" &&
  4744. Target.isValidCPUName(ParsedAttr.Architecture))
  4745. TargetCPU = ParsedAttr.Architecture;
  4746. // Now populate the feature map, first with the TargetCPU which is either
  4747. // the default or a new one from the target attribute string. Then we'll use
  4748. // the passed in features (FeaturesAsWritten) along with the new ones from
  4749. // the attribute.
  4750. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  4751. ParsedAttr.Features);
  4752. } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
  4753. llvm::SmallVector<StringRef, 32> FeaturesTmp;
  4754. Target.getCPUSpecificCPUDispatchFeatures(
  4755. SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
  4756. std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
  4757. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
  4758. } else {
  4759. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  4760. Target.getTargetOpts().Features);
  4761. }
  4762. }
  4763. llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
  4764. if (!SanStats)
  4765. SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
  4766. return *SanStats;
  4767. }
  4768. llvm::Value *
  4769. CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
  4770. CodeGenFunction &CGF) {
  4771. llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
  4772. auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
  4773. auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
  4774. return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
  4775. "__translate_sampler_initializer"),
  4776. {C});
  4777. }