CodeGenFunction.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826
  1. //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
  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-function state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CGCleanup.h"
  15. #include "CGCUDARuntime.h"
  16. #include "CGHLSLRuntime.h" // HLSL Change
  17. #include "CGCXXABI.h"
  18. #include "CGDebugInfo.h"
  19. #include "CGOpenMPRuntime.h"
  20. #include "CodeGenModule.h"
  21. #include "CodeGenPGO.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/Decl.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/Basic/TargetInfo.h"
  28. #include "clang/CodeGen/CGFunctionInfo.h"
  29. #include "clang/Frontend/CodeGenOptions.h"
  30. #include "llvm/IR/DataLayout.h"
  31. #include "llvm/IR/Intrinsics.h"
  32. #include "llvm/IR/MDBuilder.h"
  33. #include "llvm/IR/Operator.h"
  34. #include "dxc/DXIL/DxilMetadataHelper.h" // HLSL Change
  35. using namespace clang;
  36. using namespace CodeGen;
  37. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  38. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  39. Builder(cgm.getModule().getContext(), llvm::ConstantFolder(),
  40. CGBuilderInserterTy(this)),
  41. CurFn(nullptr), CapturedStmtInfo(nullptr),
  42. SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false),
  43. CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false),
  44. IsOutlinedSEHHelper(false), BlockInfo(nullptr), BlockPointer(nullptr),
  45. LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
  46. NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
  47. ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
  48. DebugInfo(CGM.getModuleDebugInfo()),
  49. DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
  50. PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
  51. CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
  52. NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
  53. CXXABIThisValue(nullptr), CXXThisValue(nullptr),
  54. CXXDefaultInitExprThis(nullptr), CXXStructorImplicitParamDecl(nullptr),
  55. CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
  56. CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
  57. TerminateHandler(nullptr), TrapBB(nullptr) {
  58. if (!suppressNewContext)
  59. CGM.getCXXABI().getMangleContext().startNewFunction();
  60. llvm::FastMathFlags FMF;
  61. if (CGM.getLangOpts().FastMath)
  62. FMF.setUnsafeAlgebra();
  63. if (CGM.getLangOpts().FiniteMathOnly) {
  64. FMF.setNoNaNs();
  65. FMF.setNoInfs();
  66. }
  67. if (CGM.getCodeGenOpts().NoNaNsFPMath) {
  68. FMF.setNoNaNs();
  69. }
  70. if (CGM.getCodeGenOpts().NoSignedZeros) {
  71. FMF.setNoSignedZeros();
  72. }
  73. if (CGM.getCodeGenOpts().ReciprocalMath) {
  74. FMF.setAllowReciprocal();
  75. }
  76. Builder.SetFastMathFlags(FMF);
  77. }
  78. CodeGenFunction::~CodeGenFunction() {
  79. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  80. // If there are any unclaimed block infos, go ahead and destroy them
  81. // now. This can happen if IR-gen gets clever and skips evaluating
  82. // something.
  83. if (FirstBlockInfo)
  84. destroyBlockInfos(FirstBlockInfo);
  85. #if 0 // HLSL Change - no OpenMP support
  86. if (getLangOpts().OpenMP) {
  87. CGM.getOpenMPRuntime().functionFinished(*this);
  88. }
  89. #endif // HLSL Change - no OpenMP support
  90. }
  91. LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  92. CharUnits Alignment;
  93. if (CGM.getCXXABI().isTypeInfoCalculable(T)) {
  94. Alignment = getContext().getTypeAlignInChars(T);
  95. unsigned MaxAlign = getContext().getLangOpts().MaxTypeAlign;
  96. if (MaxAlign && Alignment.getQuantity() > MaxAlign &&
  97. !getContext().isAlignmentRequired(T))
  98. Alignment = CharUnits::fromQuantity(MaxAlign);
  99. }
  100. return LValue::MakeAddr(V, T, Alignment, getContext(), CGM.getTBAAInfo(T));
  101. }
  102. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  103. return CGM.getTypes().ConvertTypeForMem(T);
  104. }
  105. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  106. return CGM.getTypes().ConvertType(T);
  107. }
  108. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  109. type = type.getCanonicalType();
  110. while (true) {
  111. switch (type->getTypeClass()) {
  112. #define TYPE(name, parent)
  113. #define ABSTRACT_TYPE(name, parent)
  114. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  115. #define DEPENDENT_TYPE(name, parent) case Type::name:
  116. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  117. #include "clang/AST/TypeNodes.def"
  118. llvm_unreachable("non-canonical or dependent type in IR-generation");
  119. case Type::Auto:
  120. llvm_unreachable("undeduced auto type in IR-generation");
  121. // Various scalar types.
  122. case Type::Builtin:
  123. case Type::Pointer:
  124. case Type::BlockPointer:
  125. case Type::LValueReference:
  126. case Type::RValueReference:
  127. case Type::MemberPointer:
  128. case Type::Vector:
  129. case Type::ExtVector:
  130. case Type::FunctionProto:
  131. case Type::FunctionNoProto:
  132. case Type::Enum:
  133. case Type::ObjCObjectPointer:
  134. return TEK_Scalar;
  135. // Complexes.
  136. case Type::Complex:
  137. return TEK_Complex;
  138. // Arrays, records, and Objective-C objects.
  139. case Type::ConstantArray:
  140. case Type::IncompleteArray:
  141. case Type::VariableArray:
  142. case Type::Record:
  143. case Type::ObjCObject:
  144. case Type::ObjCInterface:
  145. // HLSL Change Starts
  146. if (hlsl::IsHLSLVecType(type)) {
  147. // Treat hlsl vector as ext vector.
  148. return TEK_Scalar;
  149. }
  150. if (hlsl::IsHLSLMatType(type)) {
  151. // Treat hlsl matrix as scalar type too.
  152. return TEK_Scalar;
  153. }
  154. // HLSL Change Ends
  155. return TEK_Aggregate;
  156. // We operate on atomic values according to their underlying type.
  157. case Type::Atomic:
  158. type = cast<AtomicType>(type)->getValueType();
  159. continue;
  160. }
  161. llvm_unreachable("unknown type kind!");
  162. }
  163. }
  164. llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
  165. // For cleanliness, we try to avoid emitting the return block for
  166. // simple cases.
  167. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  168. if (CurBB) {
  169. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  170. // We have a valid insert point, reuse it if it is empty or there are no
  171. // explicit jumps to the return block.
  172. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  173. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  174. delete ReturnBlock.getBlock();
  175. } else
  176. EmitBlock(ReturnBlock.getBlock());
  177. return llvm::DebugLoc();
  178. }
  179. // Otherwise, if the return block is the target of a single direct
  180. // branch then we can just put the code in that block instead. This
  181. // cleans up functions which started with a unified return block.
  182. if (ReturnBlock.getBlock()->hasOneUse()) {
  183. llvm::BranchInst *BI =
  184. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
  185. if (BI && BI->isUnconditional() &&
  186. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  187. // Record/return the DebugLoc of the simple 'return' expression to be used
  188. // later by the actual 'ret' instruction.
  189. llvm::DebugLoc Loc = BI->getDebugLoc();
  190. Builder.SetInsertPoint(BI->getParent());
  191. BI->eraseFromParent();
  192. delete ReturnBlock.getBlock();
  193. return Loc;
  194. }
  195. }
  196. // FIXME: We are at an unreachable point, there is no reason to emit the block
  197. // unless it has uses. However, we still need a place to put the debug
  198. // region.end for now.
  199. EmitBlock(ReturnBlock.getBlock());
  200. return llvm::DebugLoc();
  201. }
  202. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  203. if (!BB) return;
  204. if (!BB->use_empty())
  205. return CGF.CurFn->getBasicBlockList().push_back(BB);
  206. delete BB;
  207. }
  208. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  209. assert(BreakContinueStack.empty() &&
  210. "mismatched push/pop in break/continue stack!");
  211. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  212. && NumSimpleReturnExprs == NumReturnExprs
  213. && ReturnBlock.getBlock()->use_empty();
  214. // Usually the return expression is evaluated before the cleanup
  215. // code. If the function contains only a simple return statement,
  216. // such as a constant, the location before the cleanup code becomes
  217. // the last useful breakpoint in the function, because the simple
  218. // return expression will be evaluated after the cleanup code. To be
  219. // safe, set the debug location for cleanup code to the location of
  220. // the return statement. Otherwise the cleanup code should be at the
  221. // end of the function's lexical scope.
  222. //
  223. // If there are multiple branches to the return block, the branch
  224. // instructions will get the location of the return statements and
  225. // all will be fine.
  226. if (CGDebugInfo *DI = getDebugInfo()) {
  227. if (OnlySimpleReturnStmts)
  228. DI->EmitLocation(Builder, LastStopPoint);
  229. else
  230. DI->EmitLocation(Builder, EndLoc);
  231. }
  232. // Pop any cleanups that might have been associated with the
  233. // parameters. Do this in whatever block we're currently in; it's
  234. // important to do this before we enter the return block or return
  235. // edges will be *really* confused.
  236. bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
  237. bool HasOnlyLifetimeMarkers =
  238. HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
  239. bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
  240. if (HasCleanups) {
  241. // Make sure the line table doesn't jump back into the body for
  242. // the ret after it's been at EndLoc.
  243. if (CGDebugInfo *DI = getDebugInfo())
  244. if (OnlySimpleReturnStmts)
  245. DI->EmitLocation(Builder, EndLoc);
  246. PopCleanupBlocks(PrologueCleanupDepth);
  247. }
  248. // Emit function epilog (to return).
  249. llvm::DebugLoc Loc = EmitReturnBlock();
  250. if (ShouldInstrumentFunction())
  251. EmitFunctionInstrumentation("__cyg_profile_func_exit");
  252. // Emit debug descriptor for function end.
  253. if (CGDebugInfo *DI = getDebugInfo())
  254. DI->EmitFunctionEnd(Builder);
  255. // Reset the debug location to that of the simple 'return' expression, if any
  256. // rather than that of the end of the function's scope '}'.
  257. ApplyDebugLocation AL(*this, Loc);
  258. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
  259. EmitEndEHSpec(CurCodeDecl);
  260. assert(EHStack.empty() &&
  261. "did not remove all scopes from cleanup stack!");
  262. // If someone did an indirect goto, emit the indirect goto block at the end of
  263. // the function.
  264. if (IndirectBranch) {
  265. EmitBlock(IndirectBranch->getParent());
  266. Builder.ClearInsertionPoint();
  267. }
  268. // If some of our locals escaped, insert a call to llvm.localescape in the
  269. // entry block.
  270. if (!EscapedLocals.empty()) {
  271. // Invert the map from local to index into a simple vector. There should be
  272. // no holes.
  273. SmallVector<llvm::Value *, 4> EscapeArgs;
  274. EscapeArgs.resize(EscapedLocals.size());
  275. for (auto &Pair : EscapedLocals)
  276. EscapeArgs[Pair.second] = Pair.first;
  277. llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
  278. &CGM.getModule(), llvm::Intrinsic::localescape);
  279. CGBuilderTy(AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
  280. }
  281. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  282. llvm::Instruction *Ptr = AllocaInsertPt;
  283. AllocaInsertPt = nullptr;
  284. Ptr->eraseFromParent();
  285. // If someone took the address of a label but never did an indirect goto, we
  286. // made a zero entry PHI node, which is illegal, zap it now.
  287. if (IndirectBranch) {
  288. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  289. if (PN->getNumIncomingValues() == 0) {
  290. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  291. PN->eraseFromParent();
  292. }
  293. }
  294. EmitIfUsed(*this, EHResumeBlock);
  295. EmitIfUsed(*this, TerminateLandingPad);
  296. EmitIfUsed(*this, TerminateHandler);
  297. EmitIfUsed(*this, UnreachableBlock);
  298. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  299. EmitDeclMetadata();
  300. for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
  301. I = DeferredReplacements.begin(),
  302. E = DeferredReplacements.end();
  303. I != E; ++I) {
  304. I->first->replaceAllUsesWith(I->second);
  305. I->first->eraseFromParent();
  306. }
  307. }
  308. /// ShouldInstrumentFunction - Return true if the current function should be
  309. /// instrumented with __cyg_profile_func_* calls
  310. bool CodeGenFunction::ShouldInstrumentFunction() {
  311. if (!CGM.getCodeGenOpts().InstrumentFunctions)
  312. return false;
  313. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  314. return false;
  315. return true;
  316. }
  317. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  318. /// instrumentation function with the current function and the call site, if
  319. /// function instrumentation is enabled.
  320. void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
  321. // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
  322. llvm::PointerType *PointerTy = Int8PtrTy;
  323. llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
  324. llvm::FunctionType *FunctionTy =
  325. llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
  326. llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
  327. llvm::CallInst *CallSite = Builder.CreateCall(
  328. CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
  329. llvm::ConstantInt::get(Int32Ty, 0),
  330. "callsite");
  331. llvm::Value *args[] = {
  332. llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
  333. CallSite
  334. };
  335. EmitNounwindRuntimeCall(F, args);
  336. }
  337. void CodeGenFunction::EmitMCountInstrumentation() {
  338. llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
  339. llvm::Constant *MCountFn =
  340. CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
  341. EmitNounwindRuntimeCall(MCountFn);
  342. }
  343. // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
  344. // information in the program executable. The argument information stored
  345. // includes the argument name, its type, the address and access qualifiers used.
  346. static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
  347. CodeGenModule &CGM, llvm::LLVMContext &Context,
  348. SmallVector<llvm::Metadata *, 5> &kernelMDArgs,
  349. CGBuilderTy &Builder, ASTContext &ASTCtx) {
  350. // Create MDNodes that represent the kernel arg metadata.
  351. // Each MDNode is a list in the form of "key", N number of values which is
  352. // the same number of values as their are kernel arguments.
  353. const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
  354. // MDNode for the kernel argument address space qualifiers.
  355. SmallVector<llvm::Metadata *, 8> addressQuals;
  356. addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
  357. // MDNode for the kernel argument access qualifiers (images only).
  358. SmallVector<llvm::Metadata *, 8> accessQuals;
  359. accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
  360. // MDNode for the kernel argument type names.
  361. SmallVector<llvm::Metadata *, 8> argTypeNames;
  362. argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
  363. // MDNode for the kernel argument base type names.
  364. SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
  365. argBaseTypeNames.push_back(
  366. llvm::MDString::get(Context, "kernel_arg_base_type"));
  367. // MDNode for the kernel argument type qualifiers.
  368. SmallVector<llvm::Metadata *, 8> argTypeQuals;
  369. argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
  370. // MDNode for the kernel argument names.
  371. SmallVector<llvm::Metadata *, 8> argNames;
  372. argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
  373. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
  374. const ParmVarDecl *parm = FD->getParamDecl(i);
  375. QualType ty = parm->getType();
  376. std::string typeQuals;
  377. if (ty->isPointerType()) {
  378. QualType pointeeTy = ty->getPointeeType();
  379. // Get address qualifier.
  380. addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
  381. ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace()))));
  382. // Get argument type name.
  383. std::string typeName =
  384. pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
  385. // Turn "unsigned type" to "utype"
  386. std::string::size_type pos = typeName.find("unsigned");
  387. if (pointeeTy.isCanonical() && pos != std::string::npos)
  388. typeName.erase(pos+1, 8);
  389. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  390. std::string baseTypeName =
  391. pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
  392. Policy) +
  393. "*";
  394. // Turn "unsigned type" to "utype"
  395. pos = baseTypeName.find("unsigned");
  396. if (pos != std::string::npos)
  397. baseTypeName.erase(pos+1, 8);
  398. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  399. // Get argument type qualifiers:
  400. if (ty.isRestrictQualified())
  401. typeQuals = "restrict";
  402. if (pointeeTy.isConstQualified() ||
  403. (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
  404. typeQuals += typeQuals.empty() ? "const" : " const";
  405. if (pointeeTy.isVolatileQualified())
  406. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  407. } else {
  408. uint32_t AddrSpc = 0;
  409. if (ty->isImageType())
  410. AddrSpc =
  411. CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
  412. addressQuals.push_back(
  413. llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
  414. // Get argument type name.
  415. std::string typeName = ty.getUnqualifiedType().getAsString(Policy);
  416. // Turn "unsigned type" to "utype"
  417. std::string::size_type pos = typeName.find("unsigned");
  418. if (ty.isCanonical() && pos != std::string::npos)
  419. typeName.erase(pos+1, 8);
  420. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  421. std::string baseTypeName =
  422. ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
  423. // Turn "unsigned type" to "utype"
  424. pos = baseTypeName.find("unsigned");
  425. if (pos != std::string::npos)
  426. baseTypeName.erase(pos+1, 8);
  427. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  428. // Get argument type qualifiers:
  429. if (ty.isConstQualified())
  430. typeQuals = "const";
  431. if (ty.isVolatileQualified())
  432. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  433. }
  434. argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
  435. // Get image access qualifier:
  436. if (ty->isImageType()) {
  437. const OpenCLImageAccessAttr *A = parm->getAttr<OpenCLImageAccessAttr>();
  438. if (A && A->isWriteOnly())
  439. accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
  440. else
  441. accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
  442. // FIXME: what about read_write?
  443. } else
  444. accessQuals.push_back(llvm::MDString::get(Context, "none"));
  445. // Get argument name.
  446. argNames.push_back(llvm::MDString::get(Context, parm->getName()));
  447. }
  448. kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
  449. kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
  450. kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
  451. kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames));
  452. kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
  453. if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
  454. kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
  455. }
  456. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  457. llvm::Function *Fn)
  458. {
  459. if (!FD->hasAttr<OpenCLKernelAttr>())
  460. return;
  461. llvm::LLVMContext &Context = getLLVMContext();
  462. SmallVector<llvm::Metadata *, 5> kernelMDArgs;
  463. kernelMDArgs.push_back(llvm::ConstantAsMetadata::get(Fn));
  464. GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs, Builder,
  465. getContext());
  466. if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
  467. QualType hintQTy = A->getTypeHint();
  468. const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
  469. bool isSignedInteger =
  470. hintQTy->isSignedIntegerType() ||
  471. (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
  472. llvm::Metadata *attrMDArgs[] = {
  473. llvm::MDString::get(Context, "vec_type_hint"),
  474. llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
  475. CGM.getTypes().ConvertType(A->getTypeHint()))),
  476. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  477. llvm::IntegerType::get(Context, 32),
  478. llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
  479. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  480. }
  481. if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
  482. llvm::Metadata *attrMDArgs[] = {
  483. llvm::MDString::get(Context, "work_group_size_hint"),
  484. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  485. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  486. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  487. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  488. }
  489. if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
  490. llvm::Metadata *attrMDArgs[] = {
  491. llvm::MDString::get(Context, "reqd_work_group_size"),
  492. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  493. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  494. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  495. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  496. }
  497. llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
  498. llvm::NamedMDNode *OpenCLKernelMetadata =
  499. CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
  500. OpenCLKernelMetadata->addOperand(kernelMDNode);
  501. }
  502. /// Determine whether the function F ends with a return stmt.
  503. static bool endsWithReturn(const Decl* F) {
  504. const Stmt *Body = nullptr;
  505. if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
  506. Body = FD->getBody();
  507. else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
  508. Body = OMD->getBody();
  509. if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  510. auto LastStmt = CS->body_rbegin();
  511. if (LastStmt != CS->body_rend())
  512. return isa<ReturnStmt>(*LastStmt);
  513. }
  514. return false;
  515. }
  516. void CodeGenFunction::StartFunction(GlobalDecl GD,
  517. QualType RetTy,
  518. llvm::Function *Fn,
  519. const CGFunctionInfo &FnInfo,
  520. const FunctionArgList &Args,
  521. SourceLocation Loc,
  522. SourceLocation StartLoc) {
  523. assert(!CurFn &&
  524. "Do not use a CodeGenFunction object for more than one function");
  525. const Decl *D = GD.getDecl();
  526. DidCallStackSave = false;
  527. CurCodeDecl = D;
  528. CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
  529. FnRetTy = RetTy;
  530. CurFn = Fn;
  531. CurFnInfo = &FnInfo;
  532. assert(CurFn->isDeclaration() && "Function already has body?");
  533. if (CGM.isInSanitizerBlacklist(Fn, Loc))
  534. SanOpts.clear();
  535. if (D) {
  536. // Apply the no_sanitize* attributes to SanOpts.
  537. for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
  538. SanOpts.Mask &= ~Attr->getMask();
  539. }
  540. // Apply sanitizer attributes to the function.
  541. if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
  542. Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
  543. if (SanOpts.has(SanitizerKind::Thread))
  544. Fn->addFnAttr(llvm::Attribute::SanitizeThread);
  545. if (SanOpts.has(SanitizerKind::Memory))
  546. Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
  547. if (SanOpts.has(SanitizerKind::SafeStack))
  548. Fn->addFnAttr(llvm::Attribute::SafeStack);
  549. // Pass inline keyword to optimizer if it appears explicitly on any
  550. // declaration. Also, in the case of -fno-inline attach NoInline
  551. // attribute to all function that are not marked AlwaysInline.
  552. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  553. if (!CGM.getCodeGenOpts().NoInline) {
  554. for (auto RI : FD->redecls())
  555. if (RI->isInlineSpecified()) {
  556. Fn->addFnAttr(llvm::Attribute::InlineHint);
  557. break;
  558. }
  559. } else if (!FD->hasAttr<AlwaysInlineAttr>())
  560. Fn->addFnAttr(llvm::Attribute::NoInline);
  561. }
  562. if (getLangOpts().OpenCL) {
  563. // Add metadata for a kernel function.
  564. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  565. EmitOpenCLKernelMetadata(FD, Fn);
  566. }
  567. // If we are checking function types, emit a function type signature as
  568. // prologue data.
  569. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
  570. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  571. if (llvm::Constant *PrologueSig =
  572. CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
  573. llvm::Constant *FTRTTIConst =
  574. CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
  575. llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
  576. llvm::Constant *PrologueStructConst =
  577. llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
  578. Fn->setPrologueData(PrologueStructConst);
  579. }
  580. }
  581. }
  582. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  583. // Create a marker to make it easy to insert allocas into the entryblock
  584. // later. Don't create this with the builder, because we don't want it
  585. // folded.
  586. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  587. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
  588. if (Builder.isNamePreserving())
  589. AllocaInsertPt->setName("allocapt");
  590. ReturnBlock = getJumpDestInCurrentScope("return");
  591. Builder.SetInsertPoint(EntryBB);
  592. // Emit subprogram debug descriptor.
  593. if (CGDebugInfo *DI = getDebugInfo()) {
  594. SmallVector<QualType, 16> ArgTypes;
  595. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  596. i != e; ++i) {
  597. ArgTypes.push_back((*i)->getType());
  598. }
  599. QualType FnType = getContext().getFunctionType(
  600. RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(), None); // HLSL Change - add param mods - TODO: review for inout
  601. DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
  602. }
  603. if (ShouldInstrumentFunction())
  604. EmitFunctionInstrumentation("__cyg_profile_func_enter");
  605. if (CGM.getCodeGenOpts().InstrumentForProfiling)
  606. EmitMCountInstrumentation();
  607. if (RetTy->isVoidType()) {
  608. // Void type; nothing to return.
  609. ReturnValue = nullptr;
  610. // Count the implicit return.
  611. if (!endsWithReturn(D))
  612. ++NumReturnExprs;
  613. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  614. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  615. // Indirect aggregate return; emit returned value directly into sret slot.
  616. // This reduces code size, and affects correctness in C++.
  617. auto AI = CurFn->arg_begin();
  618. if (CurFnInfo->getReturnInfo().isSRetAfterThis())
  619. ++AI;
  620. ReturnValue = AI;
  621. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  622. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  623. // Load the sret pointer from the argument struct and return into that.
  624. unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
  625. llvm::Function::arg_iterator EI = CurFn->arg_end();
  626. --EI;
  627. llvm::Value *Addr = Builder.CreateStructGEP(nullptr, EI, Idx);
  628. ReturnValue = Builder.CreateLoad(Addr, "agg.result");
  629. } else {
  630. ReturnValue = CreateIRTemp(RetTy, "retval");
  631. // HLSL Change begin
  632. cast<llvm::Instruction>(ReturnValue)
  633. ->setMetadata(hlsl::DxilMDHelper::kDxilTempAllocaMDName, llvm::MDTuple::get(ReturnValue->getContext(), {}));
  634. // HLSL Change end
  635. // Tell the epilog emitter to autorelease the result. We do this
  636. // now so that various specialized functions can suppress it
  637. // during their IR-generation.
  638. if (getLangOpts().ObjCAutoRefCount &&
  639. !CurFnInfo->isReturnsRetained() &&
  640. RetTy->isObjCRetainableType())
  641. AutoreleaseResult = true;
  642. }
  643. EmitStartEHSpec(CurCodeDecl);
  644. PrologueCleanupDepth = EHStack.stable_begin();
  645. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  646. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  647. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  648. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  649. if (MD->getParent()->isLambda() &&
  650. MD->getOverloadedOperator() == OO_Call) {
  651. // We're in a lambda; figure out the captures.
  652. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  653. LambdaThisCaptureField);
  654. if (LambdaThisCaptureField) {
  655. // If this lambda captures this, load it.
  656. LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  657. CXXThisValue = EmitLoadOfLValue(ThisLValue,
  658. SourceLocation()).getScalarVal();
  659. }
  660. for (auto *FD : MD->getParent()->fields()) {
  661. if (FD->hasCapturedVLAType()) {
  662. auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
  663. SourceLocation()).getScalarVal();
  664. auto VAT = FD->getCapturedVLAType();
  665. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  666. }
  667. }
  668. } else {
  669. // Not in a lambda; just use 'this' from the method.
  670. // FIXME: Should we generate a new load for each use of 'this'? The
  671. // fast register allocator would be happier...
  672. CXXThisValue = CXXABIThisValue;
  673. }
  674. }
  675. // If any of the arguments have a variably modified type, make sure to
  676. // emit the type size.
  677. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  678. i != e; ++i) {
  679. const VarDecl *VD = *i;
  680. // Dig out the type as written from ParmVarDecls; it's unclear whether
  681. // the standard (C99 6.9.1p10) requires this, but we're following the
  682. // precedent set by gcc.
  683. QualType Ty;
  684. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  685. Ty = PVD->getOriginalType();
  686. else
  687. Ty = VD->getType();
  688. if (Ty->isVariablyModifiedType())
  689. EmitVariablyModifiedType(Ty);
  690. }
  691. // Emit a location at the end of the prologue.
  692. if (CGDebugInfo *DI = getDebugInfo())
  693. DI->EmitLocation(Builder, StartLoc);
  694. }
  695. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
  696. const Stmt *Body) {
  697. incrementProfileCounter(Body);
  698. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  699. EmitCompoundStmtWithoutScope(*S);
  700. else
  701. EmitStmt(Body);
  702. }
  703. /// When instrumenting to collect profile data, the counts for some blocks
  704. /// such as switch cases need to not include the fall-through counts, so
  705. /// emit a branch around the instrumentation code. When not instrumenting,
  706. /// this just calls EmitBlock().
  707. void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
  708. const Stmt *S) {
  709. llvm::BasicBlock *SkipCountBB = nullptr;
  710. if (HaveInsertPoint() && CGM.getCodeGenOpts().ProfileInstrGenerate) {
  711. // When instrumenting for profiling, the fallthrough to certain
  712. // statements needs to skip over the instrumentation code so that we
  713. // get an accurate count.
  714. SkipCountBB = createBasicBlock("skipcount");
  715. EmitBranch(SkipCountBB);
  716. }
  717. EmitBlock(BB);
  718. uint64_t CurrentCount = getCurrentProfileCount();
  719. incrementProfileCounter(S);
  720. setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
  721. if (SkipCountBB)
  722. EmitBlock(SkipCountBB);
  723. }
  724. /// Tries to mark the given function nounwind based on the
  725. /// non-existence of any throwing calls within it. We believe this is
  726. /// lightweight enough to do at -O0.
  727. static void TryMarkNoThrow(llvm::Function *F) {
  728. // LLVM treats 'nounwind' on a function as part of the type, so we
  729. // can't do this on functions that can be overwritten.
  730. if (F->mayBeOverridden()) return;
  731. for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
  732. for (llvm::BasicBlock::iterator
  733. BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
  734. if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
  735. if (!Call->doesNotThrow())
  736. return;
  737. } else if (isa<llvm::ResumeInst>(&*BI)) {
  738. return;
  739. }
  740. F->setDoesNotThrow();
  741. }
  742. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  743. const CGFunctionInfo &FnInfo) {
  744. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  745. // Check if we should generate debug info for this function.
  746. if (FD->hasAttr<NoDebugAttr>())
  747. DebugInfo = nullptr; // disable debug info indefinitely for this function
  748. FunctionArgList Args;
  749. QualType ResTy = FD->getReturnType();
  750. // HLSL Change Start - emit root signature associated with function
  751. if (HLSLRootSignatureAttr *RSA = FD->getAttr<HLSLRootSignatureAttr>()) {
  752. CGM.getHLSLRuntime().EmitHLSLRootSignature(*this, RSA, Fn);
  753. }
  754. // HLSL Change Ends - emit root signature associated with function
  755. CurGD = GD;
  756. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  757. if (MD && MD->isInstance()) {
  758. if (CGM.getCXXABI().HasThisReturn(GD))
  759. ResTy = MD->getThisType(getContext());
  760. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  761. ResTy = CGM.getContext().VoidPtrTy;
  762. CGM.getCXXABI().buildThisParam(*this, Args);
  763. }
  764. Args.append(FD->param_begin(), FD->param_end());
  765. if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
  766. CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
  767. SourceRange BodyRange;
  768. if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
  769. CurEHLocation = BodyRange.getEnd();
  770. // Use the location of the start of the function to determine where
  771. // the function definition is located. By default use the location
  772. // of the declaration as the location for the subprogram. A function
  773. // may lack a declaration in the source code if it is created by code
  774. // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
  775. SourceLocation Loc = FD->getLocation();
  776. // If this is a function specialization then use the pattern body
  777. // as the location for the function.
  778. if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
  779. if (SpecDecl->hasBody(SpecDecl))
  780. Loc = SpecDecl->getLocation();
  781. // Emit the standard function prologue.
  782. StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
  783. // Generate the body of the function.
  784. PGO.checkGlobalDecl(GD);
  785. PGO.assignRegionCounters(GD.getDecl(), CurFn);
  786. if (isa<CXXDestructorDecl>(FD))
  787. EmitDestructorBody(Args);
  788. else if (isa<CXXConstructorDecl>(FD))
  789. EmitConstructorBody(Args);
  790. else if (getLangOpts().CUDA &&
  791. !getLangOpts().CUDAIsDevice &&
  792. FD->hasAttr<CUDAGlobalAttr>())
  793. CGM.getCUDARuntime().emitDeviceStub(*this, Args);
  794. else if (isa<CXXConversionDecl>(FD) &&
  795. cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
  796. // The lambda conversion to block pointer is special; the semantics can't be
  797. // expressed in the AST, so IRGen needs to special-case it.
  798. EmitLambdaToBlockPointerBody(Args);
  799. } else if (isa<CXXMethodDecl>(FD) &&
  800. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  801. // The lambda static invoker function is special, because it forwards or
  802. // clones the body of the function call operator (but is actually static).
  803. EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
  804. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  805. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  806. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  807. // Implicit copy-assignment gets the same special treatment as implicit
  808. // copy-constructors.
  809. emitImplicitAssignmentOperatorBody(Args);
  810. } else if (Stmt *Body = FD->getBody()) {
  811. EmitFunctionBody(Args, Body);
  812. } else
  813. llvm_unreachable("no definition for emitted function");
  814. // C++11 [stmt.return]p2:
  815. // Flowing off the end of a function [...] results in undefined behavior in
  816. // a value-returning function.
  817. // C11 6.9.1p12:
  818. // If the '}' that terminates a function is reached, and the value of the
  819. // function call is used by the caller, the behavior is undefined.
  820. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
  821. !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
  822. if (SanOpts.has(SanitizerKind::Return)) {
  823. SanitizerScope SanScope(this);
  824. llvm::Value *IsFalse = Builder.getFalse();
  825. EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
  826. "missing_return", EmitCheckSourceLocation(FD->getLocation()),
  827. None);
  828. } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  829. EmitTrapCall(llvm::Intrinsic::trap);
  830. }
  831. Builder.CreateUnreachable();
  832. Builder.ClearInsertionPoint();
  833. }
  834. // Emit the standard function epilogue.
  835. FinishFunction(BodyRange.getEnd());
  836. // If we haven't marked the function nothrow through other means, do
  837. // a quick pass now to see if we can.
  838. if (!CurFn->doesNotThrow())
  839. TryMarkNoThrow(CurFn);
  840. }
  841. /// ContainsLabel - Return true if the statement contains a label in it. If
  842. /// this statement is not executed normally, it not containing a label means
  843. /// that we can just remove the code.
  844. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  845. // Null statement, not a label!
  846. if (!S) return false;
  847. // If this is a label, we have to emit the code, consider something like:
  848. // if (0) { ... foo: bar(); } goto foo;
  849. //
  850. // TODO: If anyone cared, we could track __label__'s, since we know that you
  851. // can't jump to one from outside their declared region.
  852. if (isa<LabelStmt>(S))
  853. return true;
  854. // If this is a case/default statement, and we haven't seen a switch, we have
  855. // to emit the code.
  856. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  857. return true;
  858. // If this is a switch statement, we want to ignore cases below it.
  859. if (isa<SwitchStmt>(S))
  860. IgnoreCaseStmts = true;
  861. // Scan subexpressions for verboten labels.
  862. for (const Stmt *SubStmt : S->children())
  863. if (ContainsLabel(SubStmt, IgnoreCaseStmts))
  864. return true;
  865. return false;
  866. }
  867. /// containsBreak - Return true if the statement contains a break out of it.
  868. /// If the statement (recursively) contains a switch or loop with a break
  869. /// inside of it, this is fine.
  870. bool CodeGenFunction::containsBreak(const Stmt *S) {
  871. // Null statement, not a label!
  872. if (!S) return false;
  873. // If this is a switch or loop that defines its own break scope, then we can
  874. // include it and anything inside of it.
  875. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  876. isa<ForStmt>(S))
  877. return false;
  878. if (isa<BreakStmt>(S))
  879. return true;
  880. // Scan subexpressions for verboten breaks.
  881. for (const Stmt *SubStmt : S->children())
  882. if (containsBreak(SubStmt))
  883. return true;
  884. return false;
  885. }
  886. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  887. /// to a constant, or if it does but contains a label, return false. If it
  888. /// constant folds return true and set the boolean result in Result.
  889. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  890. bool &ResultBool) {
  891. llvm::APSInt ResultInt;
  892. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
  893. return false;
  894. ResultBool = ResultInt.getBoolValue();
  895. return true;
  896. }
  897. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  898. /// to a constant, or if it does but contains a label, return false. If it
  899. /// constant folds return true and set the folded value.
  900. bool CodeGenFunction::
  901. ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
  902. // FIXME: Rename and handle conversion of other evaluatable things
  903. // to bool.
  904. llvm::APSInt Int;
  905. if (!Cond->EvaluateAsInt(Int, getContext()))
  906. return false; // Not foldable, not integer or not fully evaluatable.
  907. if (CodeGenFunction::ContainsLabel(Cond))
  908. return false; // Contains a label.
  909. ResultInt = Int;
  910. return true;
  911. }
  912. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  913. /// statement) to the specified blocks. Based on the condition, this might try
  914. /// to simplify the codegen of the conditional based on the branch.
  915. ///
  916. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  917. llvm::BasicBlock *TrueBlock,
  918. llvm::BasicBlock *FalseBlock,
  919. uint64_t TrueCount) {
  920. Cond = Cond->IgnoreParens();
  921. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  922. // Handle X && Y in a condition.
  923. if (CondBOp->getOpcode() == BO_LAnd) {
  924. // If we have "1 && X", simplify the code. "0 && X" would have constant
  925. // folded if the case was simple enough.
  926. bool ConstantBool = false;
  927. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  928. ConstantBool) {
  929. // br(1 && X) -> br(X).
  930. incrementProfileCounter(CondBOp);
  931. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  932. TrueCount);
  933. }
  934. // If we have "X && 1", simplify the code to use an uncond branch.
  935. // "X && 0" would have been constant folded to 0.
  936. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  937. ConstantBool) {
  938. // br(X && 1) -> br(X).
  939. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  940. TrueCount);
  941. }
  942. // HLSL Change Begins.
  943. if (getLangOpts().HLSL) {
  944. // HLSL don't short circuit.
  945. // Emit the code with the fully general case.
  946. llvm::Value *CondV;
  947. {
  948. ApplyDebugLocation DL(*this, Cond);
  949. CondV = EvaluateExprAsBool(Cond);
  950. }
  951. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
  952. return;
  953. }
  954. // HLSL Change Ends.
  955. // Emit the LHS as a conditional. If the LHS conditional is false, we
  956. // want to jump to the FalseBlock.
  957. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  958. // The counter tells us how often we evaluate RHS, and all of TrueCount
  959. // can be propagated to that branch.
  960. uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
  961. ConditionalEvaluation eval(*this);
  962. {
  963. ApplyDebugLocation DL(*this, Cond);
  964. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
  965. EmitBlock(LHSTrue);
  966. }
  967. incrementProfileCounter(CondBOp);
  968. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  969. // Any temporaries created here are conditional.
  970. eval.begin(*this);
  971. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
  972. eval.end(*this);
  973. return;
  974. }
  975. if (CondBOp->getOpcode() == BO_LOr) {
  976. // If we have "0 || X", simplify the code. "1 || X" would have constant
  977. // folded if the case was simple enough.
  978. bool ConstantBool = false;
  979. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  980. !ConstantBool) {
  981. // br(0 || X) -> br(X).
  982. incrementProfileCounter(CondBOp);
  983. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  984. TrueCount);
  985. }
  986. // If we have "X || 0", simplify the code to use an uncond branch.
  987. // "X || 1" would have been constant folded to 1.
  988. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  989. !ConstantBool) {
  990. // br(X || 0) -> br(X).
  991. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  992. TrueCount);
  993. }
  994. // HLSL Change Begins.
  995. if (getLangOpts().HLSL) {
  996. // HLSL don't short circuit.
  997. // Emit the code with the fully general case.
  998. llvm::Value *CondV;
  999. {
  1000. ApplyDebugLocation DL(*this, Cond);
  1001. CondV = EvaluateExprAsBool(Cond);
  1002. }
  1003. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
  1004. return;
  1005. }
  1006. // HLSL Change Ends.
  1007. // Emit the LHS as a conditional. If the LHS conditional is true, we
  1008. // want to jump to the TrueBlock.
  1009. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  1010. // We have the count for entry to the RHS and for the whole expression
  1011. // being true, so we can divy up True count between the short circuit and
  1012. // the RHS.
  1013. uint64_t LHSCount =
  1014. getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
  1015. uint64_t RHSCount = TrueCount - LHSCount;
  1016. ConditionalEvaluation eval(*this);
  1017. {
  1018. ApplyDebugLocation DL(*this, Cond);
  1019. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
  1020. EmitBlock(LHSFalse);
  1021. }
  1022. incrementProfileCounter(CondBOp);
  1023. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1024. // Any temporaries created here are conditional.
  1025. eval.begin(*this);
  1026. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
  1027. eval.end(*this);
  1028. return;
  1029. }
  1030. }
  1031. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  1032. // br(!x, t, f) -> br(x, f, t)
  1033. if (CondUOp->getOpcode() == UO_LNot) {
  1034. // Negate the count.
  1035. uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
  1036. // Negate the condition and swap the destination blocks.
  1037. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
  1038. FalseCount);
  1039. }
  1040. }
  1041. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  1042. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  1043. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  1044. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  1045. ConditionalEvaluation cond(*this);
  1046. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
  1047. getProfileCount(CondOp));
  1048. // When computing PGO branch weights, we only know the overall count for
  1049. // the true block. This code is essentially doing tail duplication of the
  1050. // naive code-gen, introducing new edges for which counts are not
  1051. // available. Divide the counts proportionally between the LHS and RHS of
  1052. // the conditional operator.
  1053. uint64_t LHSScaledTrueCount = 0;
  1054. if (TrueCount) {
  1055. double LHSRatio =
  1056. getProfileCount(CondOp) / (double)getCurrentProfileCount();
  1057. LHSScaledTrueCount = TrueCount * LHSRatio;
  1058. }
  1059. cond.begin(*this);
  1060. EmitBlock(LHSBlock);
  1061. incrementProfileCounter(CondOp);
  1062. {
  1063. ApplyDebugLocation DL(*this, Cond);
  1064. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
  1065. LHSScaledTrueCount);
  1066. }
  1067. cond.end(*this);
  1068. cond.begin(*this);
  1069. EmitBlock(RHSBlock);
  1070. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
  1071. TrueCount - LHSScaledTrueCount);
  1072. cond.end(*this);
  1073. return;
  1074. }
  1075. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  1076. // Conditional operator handling can give us a throw expression as a
  1077. // condition for a case like:
  1078. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  1079. // Fold this to:
  1080. // br(c, throw x, br(y, t, f))
  1081. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  1082. return;
  1083. }
  1084. // Create branch weights based on the number of times we get here and the
  1085. // number of times the condition should be true.
  1086. uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
  1087. llvm::MDNode *Weights =
  1088. createProfileWeights(TrueCount, CurrentCount - TrueCount);
  1089. // Emit the code with the fully general case.
  1090. llvm::Value *CondV;
  1091. {
  1092. ApplyDebugLocation DL(*this, Cond);
  1093. CondV = EvaluateExprAsBool(Cond);
  1094. }
  1095. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights);
  1096. }
  1097. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1098. /// specified stmt yet.
  1099. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  1100. CGM.ErrorUnsupported(S, Type);
  1101. }
  1102. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  1103. /// variable-length array whose elements have a non-zero bit-pattern.
  1104. ///
  1105. /// \param baseType the inner-most element type of the array
  1106. /// \param src - a char* pointing to the bit-pattern for a single
  1107. /// base element of the array
  1108. /// \param sizeInChars - the total size of the VLA, in chars
  1109. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  1110. llvm::Value *dest, llvm::Value *src,
  1111. llvm::Value *sizeInChars) {
  1112. std::pair<CharUnits,CharUnits> baseSizeAndAlign
  1113. = CGF.getContext().getTypeInfoInChars(baseType);
  1114. CGBuilderTy &Builder = CGF.Builder;
  1115. llvm::Value *baseSizeInChars
  1116. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
  1117. llvm::Type *i8p = Builder.getInt8PtrTy();
  1118. llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
  1119. llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
  1120. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  1121. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  1122. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  1123. // Make a loop over the VLA. C99 guarantees that the VLA element
  1124. // count must be nonzero.
  1125. CGF.EmitBlock(loopBB);
  1126. llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
  1127. cur->addIncoming(begin, originBB);
  1128. // memcpy the individual element bit-pattern.
  1129. Builder.CreateMemCpy(cur, src, baseSizeInChars,
  1130. baseSizeAndAlign.second.getQuantity(),
  1131. /*volatile*/ false);
  1132. // Go to the next element.
  1133. llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(),
  1134. cur, 1, "vla.next");
  1135. // Leave if that's the end of the VLA.
  1136. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  1137. Builder.CreateCondBr(done, contBB, loopBB);
  1138. cur->addIncoming(next, loopBB);
  1139. CGF.EmitBlock(contBB);
  1140. }
  1141. void
  1142. CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
  1143. // Ignore empty classes in C++.
  1144. if (getLangOpts().CPlusPlus) {
  1145. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1146. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  1147. return;
  1148. }
  1149. }
  1150. // Cast the dest ptr to the appropriate i8 pointer type.
  1151. unsigned DestAS =
  1152. cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
  1153. llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
  1154. if (DestPtr->getType() != BP)
  1155. DestPtr = Builder.CreateBitCast(DestPtr, BP);
  1156. // Get size and alignment info for this aggregate.
  1157. std::pair<CharUnits, CharUnits> TypeInfo =
  1158. getContext().getTypeInfoInChars(Ty);
  1159. CharUnits Size = TypeInfo.first;
  1160. CharUnits Align = TypeInfo.second;
  1161. llvm::Value *SizeVal;
  1162. const VariableArrayType *vla;
  1163. // Don't bother emitting a zero-byte memset.
  1164. if (Size.isZero()) {
  1165. // But note that getTypeInfo returns 0 for a VLA.
  1166. if (const VariableArrayType *vlaType =
  1167. dyn_cast_or_null<VariableArrayType>(
  1168. getContext().getAsArrayType(Ty))) {
  1169. QualType eltType;
  1170. llvm::Value *numElts;
  1171. std::tie(numElts, eltType) = getVLASize(vlaType);
  1172. SizeVal = numElts;
  1173. CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
  1174. if (!eltSize.isOne())
  1175. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  1176. vla = vlaType;
  1177. } else {
  1178. return;
  1179. }
  1180. } else {
  1181. SizeVal = CGM.getSize(Size);
  1182. vla = nullptr;
  1183. }
  1184. // If the type contains a pointer to data member we can't memset it to zero.
  1185. // Instead, create a null constant and copy it to the destination.
  1186. // TODO: there are other patterns besides zero that we can usefully memset,
  1187. // like -1, which happens to be the pattern used by member-pointers.
  1188. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  1189. // For a VLA, emit a single element, then splat that over the VLA.
  1190. if (vla) Ty = getContext().getBaseElementType(vla);
  1191. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  1192. llvm::GlobalVariable *NullVariable =
  1193. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  1194. /*isConstant=*/true,
  1195. llvm::GlobalVariable::PrivateLinkage,
  1196. NullConstant, Twine());
  1197. llvm::Value *SrcPtr =
  1198. Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
  1199. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  1200. // Get and call the appropriate llvm.memcpy overload.
  1201. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
  1202. return;
  1203. }
  1204. // Otherwise, just memset the whole thing to zero. This is legal
  1205. // because in LLVM, all default initializers (other than the ones we just
  1206. // handled above) are guaranteed to have a bit pattern of all zeros.
  1207. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
  1208. Align.getQuantity(), false);
  1209. }
  1210. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  1211. // Make sure that there is a block for the indirect goto.
  1212. if (!IndirectBranch)
  1213. GetIndirectGotoBlock();
  1214. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  1215. // Make sure the indirect branch includes all of the address-taken blocks.
  1216. IndirectBranch->addDestination(BB);
  1217. return llvm::BlockAddress::get(CurFn, BB);
  1218. }
  1219. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  1220. // If we already made the indirect branch for indirect goto, return its block.
  1221. if (IndirectBranch) return IndirectBranch->getParent();
  1222. CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
  1223. // Create the PHI node that indirect gotos will add entries to.
  1224. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  1225. "indirect.goto.dest");
  1226. // Create the indirect branch instruction.
  1227. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  1228. return IndirectBranch->getParent();
  1229. }
  1230. /// Computes the length of an array in elements, as well as the base
  1231. /// element type and a properly-typed first element pointer.
  1232. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  1233. QualType &baseType,
  1234. llvm::Value *&addr) {
  1235. const ArrayType *arrayType = origArrayType;
  1236. // If it's a VLA, we have to load the stored size. Note that
  1237. // this is the size of the VLA in bytes, not its size in elements.
  1238. llvm::Value *numVLAElements = nullptr;
  1239. if (isa<VariableArrayType>(arrayType)) {
  1240. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
  1241. // Walk into all VLAs. This doesn't require changes to addr,
  1242. // which has type T* where T is the first non-VLA element type.
  1243. do {
  1244. QualType elementType = arrayType->getElementType();
  1245. arrayType = getContext().getAsArrayType(elementType);
  1246. // If we only have VLA components, 'addr' requires no adjustment.
  1247. if (!arrayType) {
  1248. baseType = elementType;
  1249. return numVLAElements;
  1250. }
  1251. } while (isa<VariableArrayType>(arrayType));
  1252. // We get out here only if we find a constant array type
  1253. // inside the VLA.
  1254. }
  1255. // We have some number of constant-length arrays, so addr should
  1256. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  1257. // down to the first element of addr.
  1258. SmallVector<llvm::Value*, 8> gepIndices;
  1259. // GEP down to the array type.
  1260. llvm::ConstantInt *zero = Builder.getInt32(0);
  1261. gepIndices.push_back(zero);
  1262. uint64_t countFromCLAs = 1;
  1263. QualType eltType;
  1264. llvm::ArrayType *llvmArrayType =
  1265. dyn_cast<llvm::ArrayType>(
  1266. cast<llvm::PointerType>(addr->getType())->getElementType());
  1267. while (llvmArrayType) {
  1268. assert(isa<ConstantArrayType>(arrayType));
  1269. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1270. == llvmArrayType->getNumElements());
  1271. gepIndices.push_back(zero);
  1272. countFromCLAs *= llvmArrayType->getNumElements();
  1273. eltType = arrayType->getElementType();
  1274. llvmArrayType =
  1275. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1276. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1277. assert((!llvmArrayType || arrayType) &&
  1278. "LLVM and Clang types are out-of-synch");
  1279. }
  1280. if (arrayType) {
  1281. // From this point onwards, the Clang array type has been emitted
  1282. // as some other type (probably a packed struct). Compute the array
  1283. // size, and just emit the 'begin' expression as a bitcast.
  1284. while (arrayType) {
  1285. countFromCLAs *=
  1286. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1287. eltType = arrayType->getElementType();
  1288. arrayType = getContext().getAsArrayType(eltType);
  1289. }
  1290. unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
  1291. llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
  1292. addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
  1293. } else {
  1294. // Create the actual GEP.
  1295. addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
  1296. }
  1297. baseType = eltType;
  1298. llvm::Value *numElements
  1299. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1300. // If we had any VLA dimensions, factor them in.
  1301. if (numVLAElements)
  1302. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1303. return numElements;
  1304. }
  1305. std::pair<llvm::Value*, QualType>
  1306. CodeGenFunction::getVLASize(QualType type) {
  1307. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1308. assert(vla && "type was not a variable array type!");
  1309. return getVLASize(vla);
  1310. }
  1311. std::pair<llvm::Value*, QualType>
  1312. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1313. // The number of elements so far; always size_t.
  1314. llvm::Value *numElements = nullptr;
  1315. QualType elementType;
  1316. do {
  1317. elementType = type->getElementType();
  1318. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1319. assert(vlaSize && "no size for VLA!");
  1320. assert(vlaSize->getType() == SizeTy);
  1321. if (!numElements) {
  1322. numElements = vlaSize;
  1323. } else {
  1324. // It's undefined behavior if this wraps around, so mark it that way.
  1325. // FIXME: Teach -fsanitize=undefined to trap this.
  1326. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1327. }
  1328. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1329. return std::pair<llvm::Value*,QualType>(numElements, elementType);
  1330. }
  1331. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1332. assert(type->isVariablyModifiedType() &&
  1333. "Must pass variably modified type to EmitVLASizes!");
  1334. EnsureInsertPoint();
  1335. // We're going to walk down into the type and look for VLA
  1336. // expressions.
  1337. do {
  1338. assert(type->isVariablyModifiedType());
  1339. const Type *ty = type.getTypePtr();
  1340. switch (ty->getTypeClass()) {
  1341. #define TYPE(Class, Base)
  1342. #define ABSTRACT_TYPE(Class, Base)
  1343. #define NON_CANONICAL_TYPE(Class, Base)
  1344. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1345. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1346. #include "clang/AST/TypeNodes.def"
  1347. llvm_unreachable("unexpected dependent type!");
  1348. // These types are never variably-modified.
  1349. case Type::Builtin:
  1350. case Type::Complex:
  1351. case Type::Vector:
  1352. case Type::ExtVector:
  1353. case Type::Record:
  1354. case Type::Enum:
  1355. case Type::Elaborated:
  1356. case Type::TemplateSpecialization:
  1357. case Type::ObjCObject:
  1358. case Type::ObjCInterface:
  1359. case Type::ObjCObjectPointer:
  1360. llvm_unreachable("type class is never variably-modified!");
  1361. case Type::Adjusted:
  1362. type = cast<AdjustedType>(ty)->getAdjustedType();
  1363. break;
  1364. case Type::Decayed:
  1365. type = cast<DecayedType>(ty)->getPointeeType();
  1366. break;
  1367. case Type::Pointer:
  1368. type = cast<PointerType>(ty)->getPointeeType();
  1369. break;
  1370. case Type::BlockPointer:
  1371. type = cast<BlockPointerType>(ty)->getPointeeType();
  1372. break;
  1373. case Type::LValueReference:
  1374. case Type::RValueReference:
  1375. type = cast<ReferenceType>(ty)->getPointeeType();
  1376. break;
  1377. case Type::MemberPointer:
  1378. type = cast<MemberPointerType>(ty)->getPointeeType();
  1379. break;
  1380. case Type::ConstantArray:
  1381. case Type::IncompleteArray:
  1382. // Losing element qualification here is fine.
  1383. type = cast<ArrayType>(ty)->getElementType();
  1384. break;
  1385. case Type::VariableArray: {
  1386. // Losing element qualification here is fine.
  1387. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1388. // Unknown size indication requires no size computation.
  1389. // Otherwise, evaluate and record it.
  1390. if (const Expr *size = vat->getSizeExpr()) {
  1391. // It's possible that we might have emitted this already,
  1392. // e.g. with a typedef and a pointer to it.
  1393. llvm::Value *&entry = VLASizeMap[size];
  1394. if (!entry) {
  1395. llvm::Value *Size = EmitScalarExpr(size);
  1396. // C11 6.7.6.2p5:
  1397. // If the size is an expression that is not an integer constant
  1398. // expression [...] each time it is evaluated it shall have a value
  1399. // greater than zero.
  1400. if (SanOpts.has(SanitizerKind::VLABound) &&
  1401. size->getType()->isSignedIntegerType()) {
  1402. SanitizerScope SanScope(this);
  1403. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1404. llvm::Constant *StaticArgs[] = {
  1405. EmitCheckSourceLocation(size->getLocStart()),
  1406. EmitCheckTypeDescriptor(size->getType())
  1407. };
  1408. EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
  1409. SanitizerKind::VLABound),
  1410. "vla_bound_not_positive", StaticArgs, Size);
  1411. }
  1412. // Always zexting here would be wrong if it weren't
  1413. // undefined behavior to have a negative bound.
  1414. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1415. }
  1416. }
  1417. type = vat->getElementType();
  1418. break;
  1419. }
  1420. case Type::FunctionProto:
  1421. case Type::FunctionNoProto:
  1422. type = cast<FunctionType>(ty)->getReturnType();
  1423. break;
  1424. case Type::Paren:
  1425. case Type::TypeOf:
  1426. case Type::UnaryTransform:
  1427. case Type::Attributed:
  1428. case Type::SubstTemplateTypeParm:
  1429. case Type::PackExpansion:
  1430. // Keep walking after single level desugaring.
  1431. type = type.getSingleStepDesugaredType(getContext());
  1432. break;
  1433. case Type::Typedef:
  1434. case Type::Decltype:
  1435. case Type::Auto:
  1436. // Stop walking: nothing to do.
  1437. return;
  1438. case Type::TypeOfExpr:
  1439. // Stop walking: emit typeof expression.
  1440. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1441. return;
  1442. case Type::Atomic:
  1443. type = cast<AtomicType>(ty)->getValueType();
  1444. break;
  1445. }
  1446. } while (type->isVariablyModifiedType());
  1447. }
  1448. llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
  1449. if (getContext().getBuiltinVaListType()->isArrayType())
  1450. return EmitScalarExpr(E);
  1451. return EmitLValue(E).getAddress();
  1452. }
  1453. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1454. llvm::Constant *Init) {
  1455. assert (Init && "Invalid DeclRefExpr initializer!");
  1456. if (CGDebugInfo *Dbg = getDebugInfo())
  1457. if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  1458. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1459. }
  1460. CodeGenFunction::PeepholeProtection
  1461. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1462. // At the moment, the only aggressive peephole we do in IR gen
  1463. // is trunc(zext) folding, but if we add more, we can easily
  1464. // extend this protection.
  1465. if (!rvalue.isScalar()) return PeepholeProtection();
  1466. llvm::Value *value = rvalue.getScalarVal();
  1467. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1468. // Just make an extra bitcast.
  1469. assert(HaveInsertPoint());
  1470. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1471. Builder.GetInsertBlock());
  1472. PeepholeProtection protection;
  1473. protection.Inst = inst;
  1474. return protection;
  1475. }
  1476. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1477. if (!protection.Inst) return;
  1478. // In theory, we could try to duplicate the peepholes now, but whatever.
  1479. protection.Inst->eraseFromParent();
  1480. }
  1481. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
  1482. llvm::Value *AnnotatedVal,
  1483. StringRef AnnotationStr,
  1484. SourceLocation Location) {
  1485. llvm::Value *Args[4] = {
  1486. AnnotatedVal,
  1487. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1488. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1489. CGM.EmitAnnotationLineNo(Location)
  1490. };
  1491. return Builder.CreateCall(AnnotationFn, Args);
  1492. }
  1493. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1494. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1495. // FIXME We create a new bitcast for every annotation because that's what
  1496. // llvm-gcc was doing.
  1497. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1498. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1499. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1500. I->getAnnotation(), D->getLocation());
  1501. }
  1502. llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1503. llvm::Value *V) {
  1504. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1505. llvm::Type *VTy = V->getType();
  1506. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1507. CGM.Int8PtrTy);
  1508. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  1509. // FIXME Always emit the cast inst so we can differentiate between
  1510. // annotation on the first field of a struct and annotation on the struct
  1511. // itself.
  1512. if (VTy != CGM.Int8PtrTy)
  1513. V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
  1514. V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
  1515. V = Builder.CreateBitCast(V, VTy);
  1516. }
  1517. return V;
  1518. }
  1519. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
  1520. CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
  1521. : CGF(CGF) {
  1522. assert(!CGF->IsSanitizerScope);
  1523. CGF->IsSanitizerScope = true;
  1524. }
  1525. CodeGenFunction::SanitizerScope::~SanitizerScope() {
  1526. CGF->IsSanitizerScope = false;
  1527. }
  1528. void CodeGenFunction::InsertHelper(llvm::Instruction *I,
  1529. const llvm::Twine &Name,
  1530. llvm::BasicBlock *BB,
  1531. llvm::BasicBlock::iterator InsertPt) const {
  1532. LoopStack.InsertHelper(I);
  1533. if (IsSanitizerScope)
  1534. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
  1535. }
  1536. template <bool PreserveNames>
  1537. void CGBuilderInserter<PreserveNames>::InsertHelper(
  1538. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1539. llvm::BasicBlock::iterator InsertPt) const {
  1540. llvm::IRBuilderDefaultInserter<PreserveNames>::InsertHelper(I, Name, BB,
  1541. InsertPt);
  1542. if (CGF)
  1543. CGF->InsertHelper(I, Name, BB, InsertPt);
  1544. }
  1545. #ifdef NDEBUG
  1546. #define PreserveNames false
  1547. #else
  1548. #define PreserveNames true
  1549. #endif
  1550. template void CGBuilderInserter<PreserveNames>::InsertHelper(
  1551. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1552. llvm::BasicBlock::iterator InsertPt) const;
  1553. #undef PreserveNames