CodeGenModule.cpp 191 KB

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