1 //===-- BoxedProcedure.cpp ------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "flang/Optimizer/CodeGen/CodeGen.h" 10 11 #include "flang/Optimizer/Builder/FIRBuilder.h" 12 #include "flang/Optimizer/Builder/LowLevelIntrinsics.h" 13 #include "flang/Optimizer/Dialect/FIRDialect.h" 14 #include "flang/Optimizer/Dialect/FIROps.h" 15 #include "flang/Optimizer/Dialect/FIRType.h" 16 #include "flang/Optimizer/Dialect/Support/FIRContext.h" 17 #include "flang/Optimizer/Support/FatalError.h" 18 #include "flang/Optimizer/Support/InternalNames.h" 19 #include "mlir/IR/PatternMatch.h" 20 #include "mlir/Pass/Pass.h" 21 #include "mlir/Transforms/DialectConversion.h" 22 #include "llvm/ADT/DenseMap.h" 23 24 namespace fir { 25 #define GEN_PASS_DEF_BOXEDPROCEDUREPASS 26 #include "flang/Optimizer/CodeGen/CGPasses.h.inc" 27 } // namespace fir 28 29 #define DEBUG_TYPE "flang-procedure-pointer" 30 31 using namespace fir; 32 33 namespace { 34 /// Options to the procedure pointer pass. 35 struct BoxedProcedureOptions { 36 // Lower the boxproc abstraction to function pointers and thunks where 37 // required. 38 bool useThunks = true; 39 }; 40 41 /// This type converter rewrites all `!fir.boxproc<Func>` types to `Func` types. 42 class BoxprocTypeRewriter : public mlir::TypeConverter { 43 public: 44 using mlir::TypeConverter::convertType; 45 46 /// Does the type \p ty need to be converted? 47 /// Any type that is a `!fir.boxproc` in whole or in part will need to be 48 /// converted to a function type to lower the IR to function pointer form in 49 /// the default implementation performed in this pass. Other implementations 50 /// are possible, so those may convert `!fir.boxproc` to some other type or 51 /// not at all depending on the implementation target's characteristics and 52 /// preference. 53 bool needsConversion(mlir::Type ty) { 54 if (mlir::isa<BoxProcType>(ty)) 55 return true; 56 if (auto funcTy = mlir::dyn_cast<mlir::FunctionType>(ty)) { 57 for (auto t : funcTy.getInputs()) 58 if (needsConversion(t)) 59 return true; 60 for (auto t : funcTy.getResults()) 61 if (needsConversion(t)) 62 return true; 63 return false; 64 } 65 if (auto tupleTy = mlir::dyn_cast<mlir::TupleType>(ty)) { 66 for (auto t : tupleTy.getTypes()) 67 if (needsConversion(t)) 68 return true; 69 return false; 70 } 71 if (auto recTy = mlir::dyn_cast<RecordType>(ty)) { 72 auto visited = visitedTypes.find(ty); 73 if (visited != visitedTypes.end()) 74 return visited->second; 75 [[maybe_unused]] auto newIt = visitedTypes.try_emplace(ty, false); 76 assert(newIt.second && "expected ty to not be in the map"); 77 bool wasAlreadyVisitingRecordType = needConversionIsVisitingRecordType; 78 needConversionIsVisitingRecordType = true; 79 bool result = false; 80 for (auto t : recTy.getTypeList()) { 81 if (needsConversion(t.second)) { 82 result = true; 83 break; 84 } 85 } 86 // Only keep the result cached if the fir.type visited was a "top-level 87 // type". Nested types with a recursive reference to the "top-level type" 88 // may incorrectly have been resolved as not needed conversions because it 89 // had not been determined yet if the "top-level type" needed conversion. 90 // This is not an issue to determine the "top-level type" need of 91 // conversion, but the result should not be kept and later used in other 92 // contexts. 93 needConversionIsVisitingRecordType = wasAlreadyVisitingRecordType; 94 if (needConversionIsVisitingRecordType) 95 visitedTypes.erase(ty); 96 else 97 visitedTypes.find(ty)->second = result; 98 return result; 99 } 100 if (auto boxTy = mlir::dyn_cast<BaseBoxType>(ty)) 101 return needsConversion(boxTy.getEleTy()); 102 if (isa_ref_type(ty)) 103 return needsConversion(unwrapRefType(ty)); 104 if (auto t = mlir::dyn_cast<SequenceType>(ty)) 105 return needsConversion(unwrapSequenceType(ty)); 106 if (auto t = mlir::dyn_cast<TypeDescType>(ty)) 107 return needsConversion(t.getOfTy()); 108 return false; 109 } 110 111 BoxprocTypeRewriter(mlir::Location location) : loc{location} { 112 addConversion([](mlir::Type ty) { return ty; }); 113 addConversion( 114 [&](BoxProcType boxproc) { return convertType(boxproc.getEleTy()); }); 115 addConversion([&](mlir::TupleType tupTy) { 116 llvm::SmallVector<mlir::Type> memTys; 117 for (auto ty : tupTy.getTypes()) 118 memTys.push_back(convertType(ty)); 119 return mlir::TupleType::get(tupTy.getContext(), memTys); 120 }); 121 addConversion([&](mlir::FunctionType funcTy) { 122 llvm::SmallVector<mlir::Type> inTys; 123 llvm::SmallVector<mlir::Type> resTys; 124 for (auto ty : funcTy.getInputs()) 125 inTys.push_back(convertType(ty)); 126 for (auto ty : funcTy.getResults()) 127 resTys.push_back(convertType(ty)); 128 return mlir::FunctionType::get(funcTy.getContext(), inTys, resTys); 129 }); 130 addConversion([&](ReferenceType ty) { 131 return ReferenceType::get(convertType(ty.getEleTy())); 132 }); 133 addConversion([&](PointerType ty) { 134 return PointerType::get(convertType(ty.getEleTy())); 135 }); 136 addConversion( 137 [&](HeapType ty) { return HeapType::get(convertType(ty.getEleTy())); }); 138 addConversion([&](fir::LLVMPointerType ty) { 139 return fir::LLVMPointerType::get(convertType(ty.getEleTy())); 140 }); 141 addConversion( 142 [&](BoxType ty) { return BoxType::get(convertType(ty.getEleTy())); }); 143 addConversion([&](ClassType ty) { 144 return ClassType::get(convertType(ty.getEleTy())); 145 }); 146 addConversion([&](SequenceType ty) { 147 // TODO: add ty.getLayoutMap() as needed. 148 return SequenceType::get(ty.getShape(), convertType(ty.getEleTy())); 149 }); 150 addConversion([&](RecordType ty) -> mlir::Type { 151 if (!needsConversion(ty)) 152 return ty; 153 if (auto converted = convertedTypes.lookup(ty)) 154 return converted; 155 auto rec = RecordType::get(ty.getContext(), 156 ty.getName().str() + boxprocSuffix.str()); 157 if (rec.isFinalized()) 158 return rec; 159 [[maybe_unused]] auto it = convertedTypes.try_emplace(ty, rec); 160 assert(it.second && "expected ty to not be in the map"); 161 std::vector<RecordType::TypePair> ps = ty.getLenParamList(); 162 std::vector<RecordType::TypePair> cs; 163 for (auto t : ty.getTypeList()) { 164 if (needsConversion(t.second)) 165 cs.emplace_back(t.first, convertType(t.second)); 166 else 167 cs.emplace_back(t.first, t.second); 168 } 169 rec.finalize(ps, cs); 170 return rec; 171 }); 172 addConversion([&](TypeDescType ty) { 173 return TypeDescType::get(convertType(ty.getOfTy())); 174 }); 175 addSourceMaterialization(materializeProcedure); 176 addTargetMaterialization(materializeProcedure); 177 } 178 179 static mlir::Value materializeProcedure(mlir::OpBuilder &builder, 180 BoxProcType type, 181 mlir::ValueRange inputs, 182 mlir::Location loc) { 183 assert(inputs.size() == 1); 184 return builder.create<ConvertOp>(loc, unwrapRefType(type.getEleTy()), 185 inputs[0]); 186 } 187 188 void setLocation(mlir::Location location) { loc = location; } 189 190 private: 191 // Maps to deal with recursive derived types (avoid infinite loops). 192 // Caching is also beneficial for apps with big types (dozens of 193 // components and or parent types), so the lifetime of the cache 194 // is the whole pass. 195 llvm::DenseMap<mlir::Type, bool> visitedTypes; 196 bool needConversionIsVisitingRecordType = false; 197 llvm::DenseMap<mlir::Type, mlir::Type> convertedTypes; 198 mlir::Location loc; 199 }; 200 201 /// A `boxproc` is an abstraction for a Fortran procedure reference. Typically, 202 /// Fortran procedures can be referenced directly through a function pointer. 203 /// However, Fortran has one-level dynamic scoping between a host procedure and 204 /// its internal procedures. This allows internal procedures to directly access 205 /// and modify the state of the host procedure's variables. 206 /// 207 /// There are any number of possible implementations possible. 208 /// 209 /// The implementation used here is to convert `boxproc` values to function 210 /// pointers everywhere. If a `boxproc` value includes a frame pointer to the 211 /// host procedure's data, then a thunk will be created at runtime to capture 212 /// the frame pointer during execution. In LLVM IR, the frame pointer is 213 /// designated with the `nest` attribute. The thunk's address will then be used 214 /// as the call target instead of the original function's address directly. 215 class BoxedProcedurePass 216 : public fir::impl::BoxedProcedurePassBase<BoxedProcedurePass> { 217 public: 218 using BoxedProcedurePassBase<BoxedProcedurePass>::BoxedProcedurePassBase; 219 220 inline mlir::ModuleOp getModule() { return getOperation(); } 221 222 void runOnOperation() override final { 223 if (options.useThunks) { 224 auto *context = &getContext(); 225 mlir::IRRewriter rewriter(context); 226 BoxprocTypeRewriter typeConverter(mlir::UnknownLoc::get(context)); 227 getModule().walk([&](mlir::Operation *op) { 228 bool opIsValid = true; 229 typeConverter.setLocation(op->getLoc()); 230 if (auto addr = mlir::dyn_cast<BoxAddrOp>(op)) { 231 mlir::Type ty = addr.getVal().getType(); 232 mlir::Type resTy = addr.getResult().getType(); 233 if (llvm::isa<mlir::FunctionType>(ty) || 234 llvm::isa<fir::BoxProcType>(ty)) { 235 // Rewrite all `fir.box_addr` ops on values of type `!fir.boxproc` 236 // or function type to be `fir.convert` ops. 237 rewriter.setInsertionPoint(addr); 238 rewriter.replaceOpWithNewOp<ConvertOp>( 239 addr, typeConverter.convertType(addr.getType()), addr.getVal()); 240 opIsValid = false; 241 } else if (typeConverter.needsConversion(resTy)) { 242 rewriter.startOpModification(op); 243 op->getResult(0).setType(typeConverter.convertType(resTy)); 244 rewriter.finalizeOpModification(op); 245 } 246 } else if (auto func = mlir::dyn_cast<mlir::func::FuncOp>(op)) { 247 mlir::FunctionType ty = func.getFunctionType(); 248 if (typeConverter.needsConversion(ty)) { 249 rewriter.startOpModification(func); 250 auto toTy = 251 mlir::cast<mlir::FunctionType>(typeConverter.convertType(ty)); 252 if (!func.empty()) 253 for (auto e : llvm::enumerate(toTy.getInputs())) { 254 unsigned i = e.index(); 255 auto &block = func.front(); 256 block.insertArgument(i, e.value(), func.getLoc()); 257 block.getArgument(i + 1).replaceAllUsesWith( 258 block.getArgument(i)); 259 block.eraseArgument(i + 1); 260 } 261 func.setType(toTy); 262 rewriter.finalizeOpModification(func); 263 } 264 } else if (auto embox = mlir::dyn_cast<EmboxProcOp>(op)) { 265 // Rewrite all `fir.emboxproc` ops to either `fir.convert` or a thunk 266 // as required. 267 mlir::Type toTy = typeConverter.convertType( 268 mlir::cast<BoxProcType>(embox.getType()).getEleTy()); 269 rewriter.setInsertionPoint(embox); 270 if (embox.getHost()) { 271 // Create the thunk. 272 auto module = embox->getParentOfType<mlir::ModuleOp>(); 273 FirOpBuilder builder(rewriter, module); 274 auto loc = embox.getLoc(); 275 mlir::Type i8Ty = builder.getI8Type(); 276 mlir::Type i8Ptr = builder.getRefType(i8Ty); 277 mlir::Type buffTy = SequenceType::get({32}, i8Ty); 278 auto buffer = builder.create<AllocaOp>(loc, buffTy); 279 mlir::Value closure = 280 builder.createConvert(loc, i8Ptr, embox.getHost()); 281 mlir::Value tramp = builder.createConvert(loc, i8Ptr, buffer); 282 mlir::Value func = 283 builder.createConvert(loc, i8Ptr, embox.getFunc()); 284 builder.create<fir::CallOp>( 285 loc, factory::getLlvmInitTrampoline(builder), 286 llvm::ArrayRef<mlir::Value>{tramp, func, closure}); 287 auto adjustCall = builder.create<fir::CallOp>( 288 loc, factory::getLlvmAdjustTrampoline(builder), 289 llvm::ArrayRef<mlir::Value>{tramp}); 290 rewriter.replaceOpWithNewOp<ConvertOp>(embox, toTy, 291 adjustCall.getResult(0)); 292 opIsValid = false; 293 } else { 294 // Just forward the function as a pointer. 295 rewriter.replaceOpWithNewOp<ConvertOp>(embox, toTy, 296 embox.getFunc()); 297 opIsValid = false; 298 } 299 } else if (auto global = mlir::dyn_cast<GlobalOp>(op)) { 300 auto ty = global.getType(); 301 if (typeConverter.needsConversion(ty)) { 302 rewriter.startOpModification(global); 303 auto toTy = typeConverter.convertType(ty); 304 global.setType(toTy); 305 rewriter.finalizeOpModification(global); 306 } 307 } else if (auto mem = mlir::dyn_cast<AllocaOp>(op)) { 308 auto ty = mem.getType(); 309 if (typeConverter.needsConversion(ty)) { 310 rewriter.setInsertionPoint(mem); 311 auto toTy = typeConverter.convertType(unwrapRefType(ty)); 312 bool isPinned = mem.getPinned(); 313 llvm::StringRef uniqName = 314 mem.getUniqName().value_or(llvm::StringRef()); 315 llvm::StringRef bindcName = 316 mem.getBindcName().value_or(llvm::StringRef()); 317 rewriter.replaceOpWithNewOp<AllocaOp>( 318 mem, toTy, uniqName, bindcName, isPinned, mem.getTypeparams(), 319 mem.getShape()); 320 opIsValid = false; 321 } 322 } else if (auto mem = mlir::dyn_cast<AllocMemOp>(op)) { 323 auto ty = mem.getType(); 324 if (typeConverter.needsConversion(ty)) { 325 rewriter.setInsertionPoint(mem); 326 auto toTy = typeConverter.convertType(unwrapRefType(ty)); 327 llvm::StringRef uniqName = 328 mem.getUniqName().value_or(llvm::StringRef()); 329 llvm::StringRef bindcName = 330 mem.getBindcName().value_or(llvm::StringRef()); 331 rewriter.replaceOpWithNewOp<AllocMemOp>( 332 mem, toTy, uniqName, bindcName, mem.getTypeparams(), 333 mem.getShape()); 334 opIsValid = false; 335 } 336 } else if (auto coor = mlir::dyn_cast<CoordinateOp>(op)) { 337 auto ty = coor.getType(); 338 mlir::Type baseTy = coor.getBaseType(); 339 if (typeConverter.needsConversion(ty) || 340 typeConverter.needsConversion(baseTy)) { 341 rewriter.setInsertionPoint(coor); 342 auto toTy = typeConverter.convertType(ty); 343 auto toBaseTy = typeConverter.convertType(baseTy); 344 rewriter.replaceOpWithNewOp<CoordinateOp>(coor, toTy, coor.getRef(), 345 coor.getCoor(), toBaseTy); 346 opIsValid = false; 347 } 348 } else if (auto index = mlir::dyn_cast<FieldIndexOp>(op)) { 349 auto ty = index.getType(); 350 mlir::Type onTy = index.getOnType(); 351 if (typeConverter.needsConversion(ty) || 352 typeConverter.needsConversion(onTy)) { 353 rewriter.setInsertionPoint(index); 354 auto toTy = typeConverter.convertType(ty); 355 auto toOnTy = typeConverter.convertType(onTy); 356 rewriter.replaceOpWithNewOp<FieldIndexOp>( 357 index, toTy, index.getFieldId(), toOnTy, index.getTypeparams()); 358 opIsValid = false; 359 } 360 } else if (auto index = mlir::dyn_cast<LenParamIndexOp>(op)) { 361 auto ty = index.getType(); 362 mlir::Type onTy = index.getOnType(); 363 if (typeConverter.needsConversion(ty) || 364 typeConverter.needsConversion(onTy)) { 365 rewriter.setInsertionPoint(index); 366 auto toTy = typeConverter.convertType(ty); 367 auto toOnTy = typeConverter.convertType(onTy); 368 rewriter.replaceOpWithNewOp<LenParamIndexOp>( 369 index, toTy, index.getFieldId(), toOnTy, index.getTypeparams()); 370 opIsValid = false; 371 } 372 } else { 373 rewriter.startOpModification(op); 374 // Convert the operands if needed 375 for (auto i : llvm::enumerate(op->getResultTypes())) 376 if (typeConverter.needsConversion(i.value())) { 377 auto toTy = typeConverter.convertType(i.value()); 378 op->getResult(i.index()).setType(toTy); 379 } 380 381 // Convert the type attributes if needed 382 for (const mlir::NamedAttribute &attr : op->getAttrDictionary()) 383 if (auto tyAttr = llvm::dyn_cast<mlir::TypeAttr>(attr.getValue())) 384 if (typeConverter.needsConversion(tyAttr.getValue())) { 385 auto toTy = typeConverter.convertType(tyAttr.getValue()); 386 op->setAttr(attr.getName(), mlir::TypeAttr::get(toTy)); 387 } 388 rewriter.finalizeOpModification(op); 389 } 390 // Ensure block arguments are updated if needed. 391 if (opIsValid && op->getNumRegions() != 0) { 392 rewriter.startOpModification(op); 393 for (mlir::Region ®ion : op->getRegions()) 394 for (mlir::Block &block : region.getBlocks()) 395 for (mlir::BlockArgument blockArg : block.getArguments()) 396 if (typeConverter.needsConversion(blockArg.getType())) { 397 mlir::Type toTy = 398 typeConverter.convertType(blockArg.getType()); 399 blockArg.setType(toTy); 400 } 401 rewriter.finalizeOpModification(op); 402 } 403 }); 404 } 405 } 406 407 private: 408 BoxedProcedureOptions options; 409 }; 410 } // namespace 411