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